How to use File System Module In Javascript

We are going to use a File System Module (“fs”). File System Module provides a different different functions to read and write the data to the file. We can use fs.readFileSync(file_name) or fs.readFile(file_name) function to read the content of the data.json file.

Once the data is read from the file. we will parse it into a JavaScript object using JSON.parse() method. JSON.parse() method will converts the JSON string into a JavaScript object. After parsing the JSON data, we can manipulate the JavaScript object like any other object.

Once the data is updated, we will convert the JavaScript object back to a JSON string using JSON.stringify() method. After that we will use fs.writeFileSync() or fs.writeFile() function to write the updated JSON data back to the file.

Note: fs.readFile(file_name) and fs.writeFile() are asynchronous, so we have to handle it using callback functions, promises or the async/await syntax.

Syntax:

const fs = require('fs');

// Read the JSON file
let rawData = fs.readFileSync('data.json');
let jsonData = JSON.parse(rawData);

// Update the data
jsonData.key = 'new value';

// Write the updated data back to the file
fs.writeFileSync('data.json', JSON.stringify(jsonData));

Before Updating data.json file:

{
"key": "old value"
}

After Updating data.json file:

{
"key": "new value"
}

Example : The below example demonstrate updating data in json file using file system module

JavaScript
//File path: /index.js

const fs = require('fs');

// Define the file path
const filePath = 'data.json';

// Read the JSON file
fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    
    try {
        // Parse the JSON data
        const jsonData = JSON.parse(data);

        // Display the original data
        console.log('Before updating JSON:');
        console.log(jsonData);

        // Update the data
        jsonData.forEach(item => {
            item.programmingLanguage.push('JavaScript');
        });

        // Display the updated data
        console.log('\nAfter updating JSON:');
        console.log(jsonData);

        // Write the updated data back to the file
        fs.writeFile(filePath, JSON.stringify(jsonData), (err) => {
            if (err) {
                console.error('Error writing file:', err);
                return;
            }
            console.log('\nData updated successfully.');
        });
    } catch (error) {
        console.error('Error parsing JSON data:', error);
    }
});
JavaScript
//File path: data.json (note: remove this comment line)

[
    { "name": "John", "programmingLanguage": ["Python"] },
    { "name": "Alice", "programmingLanguage": ["C++"] }
]

To run the application use the following command:

node index.js 

Output:

Before updating JSON:
[
{ name: 'John', programmingLanguage: [ 'Python' ] },
{ name: 'Alice', programmingLanguage: [ 'C++' ] }
]

After updating JSON:
[
{ name: 'John', programmingLanguage: [ 'Python', 'JavaScript' ] },
{ name: 'Alice', programmingLanguage: [ 'C++', 'JavaScript' ] }
]

Data updated successfully.


How to Update Data in JSON File using JavaScript ?

JSON stands for JavaScript Object Notation. It is a text-based data exchange format that allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and then writing the updated data back to the file.

Table of Content

  • Using require() Method
  • Using File System Module

Similar Reads

Using require() Method

We are going to use a Direct Approach, In this approach we can directly import the json data file and update like we normally update the JavaScript object. In last to update the changes in a Json file that we have made, we need to use a writeFileSync() function of a File System Module to update the changes....

Using File System Module

We are going to use a File System Module (“fs”). File System Module provides a different different functions to read and write the data to the file. We can use fs.readFileSync(file_name) or fs.readFile(file_name) function to read the content of the data.json file....

Contact Us