Node.js fsPromises.open() Method
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
const fs = require( 'fs' );
const fsPromises = fs.promises;
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
Share your thoughts in the comments
Please Login to comment...