Open In App

Node.js fsPromises.open() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The fsPromises.open() method is used to asynchronously open a file that returns a Promise that, when resolved, yields a FileHandle object.

Syntax:

fsPromises.open( filename, flags, mode)

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

  • filename: It is a String, Buffer, or URL that holds the name of the file to read or the entire path if stored at another location.
  • flags: It is a String or a Number, which gives an operation in which the file has to be opened. Default ‘r’.
  • mode:  It is a String or an Integer. Sets the mode of the file i.e. r:read, w:write, r+:readwrite. It sets to default as read-write.

Return Value: It returns the Promise.

Example: The below example illustrates the fsPromises.open() method in Node.js:

javascript




// Node.js program to demonstrate the   
// fsPromises.open() Method
 
// Include the fs module
const fs = require('fs');
const fsPromises = fs.promises;
 
// Open file Demo.txt in read mode
fsPromises.open('Demo.txt', 'r')
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.log(error);
    });


Output:

FileHandle { [Symbol(handle)]: FileHandle { fd: 3 } }

Explanation: The file is opened and the flag is set to read mode. After the opening of the file function is called to read the contents of the file and store them in memory.

Note: mode sets the file mode (permission and sticky bits), but only if the file was created.

Some characters (< >: ” / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces.


Last Updated : 04 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads