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

## The Question :

673 people think this question is useful

## Background

I am doing some experimentation with Node.js and would like to read a JSON object, either from a text file or a .js file (which is better??) into memory so that I can access that object quickly from code. I realize that there are things like Mongo, Alfred, etc out there, but that is not what I need right now.

## Question

How do I read a JSON object out of a text or js file and into server memory using JavaScript/Node?

1276 people think this answer is useful

Sync:

var fs = require('fs');

Async:

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

417 people think this answer is useful

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

58 people think this answer is useful

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

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

// Declare variables
var fs = require('fs'),
obj

// Read the file and send to the callback

// Write the callback function
function handleFile(err, data) {
if (err) throw err
obj = JSON.parse(data)
// You can now play with your datas
}

45 people think this answer is useful

At least in Node v8.9.1, you can just do

var json_data = require('/path/to/local/file.json');

and access all the elements of the JSON object.

17 people think this answer is useful

In Node 8 you can use the built-in util.promisify() to asynchronously read a file like this

const {promisify} = require('util')
const fs = require('fs')

readFileAsync(\${__dirname}/my.json, {encoding: 'utf8'})
.then(contents => {
const obj = JSON.parse(contents)
console.log(obj)
})
.catch(error => {
throw error
})

8 people think this answer is useful

using node-fs-extra (async await)

const readJsonFile = async () => {
try {
console.log(myJsonObject);
} catch (err) {
console.error(err)
}
}

7 people think this answer is useful

Using fs-extra package is quite simple:

Sync:

const fs = require('fs-extra')

console.log(packageObj.version)

Async:

const fs = require('fs-extra')

console.log(packageObj.version)

3 people think this answer is useful
function parseIt(){
return new Promise(function(res){
try{
var fs = require('fs');
const dirPath = 'K:\\merge-xml-junit\\xml-results\\master.json';
if(err) throw err;
res(data);
})}
catch(err){
res(err);
}
});
}

async function test(){
jsonData = await parseIt();
var parsedJSON = JSON.parse(jsonData);
var testSuite = parsedJSON['testsuites']['testsuite'];
console.log(testSuite);
}

test();

2 people think this answer is useful
var fs = require('fs');

if (err) throw err;
console.log(data);
});

// options

You can find all usage of Node.js at the File System docs!
hope this help for you!

0 people think this answer is useful

So many answers, and no one ever made a benchmark to compare sync vs async vs require. I described the difference in use cases of reading json in memory via require, readFileSync and readFile here.

-1 people think this answer is useful

If you are looking for a complete solution for Async loading a JSON file from Relative Path with Error Handling

// Global variables
// Request path module for relative path
const path = require('path')
// Request File System Module
var fs = require('fs');

// GET request for the /list_user page.
router.get('/listUsers', function (req, res) {
console.log("Got a GET request for list of users");

// Create a relative path URL
let reqPath = path.join(__dirname, '../mock/users.json');

//Read JSON from relative path of this file
fs.readFile(reqPath , 'utf8', function (err, data) {
//Handle Error
if(!err) {
//Handle Success
console.log("Success"+data);
// Parse Data to JSON OR
var jsonObj = JSON.parse(data)
//Send back as Response
res.end( data );
}else {
//Handle Error
res.end("Error: "+err )
}
});
})

Directory Structure: