Node.js fs.openSync() Method
Last Updated :
30 Mar, 2023
The fs.openSync() method is an inbuilt application programming interface of fs module which is used to return an integer value that represents the file descriptor.
Syntax:
fs.openSync( path, flags, mode )
Parameters: This method accepts three parameters as mentioned above and described below:
- path: It holds the path of the file. It is of type string, Buffer, or URL.
- flags: It holds either a string or a number value. Its default value of it is ‘r’.
- mode: It holds either a string or an integer value and its default value of it is 0o666.
Return Value: It returns a number that represents the file descriptor.
The below examples illustrate the use of the fs.openSync() method in Node.js:
Example 1:
javascript
const fs = require( 'fs' );
const filename = './myfile' ;
const res = fs.openSync(filename, 'r' );
console.log(res);
|
Output:
23
Here, the flag ‘r’ indicates that the file is already created and it reads the created file.
Example 2:
javascript
const fs = require( 'fs' );
const path = require( 'path' );
const fd = fs.openSync(path.join(
process.cwd(), 'input.txt' ), 'w' , 0o666);
fs.writeSync(fd, 'GeeksforGeeks' );
setTimeout( function () {
console.log( 'closing file now' );
fs.closeSync(fd);
}, 10000);
console.log( "Program done!" );
|
Output:
Program done!
closing file now
Here, the flag ‘w’ indicates that the file is created or overwritten.
Reference: https://nodejs.org/api/fs.html#fs_fs_opensync_path_flags_mode
Share your thoughts in the comments
Please Login to comment...