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.

Advertisement

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.

Syntax

The fs.writeFile() function in Nodejs (JavaScript) uses the following syntax.

 fs.writeFile(filename, data[, options], callback)

Here:

  1. filename 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.

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.

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.

Share.

1 Comment

Leave A Reply

Exit mobile version