Categories
JavaScript Answers

How to write objects into file with Node.js?

Spread the love

Sometimes, we want to write objects into file with Node.js.

In this article, we’ll look at how to write objects into file with Node.js.

How to write objects into file with Node.js?

To write objects into file with Node.js, we can convert the object to a string with util.inspect.

For instance, we write

const util = require("util");
fs.writeFileSync("./data.json", util.inspect(obj), "utf-8");

to call fs.writeSync to write the stringified obj object into the data.json file.

We call util.inspect with obj to convert obj into a JSON string.

Conclusion

To write objects into file with Node.js, we can convert the object to a string with util.inspect.

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 *