13

My script needs to read and write from a JSON file. This works without problems. I copy the file locally, edit the object, and write them back out to the file. However, when I close the script with Ctrl+C and check my file it has [object, object] instead of the actual objects that should be there. This doesn't happen all every time, but is annoying because my script depends on this file.

Any ideas for how to prevent this from closing the reader incorrectly? I already tried checking the type before writing but it didn't seem to help much.

function writeConfig(obj) {
    fs.writeFile('./config.json', obj, function (err) {
        if (err) console.log(err);
    });
}
maxwellb
  • 13,366
  • 2
  • 25
  • 35
brabant
  • 135
  • 1
  • 1
  • 7

2 Answers2

22

I believe you should convert the obj to a JSON string, otherwise it's a real - JSON object that can't be simply be written into file

JSON.stringify(obj)

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Ricky Levi
  • 7,298
  • 1
  • 57
  • 65
3

The second argument to fs.writeFile is a String or Buffer:

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

If you're passing an object, it will be converted via the default .toString() method on the object, which results in [object Object]

If you want to serialize the object in JSON format, use the JSON.stringify function:

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