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:
- ESM
- CJS
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:
| Flag | Description | File 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 | ✅ |
a | Opens 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 thefs.openSync method, which returns the file descriptor instead of providing it in a callback:
- ESM
- CJS
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-basedfsPromises.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.- ESM
- CJS
util.promisify:
- ESM
- CJS
To see more details about the
fs/promises module, please check the fs/promises API.