Skip to content

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

Node.js Write to File - fs.writeFile() Function. Write data to file asynchronously. This function can write data from string or a buffer.

Covers
Node.js
Versions & support
About Node.js →
On this page

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

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

1 Comment

Leave a Reply

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


Back to top