I have seen different method to read JSON files in Nodejs, like this:
Using FS library
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); });
Source : https://mcmap.net/q/53620/-using-node-js-how-do-i-read-a-json-file-into-server-memory
Using require()
let data = require('/path/file.json');
Using Ajax request
There might have any other ways. But I heard when reading JSON file using Method 1 is efficient than other methods.
I'm developing a module where I have to read a JSON file when each client side request and I'm currently using Method 1. This is a banking application and performance matters, so help me to find which way is good to use this scenario.
JSON.parse
itself. It requires that you load the whole file in aString
(plus, JavaScript uses UTF16 so double the memory usage) and blind JSON parsing is quite slow. If your input is an array or dictionary you can 1) stream the JSON parsing so you can start working before you've loaded the whole file, 2) filter while parsing so you only generate the objects you want. – Percy