YouTube Icon

Code Playground.

Read and Write Data to Local JSON File with NodeJS

CFG

Read and Write Data to Local JSON File with NodeJS

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

In this composition, We'll see writing data to a original JSON file with NodeJS operation. Let's start step by step 

1. produce an empty JSON file namedposts.json 

{
"posts": []
}

2. Read data from JSON file 

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

var fs = require('fs');
fs.readFile('./namedposts.json', 'utf-8', function(err, data) {
    if (err) throw err
    let postsArr = JSON.parse(data) })

3. In the parsed data push the new data. 

produce/ modify the data which is demanded to write into the JSON file. For simplicity, I'm creating a single object. 

const newPostObj = 	{
						id: 122,
						authorId: 123,
						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 theposts.json file, If you have multiple objects( Array of objects) to write into the file also in the below law you'll need to produce the circle so that each object will be pushed in the postsArr variable. 

postsArr .posts.push(newPostObj)

5. Write the streamlined data intoposts.json file.

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

Let's see the complete here.

var fs = require('fs')
fs.readFile('./namedposts.json', 'utf-8', function(err, data) {
    if (err) throw err
    var arrayOfObjects = JSON.parse(data)
    arrayOfObjects.posts.push({
        id: 122,
        authorId: 123,
        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('./namedposts.json', JSON.stringify(arrayOfObjects), 'utf-8', function(err) {
        if (err) throw err
        console.log('JSON file updated successfully!')
    })
})

I hope this composition helped you to write JSON file with NodeJS. Click here to read further papers on NodeJS. 

Also Read:-How to Connect a MySQL Database in NodeJS

Also Read:-How to Install Node.js and npm on Raspberry Pi

Thanks! 




CFG