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.

JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134
  • 1
    Have you tried the requiring with the JSON file with the `.json` file ending, like `require('../../settings.json')`? – helpermethod Apr 22 '16 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? – Shanoor Apr 22 '16 at 13:45

2 Answers2

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?

Community
  • 1
  • 1
CosmicChild
  • 181
  • 8
  • 1
    Just a reminder - better wrap it in try/catch, both FS operations and JSON.parse may throw exceptions. – jkondratowicz Apr 22 '16 at 13:19
  • 1
    `require()` is commonly used to load/parse JSON files, you can see an example in [npm's doc](https://docs.npmjs.com/files/package.json). – Shanoor Apr 22 '16 at 13:41
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');
HK JR
  • 260
  • 1
  • 8