In the realm of Node.js development, you may encounter the need to rapidly access JSON objects stored in text or .js files. While database solutions exist, they may not be suitable for your immediate requirements. This article explores two methods to read JSON objects into server memory using JavaScript/Node.
For synchronous file operations, use the fs.readFileSync function:
<code class="javascript">var fs = require('fs'); var obj = JSON.parse(fs.readFileSync('file', 'utf8'));</code>
This code reads the file into memory and parses it into a JavaScript object.
For asynchronous file operations, employ the fs.readFile function:
<code class="javascript">var fs = require('fs'); var obj; fs.readFile('file', 'utf8', function (err, data) { if (err) throw err; obj = JSON.parse(data); });</code>
Here, a callback function is used to handle the file data and parse it into an object, providing a non-blocking approach.
The above is the detailed content of How to Efficiently Read JSON Files into Server Memory in Node.js?. For more information, please follow other related articles on the PHP Chinese website!