fs.writeFile () writes [object, object] instead of real objects when closing the script

My script should read and write from a JSON file. This works without a problem. I copy the file locally, edit the object and write them back to the file. However, when I close the script with Ctrl + C and check my file, it contains [object, object]instead of the real objects that should be there. This does not happen every time, but annoying, because my script depends on this file.

Any ideas on how to prevent the reader from closing incorrectly? I already tried to check the type before writing, but that didn't help much.

function writeConfig(obj) {
    fs.writeFile('./config.json', obj, function (err) {
        if (err) console.log(err);
    });
}
+4
source share
2 answers

fs.writeFile - :

fs.writeFile(file, data[, options], callback)

, toto() , [object Object]

JSON, JSON.stringify:

function writeConfig(obj) {
        fs.writeFile('./config.json', JSON.stringify(obj, undefined, 2), function (err) {
            if (err) console.log(err);
        });
}
+2

All Articles