0

I am trying to access a nested JSON object, but I am getting Cannot read property 'module' of undefined.

Here is the JSON file.

{
  "server": {
    "module": {
      "InPluginPath": "/usr/home/nah/Website/server/httpModule.js"
    }
  }
}

Then when I try to access the JSON object after reading the file with fs.readFile(), I get the Cannot read property 'module' of undefined, error. Below is the line that causes the error.

console.log(config.server.module.InPluginPath);
1
  • Please show the specific code you use with fs.readFile(). Do you know that require() will load and parse a .json file for you automatically. Commented May 21, 2015 at 1:49

1 Answer 1

1

You need to JSON.parse() the resulting string from fs.readFile(). For example:

fs.readFile('/tmp/foo.json', { encoding: 'utf8' }, function(err, data) {
  if (err) throw err;
  try {
    data = JSON.parse(data);
  } catch (ex) {
    console.log('Error parsing json');
    return;
  }
  console.log(data.server.module.InPluginPath);
});
Sign up to request clarification or add additional context in comments.

4 Comments

Or, you could load it as a module with require() and it will get parsed automatically.
@jfriend00 Except require() will cache the result, just like modules, and save it in memory. This is not desirable in all cases. Additionally the OP had already mentioned using fs.readFile(), so I thought it was more fitting.
Its not a criticism, but a suggestion for something you could add to your answer to make it more complete.
Your console.log() statement isn't using the parsed results. Maybe want to correct that.

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.