JSONaLeo
JSONaLeo

Reputation: 416

Node.js script seems to skip fs.readFile code block

I'm trying to use Node.js to append a .json file using fs.

I have written const fs = require("fs"); at the top of my document, but within a switch and case block, where much of the code is run normally, the entire fs.readFile(...) section doesn't seem to do anything.

Also, for the purposes of simplicity, lets say I've defined initCommand as process.argv[2] and whatToSet as process.argv[3]

here is the whole switch and case block for the case in question:

switch(initCommand) {
    case("set"):
        newObject = {
            whatToSet: whatToSet,
            whenToSet: Date.now(),
        };
        console.log(newObject);
        console.log("top of fs code block");
        fs.readFile('objects.json', function (err, data) {
            let json = [];
            if (!err) {
                try {
                    json = JSON.parse(data);
                } catch (e) {
                    console.error(e);
                }
            }
            json.push(newObject);
            fs.writeFile("objects.json", JSON.stringify(json), function(err){
                if (err) throw err;
                console.log(`Your "object" was successfully appended!`);
            });
        });
        console.log("bottom of fs code block");
    break;
}

And when I run the command from the command line, calling the "set" case, node index.js set attribute here is the output:

{ whatToSet: 'attribute', whenToSet: 1516730036191 }
top of fs code block
bottom of fs code block

And needless to say, objects.json remains untouched. Any ideas would be appreciated.

Edit: Found a rogue process.exit(); that was cancelling the async fs process. Code runs correctly now. I also updated that fs.readFile(...)... bit above based on everyone's advice.

Upvotes: 0

Views: 735

Answers (1)

Thiago Barcala
Thiago Barcala

Reputation: 7353

Make sure the file objects.json exists, that it contains a valid JSON, and that the JSON represents an array (like []). If the file contains an object ({}), the call to .push will fail.

If you don't care about the possibility of losing some data in case of error, you can try something like this:

newObject = {
    whatToSet: whatToSet,
    whenToSet: Date.now(),
};
console.log(newObject);
console.log("top of fs code block");
fs.readFile('objects.json', function (err, data) {
    let json = [];
    if (!err) {
        try {
            json = JSON.parse(data);
        } catch (e) {
            console.error(e);
        }
    }
    json.push(newObject);
    fs.writeFile("objects.json", JSON.stringify(json), function(err){
        if (err) throw err;
        console.log(`Your "object" was successfully appended!`);
    });
});
console.log("bottom of fs code block");

I tested this code on Node v8.4.0 and it worked just fine.

Upvotes: 1

Related Questions