How to append JSON data to existing JSON file node.js How to append JSON data to existing JSON file node.js json json

How to append JSON data to existing JSON file node.js


Try this. Don't forget to define anchors array.

var data = fs.readFileSync('testOutput.json');var json = JSON.parse(data);json.push(...anchors);fs.writeFile("testOutput.json", JSON.stringify(json))


I created two small functions to handle the data to append.

  1. the first function will: read data and convert JSON-string to JSON-array
  2. then we add the new data to the JSON-array
  3. we convert JSON-array to JSON-string and write it to the file

example: you want to add data { "title":" 2.0 Wireless " } to file my_data.json on the same folder root. just call append_data (file_path , data ) ,

it will append data in the JSON file, if the file existed . or it will create the file and add the data to it.

data = {  "title":"  2.0 Wireless " }file_path = './my_data.json'append_data (file_path , data )

the full code is here :

   const fs = require('fs');   data = {  "title":"  2.0 Wireless " }   file_path = './my_data.json'   append_data (file_path , data )   async function append_data (filename , data ) {    if (fs.existsSync(filename)) {        read_data = await readFile(filename)        if (read_data == false) {            console.log('not able to read file')        }        else {            read_data.push(data)            dataWrittenStatus = await writeFile(filename, read_data)            if dataWrittenStatus == true {              console.log('data added successfully')            }           else{              console.log('data adding failed')            }        }      else{          dataWrittenStatus = await writeFile(filename, [data])          if dataWrittenStatus == true {              console.log('data added successfully')          }          else{             console.log('data adding failed')           }      }   }    async function readFile  (filePath) {      try {        const data = await fs.promises.readFile(filePath, 'utf8')        return JSON.parse(data)      }     catch(err) {         return false;      }    }    async function writeFile  (filename ,writedata) {      try {          await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');          return true      }      catch(err) {          return false      }    }