In Node.js, you can read a JSON file into memory using the built-in fs (File System) module to read the file content and then use JSON.parse to parse the JSON data. Here's a simple example:
Explanation:
fs.readFile: Reads the content of the file specified byfilePath.'utf8': Specifies the file encoding. This is important when reading text files.- The callback function is called once the file is read. If there's an error, it's logged. If not, the data is passed to
JSON.parse. JSON.parse: Parses the JSON data into a JavaScript object.
Make sure to replace 'path/to/your/file.json' with the actual path to your JSON file.
Keep in mind that reading files is an asynchronous operation in Node.js, and the callback function is used to handle the results. If you're working with modern JavaScript, you can also use util.promisify or the fs.promises API for a more synchronous-like code structure.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.