JSON Parsing in Node

JSON parsing in Node

The readFile method can be used to read json files. It asynchronously reads the contents of the entire file in memory and is therefore not the most optimal approach to this.

fs.readFile(path, options, callback);

The first argument path is the filename of file descriptor.

The second is an optional object argument.

Third is a callback function.

The callback function takes 2 arguments.

err
data

Example code :

const fs = require('fs');

fs.readFile('data.json', function(err, data) { 

    if (err) throw err; 

    const cartData = JSON.parse(data); 
    console.log(cartData); 
});