Open In App

Node.js fsPromises.writeFile() Method

The fsPromises.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.

The Promise will be resolved with no arguments upon success.



Syntax:

fsPromises.writeFile( file, data, options )

Parameters: This method accepts three parameters as mentioned above and described below:



Return Value: This method returns a Promise.

Below examples illustrate the fsPromises.writeFile() method in Node.js:

Example 1:




// Node.js program to demonstrate the 
// fsPromises.writeFile() method 
  
// Import the filesystem module 
const fs = require('fs');
const fsPromises = require('fs').promises;
let data = "This is a file containing"
        + " a collection of movies.";
  
(async function main() {
    try {
        await fsPromises.writeFile(
                "movies.txt", data)
  
        console.log("File written successfully");
        console.log("The written file has"
            + " the following contents:");
  
        console.log(""
            fs.readFileSync("./movies.txt"));
  
    } catch (err) {
        console.error(err);
    }
})();

Output:

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

Example 2:




// Node.js program to demonstrate the 
// fsPromises.writeFile() method 
  
// Import the filesystem module 
const fs = require('fs');
const fsPromises = require('fs').promises;
let data = "This is a file containing"
        + " a collection of books.";
  
(async function main() {
    try {
  
        await fsPromises.writeFile(
                "books.txt", data, {
            encoding: "utf8",
            flag: "w",
            mode: 0o666
        });
  
        console.log("File written successfully\n");
        console.log("The written has the "
                + "following contents:");
  
        console.log(""
            fs.readFileSync("books.txt"));
    }
    catch (err) {
        console.error(err);
    }
})();

Output:

File written successfully

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

Reference: https://nodejs.org/api/fs.html#fs_fspromises_writefile_file_data_options


Article Tags :