Write / add data in JSON file using Node.js

Cover Image for Write / add data in JSON file using Node.js
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

How to Write and Add Data in a JSON File using Node.js

Are you struggling to write and add data to a JSON file using Node.js? Look no further! In this guide, we will walk you through a step-by-step process to help you achieve your goal. 📝💻

The Problem

Let's start by addressing the problem at hand. The original code provided in the question uses the jsonfile module to write data to a JSON file. However, each time the code runs, it overwrites the existing data in the file instead of adding new elements. The desired output is a JSON file with an array of objects, where each object represents the ID and square of a number.

The Solution

To solve this problem, we will use the built-in fs module in Node.js. This module provides file system-related functionality, allowing us to read, write, and modify files.

Here's an updated version of the code that will give you the desired output:

const fs = require('fs');

// Check if the file exists
fs.exists('myjsonfile.json', function(exists) {
    if (exists) {
        console.log("File exists");
        fs.readFile('myjsonfile.json', function readFileCallback(err, data) {
            if (err) {
                console.log(err);
            } else {
                let obj = JSON.parse(data);
                for (let i = 0; i < 5; i++) {
                    obj.table.push({
                        id: i,
                        square: i * i
                    });
                }
                let json = JSON.stringify(obj);
                fs.writeFile('myjsonfile.json', json);
            }
        });
    } else {
        console.log("File does not exist");
        let obj = {
            table: []
        };
        for (let i = 0; i < 5; i++) {
            obj.table.push({
                id: i,
                square: i * i
            });
        }
        let json = JSON.stringify(obj);
        fs.writeFile('myjsonfile.json', json);
    }
});

In this updated code, we first check if the file myjsonfile.json exists. If it does, we read its content and parse it into a JavaScript object. We then loop through the data and add new elements to the table array. Finally, we convert the updated object back into a JSON string and write it back to the file.

If the file does not exist, we create a new object and follow the same steps as above to add the elements. This ensures that the code can be re-run multiple times without losing the existing data.

Conclusion

Congratulations! 🎉 You now know how to write and add data to a JSON file using Node.js. By using the fs module and following the example code provided, you can easily achieve your desired output.

Feel free to experiment with the code and customize it to fit your specific needs. If you have any questions or need further assistance, drop a comment below and we'll be happy to help!

Now it's your turn to try it out. Let's write some data to JSON files! 💪😊


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello