Open In App

Node JS fs.writeFile() Method

fs.writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The ‘options’ parameter can be used to modify the functionality of the method.

Syntax:



fs.writeFile( file, data, options, callback )

Parameters:

This method accepts four parameters as mentioned above and described below:



Steps to Create Node JS Application:

Step 1: Create a node project folder and install locally by npm init -y

npm init -y

Step 2: After creating your project folder, move to it by using the following command.

cd *project folder name*

Project Structure:

Project Structure

Example 1: Below examples illustrate the fs.writeFile() method in Node.js:




// Node.js program to demonstrate the
// fs.writeFile() method
 
// Import the filesystem module
const fs = require('fs');
 
let data = "This is a file containing a collection of books.";
 
fs.writeFile("books.txt", data, (err) => {
  if (err)
    console.log(err);
  else {
    console.log("File written successfully\n");
    console.log("The written has the following contents:");
    console.log(fs.readFileSync("books.txt", "utf8"));
  }
});

Output:

File written successfully
The written has the following contents:
This is a file containing a collection of books.

Example 2: Below examples illustrate the fs.writeFile() method in Node.js:




// Node.js program to demonstrate the
// fs.writeFile() method
 
// Import the filesystem module
const fs = require('fs');
 
let data = "This is a file containing a collection of movies.";
 
fs.writeFile("movies.txt", data,
  {
    encoding: "utf8",
    flag: "w",
    mode: 0o666
  },
  (err) => {
    if (err)
      console.log(err);
    else {
      console.log("File written successfully\n");
      console.log("The written has the following contents:");
      console.log(fs.readFileSync("movies.txt", "utf8"));
    }
});

Output:

File written successfully
The written has the following contents:
This is a file containing a collection of movies.

Article Tags :