Skip to content
Related Articles
Open in App
Not now

Related Articles

Node.js fsPromises.open() Method

Improve Article
Save Article
Like Article
  • Last Updated : 08 Oct, 2021
Improve Article
Save Article
Like Article

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 accept three parameters as mentioned above and described below:

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

Return Value: It returns the Promise.

Below example illustrates the fsPromises.open() method in Node.js:

Example:




// Node.js program to demonstrate the     
// fsPromises.open() Method 
     
// Include the fs module 
var fs = require('fs'); 
var 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 opening of file function is called to read the contents of file and store 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.

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!