My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Read and Write Data to Local JSON File with NodeJS

Read and Write Data to Local JSON File with NodeJS

Pankaj Kumar's photo
Pankaj Kumar
·Jan 16, 2022·

2 min read

While working with NodeJS, We may need to work with the local JSON file.

In this article, We will see writing data to a local JSON file with NodeJS application. Let's start step by step:

1.Create an empty JSON file named posts.json

{

"posts": []

}

2.Read data from JSON file

Here we will read the JSON file and store the data into a variable after parsing it.

var fs = require('fs');

fs.readFile('./posts.json', 'utf-8', function(err, data) {

    if (err) throw err

    let postsArr = JSON.parse(data) })

3.In the parsed data push the new data.

create/modify the data which is needed to write into the JSON file. For simplicity, I am creating a single object.

const newPostObj = 

{

        id: 12,

        authorId: 242,

        title : "11unt aut facere repellat provident occaecati excepturi optio reprehenderit",

        body :"22uia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"

    }

4.Push the new object to the parsed data of the posts.json file, If you have multiple objects(Array of objects) to write into the file then in the below code you will need to create the loop so that each object will be pushed in the postsArr variable.

postsArr .posts.push(newPostObj)

5.Write the updated data into posts.json file

   fs.writeFile('./posts.json', JSON.stringify(postsArr), 'utf-8', function(err) {

        if (err) throw err

        console.log('JSON file successfully updated');

    })

Let's see the complete code:

var fs = require('fs')

fs.readFile('./posts.json', 'utf-8', function(err, data) {
    if (err) throw err

    var arrayOfObjects = JSON.parse(data)
    arrayOfObjects.posts.push({
        id: 12,
        authorId: 242,
        title : "11unt aut facere repellat provident occaecati excepturi optio reprehenderit",
        body :"22uia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    })

    console.log(arrayOfObjects)

    fs.writeFile('./posts.json', JSON.stringify(arrayOfObjects), 'utf-8', function(err) {
        if (err) throw err
        console.log('JSON file updated successfully!')
    })
})

I hope this article helped you to write JSON file with NodeJS. Click here to read more articles on NodeJS.

Click here to Read How to Read Local JSON file in Angular

Thanks!