Skip to content

Node.js fs.writeFile() Method (Write to File)

Advertisement

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.

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.

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top