Nigel
Nigel

Reputation: 33

Reading JSON file undefined (asynchronous)

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"
} 

Upvotes: 0

Views: 1635

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075447

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);
}); 

Upvotes: 1

Related Questions