Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *