32

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"
]
mmryspace
  • 689
  • 1
  • 9
  • 18
  • Possible duplicate of [How to append to a file in Node?](http://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node) – peteb Mar 18 '16 at 19:53
  • do you want the resulting file to contain valid json? if so, just appending to the file isn't going to be good enough. – Kevin B Mar 18 '16 at 19:54
  • @KevinB yes, that would be ideal but honestly I am not sure append is the correct terminology, so I edited my question. – mmryspace Mar 18 '16 at 19:59
  • @filmplane Did you find solution ? –  Mar 18 '16 at 20:22

4 Answers4

44

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))
})
Daniel Diekmeier
  • 3,401
  • 18
  • 33
15

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!');
    });
})
  • 1
    To clarify, I do not want to overwrite data. I want to add additional data to existing results – mmryspace Mar 18 '16 at 20:32
  • @filmplane The first example append data without making valid json. The second example append data also, but json structure is not destroyed. –  Mar 18 '16 at 20:36
  • We have to read the data, parse, append, and then overwrite the original file because of the JSON format. – SaundersB Sep 14 '20 at 22:38
1

Promise based solution [Javascript (ES6) + Node.js (V10 or above)]

const fsPromises = require('fs').promises;
fsPromises.readFile('myFile.json', 'utf8') 
        .then(data => { 
                let json = JSON.parse(data);
                json.myArr.push({name: "Krishnan", salary: 5678});

                fsPromises.writeFile('myFile.json', JSON.stringify(json))
                        .then(  () => { console.log('Append Success'); })
                        .catch(err => { console.log("Append Failed: " + err);});
            })
        .catch(err => { console.log("Read Error: " +err);});

If your project supports Javascript ES8 then you could use asyn/await instead of native promise.

SridharKritha
  • 8,481
  • 2
  • 52
  • 43
0

I have created data. Js file to maintain data displaying in the table fomat. Including text box to read data from user and how to display data enteted through text box in table

  • 1
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30461741) – camille Nov 29 '21 at 22:48