1

I want to read properties from a config file - in a key value pair format from my main.js

I have a config file config.json

{
 "IGUrl": "xyz",
 "Key": "abc",
 "dbName": "node-login"
}

I want to read the property say "IGUrl" from my app.js.

The code to access and read this file is

    var config  = require('./config.json');
    var x = config.IGUrl;
    console.log("TEST URL " + x)

But this is giving me an error Uncaught TypeError: Cannot read property 'IGUrl' of undefined

6
  • 2
    Have you tried JSON.parse after require the file? Commented Oct 30, 2019 at 16:24
  • var { config } = require('./config.json') you are not importing correctly. If you would import correctly it will work. In config file you need module.exports = objectThatYouAreExporting Commented Oct 30, 2019 at 16:24
  • Hmm, I thought it was the JSON.parse() as well, but just tested this on my node and apparently requiring a json file automatically parses it. So your posted code works for me. Which version of node.js are you running since iirc, requiring a json file is a relatively recent addition. Commented Oct 30, 2019 at 16:30
  • The user is importing a JSON file, no a JS module in some kind of module format. So exporting should not matter. And it seems requiring a json file has been in node since 0.5. I just copy pasted the OP code and everything works for me as expected on node v12.2.0 . Are you running this on the client? Or with a non-node version of require() ? Commented Oct 30, 2019 at 16:34
  • What version of Nodejs are you using @psd and is config.json in same directory as main.js Commented Oct 30, 2019 at 17:03

2 Answers 2

1

You can just use a common JS file instead. Is much easier and there is no need to do anything special other than accessing the file.

export const properties = {
    IGUrl: "xyz",
    Key: "abc",
    dbName: "node-login"
};

export default properties;

Then whenever you need to access it, just use the following code.

import properties from './path/properties';

console.log(properties.IGUrl);
Sign up to request clarification or add additional context in comments.

Comments

0

Since this code is on client side, the require statement wouldn't work. I just had to have the config file in my html file and reference it directly in my main.js

config.js

const properties = {
    url: "xyz",
    key: "abc",
    dbName: "node-login"
    };

main.js

console.log("TEST " + properties.url);

index.html

<script src="/config.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.