George George - 6 months ago 15
JSON Question

access json stucture from another file

I am trying to create a configuration file in order to use some fields in my files.

So, in the config file ( myconfig.json ) :

var fs = require('fs');
var path = require('path');

var Struct = {

FIELD: 1

};

var Data = JSON.stringify(Struct);

fs.writeFile(__dirname + '/myconfig.json', Data, function (err) {

if (err) {

console.log('There has been an error.');
console.log(err.message);
return;
}

console.log('Configuration saved successfully.')
});


In another js file :

var path = require('path');
var fs = require('fs');


var Data = fs.readFileSync( __dirname + '/myconfig.json');


console.log("res = ", Data.FIELD);


but it prints
undefined
.

Answer

Ok, the error was that the first code is a javascript file and not a json .

So, I need to have the myconfig.json :

{ 

   "FIELDS" : 1
}

and use :

var Data = JSON.parse(fs.readFileSync( './myconfig.json'));