33

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"
]
4
  • Possible duplicate of How to append to a file in Node? Commented Mar 18, 2016 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. Commented Mar 18, 2016 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. Commented Mar 18, 2016 at 19:59
  • @filmplane Did you find solution ? Commented Mar 18, 2016 at 20:22

3 Answers 3

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))
})
Sign up to request clarification or add additional context in comments.

7 Comments

jsonis an Array, and you can append a new item to an array with .push.
In this example, "json" is not an array tho
The results.json in the original question contains an array. With fs.readFile, we get a string, and after JSON.parse, we have an array of strings. Then we push another string to the array.
You're correct, I didn't notice the actual result is an array.
I downvote because this will not work in case of multiple call in a a short time with no delay to lock the file.
|
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!');
    });
})

3 Comments

To clarify, I do not want to overwrite data. I want to add additional data to existing results
@filmplane The first example append data without making valid json. The second example append data also, but json structure is not destroyed.
We have to read the data, parse, append, and then overwrite the original file because of the JSON format.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.