Node.js Write JSON Object to File

Node.js Write JSON Object to File – In this article, we shall learn to write a JSON Object to a local file.

To write a JSON Object to a local file, following is a step-by-step guide :

  1. Stringify JSON Object.
    UseJSON.stringify(jsonObject)  to convert JSON Object to JSON String.
  2. Write the stringified object to file using fs.writeFile() function of Node FS module.

Complete Node.js Script File

Useful Link – To access elements of JSON Object, refer Node.js Parse JSON  .

Run the above program in Terminal with node command


A Big Note

In the above program, you might have observed that bothjsonData  andjsonContent  when logged to console result in same output. This is because when the JSON Object is logged to console, toString method is called implicitly. But if you attempt to write the JSON object to a file directly without prior Stringify, it results in[Object Object]  written to file.


Conclusion :

In this Node.js Tutorial – Node.js Write JSON Object to File, we have learnt to write a JSON Object to a file using JSON.stringify() function and FS.writeFile() function.