Node.JS Write to File

Node.JS Write to File – To write content to a file in Node.js, usewriteFile()  function of node fs module.


Syntax of Node.js writeFile() function

filename : [mandatory] name of the file, the data has to be written to
data : [mandatory] content that has to be written to file
encoding : [optional] encoding standard that has to be followed while writing content to file.
callback_function : [optional] function that would be called once writing to the file is completed

Allowed encoding formats are

  • ascii
  • utf8
  • base64

Note : A new file with specified filename is created with data specified. If a file with the same name exists already, the content is overwritten. Care has to be taken as previous content of file could be lost.


Example 1 – Write data to file in Node.js

In this example, we shall write content, “Hello !” , to a text file sample.txt.

When the above program is run in Terminal,


Example 2 – Write Content to file with specified encoding

When the above program is run in Terminal,

Conclusion :

In this Node.js TutorialNode FS – Write to File, we have learnt to write content to file with the help of an example.