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 which represents the file descriptor.
Below examples illustrate the use of fs.openSync() method in Node.js:
Example 1:
// Node.js program to demonstrate the // fs.openSync() method // Including fs module var fs = require('fs'); // Defining filename var filename = './myfile'; // Calling openSync method // with its parameters var res = fs.openSync(filename, 'r'); // Prints output console.log(res); |
Output:
23
Here, the flag ‘r’ indicates that the file is already created and it reads the created file.
Example 2:
// Node.js program to demonstrate the // fs.openSync() method // Including fs module var fs = require('fs'); // Defining path var path = require('path'); // Calling openSync method with // all its parameters var fd = fs.openSync(path.join( process.cwd(), 'input.txt'), 'w', 0o666); // This will append the content // of file created above fs.writeSync(fd, 'GeeksforGeeks'); // Setting timeout setTimeout(function () { // Its printed after the file is closed console.log('closing file now'); // closing file descriptor 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

