Using Node.JS, how do I read a JSON file into (server) memory? Using Node.JS, how do I read a JSON file into (server) memory? javascript javascript

Using Node.JS, how do I read a JSON file into (server) memory?


Sync:

var fs = require('fs');var obj = JSON.parse(fs.readFileSync('file', 'utf8'));

Async:

var fs = require('fs');var obj;fs.readFile('file', 'utf8', function (err, data) {  if (err) throw err;  obj = JSON.parse(data);});


The easiest way I have found to do this is to just use require and the path to your JSON file.

For example, suppose you have the following JSON file.

test.json

{  "firstName": "Joe",  "lastName": "Smith"}

You can then easily load this in your node.js application using require

var config = require('./test.json');console.log(config.firstName + ' ' + config.lastName);


Asynchronous is there for a reason! Throws stone at @mihai

Otherwise, here is the code he used with the asynchronous version:

// Declare variablesvar fs = require('fs'),    obj// Read the file and send to the callbackfs.readFile('path/to/file', handleFile)// Write the callback functionfunction handleFile(err, data) {    if (err) throw err    obj = JSON.parse(data)    // You can now play with your datas}