Node.js fs.openSync() Method

Last Updated : 28 Apr, 2025

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
// Node.js program to demonstrate the    
// fs.openSync() method

// Including fs module
const fs = require('fs');

// Defining filename
const filename = './myfile';

// Calling openSync method
// with its parameters
const 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: 

javascript
// Node.js program to demonstrate the    
// fs.openSync() method

// Including fs module
const fs = require('fs');

// Defining path
const path = require('path');

// Calling openSync method with
// all its parameters
const 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

Comment

Explore