Node.JS Write to File

We can write data to file in Node.js using fs module.

In this tutorial, we will learn how to use fs module and its function writeFile() to write content to a file.

Syntax – writeFile()

The syntax of writeFile() function is

fs = require('fs');
fs.writeFile(filename, data, [encoding], [callback_function])

where

  • 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.

nodejs-write-to-file-example.js

</>
Copy
// include file system module

var fs = require('fs');

var data = "Hello !"

// write data to file sample.html
fs.writeFile('sample.txt', data,
	// callback function that is called after writing file is done
	function(err) {		
		if (err) throw err;
		// if no error
		console.log("Data is written to file successfully.")
});

When the above program is run in Terminal or Command Prompt, you will get the following output.

Output

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-write-to-file-example.js 
Data is written to file successfully.

Example 2 – Write Content to File with Specified Encoding

We can also specify encoding to be followed by writeFile() method when it writes content to file.

In this example, we will tell writeFile() method to write content to file with ASCII encoding.

nodejs-write-to-file-example-2.js

</>
Copy
// include file system module

var fs = require('fs');

var data = "HELLO";

// write data to file sample.html
fs.writeFile('sample.txt',data, 'ascii',
	// callback function that is called after writing file is done
	function(err) {		
		if (err) throw err;
		// if no error
		console.log("Data is written to file successfully.")
});

When the above program is run in Terminal,

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-write-to-file-example-2.js 
Data is written to file successfully.

Conclusion

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