Home > Article > Web Front-end > How to Access JSON Data in Node.js Server Memory?
Accessing JSON Data in Node.js Server Memory
In the realm of Node.js development, it often becomes necessary to access JSON objects residing in external files into server memory for quick retrieval.
To accomplish this task, you have two primary options: reading from a text file or a JS file. The choice between the two depends on your specific needs and preferences.
To read a JSON object from a text file into server memory using JavaScript/Node, follow these steps:
Synchronous Approach:
Asynchronous Approach:
For your convenience, here are code snippets for both approaches:
Synchronous:
var fs = require('fs'); var obj = JSON.parse(fs.readFileSync('file', 'utf8'));
Asynchronous:
var fs = require('fs'); var obj; fs.readFile('file', 'utf8', function (err, data) { if (err) throw err; obj = JSON.parse(data); });
Once you have loaded the JSON object into memory, you can access its properties and values directly from your JavaScript code, enabling efficient data retrieval and processing within your Node.js server.
The above is the detailed content of How to Access JSON Data in Node.js Server Memory?. For more information, please follow other related articles on the PHP Chinese website!