Working with file descriptors in Node.js
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 (fd
) uniquely identifies an open file in operating system:
const module "node:fs"
fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
module "node:fs"
fs.function open(path: fs.PathLike, flags: fs.OpenMode | undefined, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void (+2 overloads)
open('/Users/joe/test.txt', 'r', (err: NodeJS.ErrnoException | null
err, fd: number
fd) => {
// fd is our file descriptor
});
Notice the r
we 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+ | This flag opens the file for reading and writing | ❌ |
w+ | This flag opens the file for reading and writing and it also positions the stream at the beginning of the file | ✅ |
a | This flag opens the file for writing and it also positions the stream at the end of the file | ✅ |
a+ | This flag opens the file for reading and writing and it also positions the stream at the end of the file | ✅ |
You can also open the file by using the fs.openSync
method, which returns the file descriptor, instead of providing it in a callback:
const module "node:fs"
fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
try {
const const fd: number
fd = module "node:fs"
fs.function openSync(path: fs.PathLike, flags: fs.OpenMode, mode?: fs.Mode | null): number
openSync('/Users/joe/test.txt', 'r');
} catch (var err: unknown
err) {
var console: Console
console.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
error(var err: unknown
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.
You can also open the file by using the promise-based fsPromises.open
method offered by the fs/promises
module.
The fs/promises
module is available starting only 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.
const module "node:fs/promises"
fs = var require: NodeJS.Require
(id: string) => any
require('node:fs/promises');
// Or const fs = require('fs').promises before v14.
async function function example(): Promise<void>
example() {
let let filehandle: any
filehandle;
try {
let filehandle: any
filehandle = await module "node:fs/promises"
fs.function open(path: PathLike, flags?: string | number, mode?: Mode): Promise<fs.FileHandle>
open('/Users/joe/test.txt', 'r');
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(let filehandle: fs.FileHandle
filehandle.FileHandle.fd: number
fd);
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(await let filehandle: fs.FileHandle
filehandle.FileHandle.readFile(options: ({
encoding: BufferEncoding;
} & EventEmitter<T extends EventMap<T> = DefaultEventMap>.Abortable) | BufferEncoding): Promise<string> (+2 overloads)
readFile({ encoding: BufferEncoding
encoding: 'utf8' }));
} finally {
if (let filehandle: fs.FileHandle | undefined
filehandle) {
await let filehandle: fs.FileHandle
filehandle.FileHandle.close(): Promise<void>
close();
}
}
}
function example(): Promise<void>
example();
Here is an example of util.promisify
:
const module "node:fs"
fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
const module "node:util"
util = var require: NodeJS.Require
(id: string) => any
require('node:util');
async function function example(): Promise<void>
example() {
const const open: (path: fs.PathLike, flags: fs.OpenMode, mode?: fs.Mode | null) => Promise<number>
open = module "node:util"
util.function promisify<(path: fs.PathLike, flags: fs.OpenMode, mode?: fs.Mode | null) => Promise<number>>(fn: util.CustomPromisify<(path: fs.PathLike, flags: fs.OpenMode, mode?: fs.Mode | null) => Promise<number>>): (path: fs.PathLike, flags: fs.OpenMode, mode?: fs.Mode | null) => Promise<number> (+13 overloads)
promisify(module "node:fs"
fs.function open(path: fs.PathLike, flags: fs.OpenMode | undefined, mode: fs.Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void (+2 overloads)
open);
const const fd: number
fd = await const open: (path: fs.PathLike, flags: fs.OpenMode, mode?: fs.Mode | null) => Promise<number>
open('/Users/joe/test.txt', 'r');
}
function example(): Promise<void>
example();
To see more details about the fs/promises
module, please check fs/promises API.