Read and write a JSON file in Node.js

— 4 minute read

Reading and writing files in Node.js

Ever needed to write a file in node.js? Of course, I've heard of databases, but sometimes it's just way easier to write a small json file. 🔥

Creating a basic node.js app permalink

To read and write files in node.js we need to include the file system package in our application.

First, we will create a basic application to test this. Open up your terminal and execute the following command.

Read more: Basic Node.js Express application

Note: Make sure you have node.js installed on your machine see nodejs website for the installation procedure.

mkdir fs-app && cd fs-app && npm init

This will create a directory called fs-app, make the terminal change into this directory, and then execute the npm init function.

npm init will create a default starting app for node.js.

Now we need to create our application index file. Open your favorite terminal and create an index.js file.

Installing file system package in node.js permalink

To install the package, all we have to include in our index.js file is the following code:

const fs = require('fs');

All this does is tell our application we are planning to use the fs package.

Reading a json file in node.js permalink

To read a file, we will start by creating our demo file. Create a file called people.json and place the following content in it.

{
"people": [
{
"firstname": "Chris",
"lastname": "Bongers"
}
]
}

Now we add the following code to our index.js

let rawdata = fs.readFileSync('people.json');
let people = JSON.parse(rawdata);
console.log(people);

If we now run node index.js in our terminal we should see our json people object logged. 👏

Writing data to a json file in node.js permalink

To write data back to the file, we will manipulate the contents of our json object, let's add another person and try and save that back to the json file.

people.people.push({
'firstname': 'Steve',
'lastname': 'Jobs'
});

fs.writeFileSync('people.json', JSON.stringify(people));

We use people.people because our index in the json is called people as well as the object we created. Then we tell the fs package to write to the people.json file the newly adjusted object.

Now, if we rerun node index.js and open our people.json file, we should see two entries!

Congrats, you just read and write a json file in node.js

You can find this project on GitHub

Let me know what you think! permalink

I love it when people get in touch with me and let me know what topics they are interested in. Reach out to me on Facebook or Twitter!