I am new to Node.js and JavaScript. I have a results.json
file that I want to keep a running log of results from a script that pulls images from the web. However, my current script only overwrites the existing result. How do I build upon or add to the results.json
so each subsequent result is logged in the results.json file? I would like it to be valid json.
Here is general example:
var currentSearchResult = someWebSearchResult var fs = require('fs'); var json = JSON.stringify(['search result: ' + currentSearchResult + ': ', null, "\t"); fs.writeFile("results.json", json);
And the results.json:
[ "search result: currentSearchResult" ]
Append file creates file if does not exist. But ,if you want to append JSON data first you read the data and after that you could overwrite that data. We have to read the data, parse, append, and then overwrite the original file because of the JSON format.
Steps for Appending to a JSON FileRead the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.
To append data to file in Node. js, use Node FS appendFile() function for asynchronous file operation or Node FS appendFileSync() function for synchronous file operation.
If you want the file to be valid JSON, you have to open your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.
var fs = require('fs') var currentSearchResult = 'example' fs.readFile('results.json', function (err, data) { var json = JSON.parse(data) json.push('search result: ' + currentSearchResult) fs.writeFile("results.json", JSON.stringify(json)) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With