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
.