How to write JSON object to a JSON file with fs.writeFileSync?

Sometimes, we want to write JSON object to a JSON file with fs.writeFileSync.

In this article, we’ll look at how to write JSON object to a JSON file with fs.writeFileSync.

How to write JSON object to a JSON file with fs.writeFileSync?

To write JSON object to a JSON file with fs.writeFileSync, we can convert the JSON object to a string before we write it.

For instance, we write

fs.writeFileSync('../data/freqs.json', JSON.stringify(output));

to call fs.writeFileSync with the JSON file path and the stringified JSON object.

We call JSON.stringify to stringify output.

Conclusion

To write JSON object to a JSON file with fs.writeFileSync, we can convert the JSON object to a string before we write it.