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?

2 min read
javascript
json
node.js

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?

Photo by Sven Schlager | Unsplash
3 posted solutions
1.5K

mihai wrote:

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

Travis Tidwell wrote:

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

Florian Ledermann wrote:

Answer for 2022, using ES6 module syntax and async/await

In modern JavaScript, this can be done as a one-liner, without the need to install additional packages:

import { readFile } from 'fs/promises';

let data = JSON.parse(await readFile("filename.json", "utf8"));

Add a try/catch block to handle exceptions as needed.

Submit your solution

© 2023 Dev's Feed