Node.js fs.writeFile() function writes data to a file asynchronously with replacing the file in case of already exists. This function can write data from 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.
1. path is the filename with path.
2. data is the String or buffer to write
3. options can be an object which is like {encoding, mode, flag}.
4. callback function takes single parameter err and used to return errors.
Syntax
Node.js fs.writeFile() function uses following syntax.
fs.writeFile(filename, data[, options], callback)
Example
Create a JavaScript file (example: app.js) and add following content. This script will write “Hello World!” string in to the file named output.txt in current directory.
var fs = require('fs'); fs.writeFile("output.txt", "Hello World!", function(err) { if(err) { return console.log(err); } console.log("File saved successfully!"); });
Leave a Reply