Skip to main content
Before you’re able to interact with a file that sits in your filesystem, you must get a file descriptor. A file descriptor is a reference to an open file — a number (fd) returned by opening the file using the open() method offered by the fs module. This number uniquely identifies an open file in the operating system:
import fs from 'node:fs';

fs.open('/Users/joe/test.txt', 'r', (err, fd) => {
  // fd is our file descriptor
});
Notice the r used as the second parameter to the fs.open() call. That flag means we open the file for reading. Other flags you’ll commonly use are:
FlagDescriptionFile gets created if it doesn’t exist
r+Opens the file for reading and writing
w+Opens the file for reading and writing and positions the stream at the beginning of the file
aOpens the file for writing and positions the stream at the end of the file
a+Opens the file for reading and writing and positions the stream at the end of the file

Synchronous open

You can also open the file using the fs.openSync method, which returns the file descriptor instead of providing it in a callback:
import fs from 'node:fs';

try {
  const fd = fs.openSync('/Users/joe/test.txt', 'r');
} catch (err) {
  console.error(err);
}
Once you get the file descriptor — in whatever way you choose — you can perform all the operations that require it, like calling fs.close() and many other operations that interact with the filesystem.

Using the promise-based API

You can also open the file using the promise-based fsPromises.open method offered by the fs/promises module.
The fs/promises module is available starting from Node.js v14. Before v14, after v10, you can use require('fs').promises instead. Before v10, after v8, you can use util.promisify to convert fs methods into promise-based methods.
import fs from 'node:fs/promises';

let filehandle;
try {
  filehandle = await fs.open('/Users/joe/test.txt', 'r');
  console.log(filehandle.fd);
  console.log(await filehandle.readFile({ encoding: 'utf8' }));
} finally {
  if (filehandle) {
    await filehandle.close();
  }
}
Here is an example of util.promisify:
import fs from 'node:fs';
import util from 'node:util';

async function example() {
  const open = util.promisify(fs.open);
  const fd = await open('/Users/joe/test.txt', 'r');
}
example();
To see more details about the fs/promises module, please check the fs/promises API.

Build docs developers (and LLMs) love