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

前端 未结 3 522
伪装坚强ぢ
伪装坚强ぢ 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条回答
  • 2020-12-03 03:47

    You can use Bunyan. That is

    a simple and fast JSON logging library

    0 讨论(0)
  • 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))
    })
    
    0 讨论(0)
  • 2020-12-03 04:07

    In general, If you want to append to file you should use:

    fs.appendFile("results.json", json , function (err) {
       if (err) throw err;
       console.log('The "data to append" was appended to file!');
    });
    

    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.

    fs.readFile('results.json', function (err, data) {
        var json = JSON.parse(data);
        json.push('search result: ' + currentSearchResult);    
        fs.writeFile("results.json", JSON.stringify(json), function(err){
          if (err) throw err;
          console.log('The "data to append" was appended to file!');
        });
    })
    
    0 讨论(0)
提交回复
热议问题