HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How do I read a JSON file into (server) memory?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howjsonserverfilememoryintoread

Problem

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.

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

Solution

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

Code Snippets

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

Context

Stack Overflow Q#10011011, score: 1596

Revisions (0)

No revisions yet.