0

Hello I'm trying to read a JSON file using nodejs and when I try to access one of the properties they come back as undefined. However, when I console.log the entire file is shows up.

var keyFile;

function setKeys(callback){
  const fs = require('fs');
  const filePath = '../KEY.json';
  fs.readFile(filePath, 'utf-8', (error, data) => {
    if (error){
      return console.log(error);
    }
    keyFile = data;
    callback();
  });
}

setKeys(()=>{
             console.log(keyFile) // shows JSON
             console.log(keyFile.google) //undefined
            }); 

KEY.json:

{
  "darksky": "ab",
  "google": "cd"
} 

1 Answer 1

1

Doesn't look like you're parsing it anywhere. data will be a string, so change:

keyFile = data;

to

keyFile = JSON.parse(data);

Side note: Instead of using a module global, I'd strongly recommend passing the data to the callback as an argument:

// *** No var keyFile; here

function setKeys(callback){
  const fs = require('fs');
  const filePath = '../KEY.json';
  fs.readFile(filePath, 'utf-8', (error, data) => {
    if (error){
      return console.log(error);
    }
    callback(JSON.parse(data)); // ***
  });
}

setKeys(keyFile => {            // ***
  console.log(keyFile.google);
}); 
Sign up to request clarification or add additional context in comments.

1 Comment

@Nigel: No worries. I should also have mentioned that you can read JSON via require if you like. For instance, this works: const keyFile = requre("../KEY.json"); console.log(keyFile.google); I don't recommend it, but you'll see people do it, so I figured I should flag it up.

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.