How to append JSON data to existing JSON file node.js
I created two small functions to handle the data to append.
- the first function will: read data and convert JSON-string to JSON-array
- then we add the new data to the JSON-array
- 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 } }