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?
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.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With