Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    });
}
like image 251
brabant Avatar asked Jun 16 '16 12:06

brabant


People also ask

Does writeFile overwrite?

writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.

Should I use writeFile or writeFileSync?

Creating and writing files with writeFileSync is only recommended for debugging purposes, just like every other synchronous function in Node. As such, you should use the asynchronous function writeFile for creating and writing files in real-world projects.

Is FS writeFile a promise?

Promise version of fs. writeFile: Asynchronously writes data to a file, replacing the file if it already exists.

Is FS writeFile synchronous?

The fs. writeFileSync() is a synchronous method. The fs. writeFileSync() creates a new file if the specified file does not exist.


1 Answers

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

like image 134
Ricky Levi Avatar answered Sep 19 '22 14:09

Ricky Levi