It’s possible to read and write JSON files in Node.js. All you need to do is utilize the fs Module as detailed in our easy-to-follow guide.

Reading and Writing JSON files in Node.js

The JavaScript Object Notation format, popularly known as JSON, is a lightweight data-transfer format widely used for representing structured data. It is a text-based format that is easy for humans to read and write and for machines to parse and generate.

The ability to programmatically read and write JSON files in Node.js allows you to store, exchange, and manipulate structured data efficiently and easily. Learn how to read, write, and update JSON files using the Node.js file system module.

The Node.js File System Module

The Node.js file system (fs) module is built into Node.js. It lets you interact with the file system on your device. you may use it to read the contents of a file, create a new file, and delete a file, among other things.

The methods provided by thefsmodule can either besynchronous or asynchronous. Synchronous methods block the execution of your program until the file system operation is complete. These methods usually have “Sync” at the end of their names. For example,readFileSyncorwriteFileSync.

On the other hand, asynchronous methods do not block the execution of your program and allow it to continue processing other tasks while the file system operation is being performed. These methods accept a callback function that will run when the operation is complete. For example,readFileorwriteFile.

When interacting with the file system, you should always use asynchronous methods to maintain the non-blocking nature of the event loop and improve your application’s performance and responsiveness.

However, synchronous methods have their place in certain scenarios, especially when you’re writing simple scripts or dealing with one-time file operations.

Reading JSON Files With the fs Module

To read a JSON file, first import the asynchronousfsmodule into your main file. Like so:

If you are using a version lower thanNode.js v18, import thefsmodule like this:

If you want to import the entire module (Synchronous and Asynchronous), remove the/promises.

You can read a JSON file using thereadFilemethod which takes two arguments: a file path and an optional configuration object. The config argument specifies options for reading the file and can be an object with options or a string encoding.

The object options include:

For example:

This code reads a JSON file calledusers.jsonin the current directory. When you retrieve the file’s data, you’re able to parse it from JSON into a JavaScript object usingJSON.parse. This allows you to access and manipulate the data as an object in your code.

For small JSON files, you can userequireto read them synchronously. This method automatically parses JSON files into JavaScript objects. For larger JSON files and in non-blocking scenarios, usefs.readFileto read them asynchronously. Additionally, usingrequirealso caches the file contents in memory, so it might not be ideal if your JSON file changes a lot.

Writing JSON Files With the fs Module

You can write data to JSON files using thewriteFilemethod. This method takes three arguments:

This method asynchronously writes data to a file. If the file exists, it overwrites the existing content with the new content. If the file doesn’t exist, it creates it and populates it with the data you pass as an argument.

The data you pass into the writeFile function has to be a string or a buffer, so if you want to write an object to the file, you must first convert it into a string using theJSON.stringifymethod.

Updating JSON Files With the fs Module

Thefsmodule doesn’t provide an explicit way to update files, as writing a file overwrites any existing data.

To work around this, you can update a file by first getting the existing content from the file using thereadFilemethod. Then, you can add the existing data to your current data and pass it as your data argument in thewriteFilemethod.

Here’s a function that implements the logic above:

You can call the function like so:

This code block will add the users with the information above to the existingusers.jsonfile.

Security Considerations for Reading and Writing JSON Files

Safeguarding your Node.js application when reading and writing JSON files involves crucial security considerations. You should always validate the JSON data to ensure it conforms to your expectations. You should also restrict file access permissions and sanitize user input to thwart potential vulnerabilities like code injection.