DEV Community

Cover image for Read and Write Data to Local JSON File with NodeJS
Pankaj Kumar
Pankaj Kumar

Posted on

Read and Write Data to Local JSON File with NodeJS

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": []

}
Enter fullscreen mode Exit fullscreen mode

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) })
Enter fullscreen mode Exit fullscreen mode

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"

    }
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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');

    })
Enter fullscreen mode Exit fullscreen mode

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!')
    })
})
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)