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 writeFile
- Example 1
- Example 2 – With encoding mentioned
Syntax of Node.js writeFile() function
fs = require('fs'); fs.writeFile(filename, data, [encoding], [callback_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.
// 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,
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
// 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 Tutorial – Node FS – Write to File, we have learnt to write content to file with the help of an example.