Node.js fs.writeFile() method writes data to a file asynchronously with replacing the file in case of already exists. This function can write data from a string or a buffer.
The encoding option is ignored if data is a buffer. It defaults encoding is ‘utf8’, Default file mode is 0666 and default flag is used ‘w’ means write mode.
Advertisement
Syntax
The fs.writeFile() function in Nodejs (JavaScript) uses the following syntax.
fs.writeFile(filename, data[, options], callback)
Here:
- filename is the filename with path.
- data is the String or buffer to write
- options can be an object which is like {encoding, mode, flag}.
- callback function takes single parameter err and used to return errors.
Example
Let’s create a JavaScript file testWriteFile.js
and add the following content. This script will write the “Hello World!” string into the file named output.txt in the current directory.
1 2 3 4 5 6 7 8 | var fs = require('fs'); fs.writeFile("output.txt", "Hello World!", function(err) { if(err) { return console.error(err); } console.log("File saved successfully!"); }); |
Save file and run it with Node.js
node testWriteFile.js
Output:File saved successfully!
You can also view the content of output.txt with type command on Windows or cat command in Linux.
1 Comment
console.log(err) should be console.error(err) 🙂