0

I have a Node app. In this app, I have a directory structure like this:

library/
  ents/
    index.js
index.js
package.json
settings.json

My settings.json file looks like this:

settings.json

{
  "url":"http://www.example.com"
}

There's more in the file, but that's not relevant to this question. In the ./library/ents/index.js file I have the following:

let settings = require('../../settings');
console.log(settings);

This executes. But, I was expecting to see the contents of the settings.json file printed out. Instead, I just see {}. I really don't understand why this would happen.

2
  • 1
    Have you tried the requiring with the JSON file with the .json file ending, like require('../../settings.json')? Commented Apr 22, 2016 at 13:20
  • I reproduced your folder structure and copy-pasted your json and code, it works fine. Are you sure your json file is not empty? Did you try using an absolute path? Commented Apr 22, 2016 at 13:45

2 Answers 2

2

require is for loading amd modules, not for reading json in this manner, if you wish to keep yout file as true json, you can try something like:

var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('file', 'utf8'));

Taken from Using Node.JS, how do I read a JSON object into (server) memory?

Sign up to request clarification or add additional context in comments.

2 Comments

Just a reminder - better wrap it in try/catch, both FS operations and JSON.parse may throw exceptions.
require() is commonly used to load/parse JSON files, you can see an example in npm's doc.
0

You could change settings.json to settings.js which looks like this:

module.exports = {
  "url":"http://www.example.com"
}

then

let settings = require('../../settings');

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.