How do I add to an existing json file in node.js

前端 未结 3 535
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 03:03

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. Howeve

3条回答
  •  萌比男神i
    2020-12-03 04:01

    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))
    })
    

提交回复
热议问题