Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 409
Matt Cashatt Avatar asked Apr 04 '12 12:04

Matt Cashatt


People also ask

How is JSON stored in memory?

In the preceding representation of JSON, it is clearly identified that the value received is not a string but an object; to be more precise, it is a JavaScript object notation. Now, the notion of storage of JSON in memory is the same as the JavaScript object.

How do I save JSON data in node JS?

To save the JSON object to a file, we stringify the json object jsonObj and write it to a file using Node FS's writeFile() function.


1 Answers

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); }); 
like image 68
mihai Avatar answered Oct 05 '22 22:10

mihai