text
stringlengths
2
4k
for await (const dirent of dir) * console.log(dirent.name); * } catch (err) { * console.error(err); * } * ``` * * When using the async iterator, the `fs.Dir` object will be automatically * closed after the iterator exits. * @since v12.12.0 */ export class Dir implements AsyncIterable<Dirent> { /** * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. * @since v12.12.0 */ readonly path: string; /** * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. */ [Symbol.asyncIterator](): AsyncIterableIterator<Dirent>; /** * Asynchronously close the directory's underlying resource handle. * Subsequent reads will result in errors. * * A promise is returned that will be fulfilled after the resource has been * closed. * @since v12.12.0 */ close(): Promise<void>; close(cb: NoParamCallback): void; /** * Synchronously close the directory's underlying resource handle. * Subsequent reads will result in errors. * @since v12.12.0 */ closeSync(): void; /** * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. * * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null`if there are no more directory entries to read. * * Directory entries returned by this function are in no particular order as * provided by the operating system's underlying directory mechanisms. * Entries added or removed while iterating over the directory might not be * included in the iteration results. * @since v12.12.0 * @return containing {fs.Dirent|null} */ read(): Promise<Dirent | null>; read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; /** * Synchronously read the next directory entry as an `fs.Dirent`. See the * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. * * If there are no more directory entries to read, `null` will be returned. * * Directory entries returned by this function are in no particular order as * provided by the operating system's underlying directory mechanisms. * Entries added or removed while iterating over the directory might not be * included in the iteration results. * @since v12.12.0 */ readSync(): Dirent | null; } /** * Class: fs.StatWatcher * @since v14.3.0, v12.20.0 * Extends `EventEmitter` * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. */ export interface StatWatcher extends EventEmitter { /** * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have * no effect. * * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been * called previously. * @since v14.3.0, v12.20.0 */ ref(): this; /** * When called, the active `fs.StatWatcher` object will not require the Node.js * event loop to remain active. If there is no other activity keeping the * event loop running, the process may exit before the `fs.StatWatcher` object's * callback is invoked. Calling `watcher.unref()` multiple times will have * no effect. * @since v14.3.0, v12.20.0
*/ unref(): this; } export interface FSWatcher extends EventEmitter { /** * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. * @since v0.5.8 */ close(): void; /** * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have * no effect. * * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been * called previously. * @since v14.3.0, v12.20.0 */ ref(): this; /** * When called, the active `fs.FSWatcher` object will not require the Node.js * event loop to remain active. If there is no other activity keeping the * event loop running, the process may exit before the `fs.FSWatcher` object's * callback is invoked. Calling `watcher.unref()` multiple times will have * no effect. * @since v14.3.0, v12.20.0 */ unref(): this; /** * events.EventEmitter * 1. change * 2. close * 3. error */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "error", listener: (error: Error) => void): this; on(event: string, listener: (...args: any[]) => void): this; on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; on(event: "close", listener: () => void): this; on(event: "error", listener: (error: Error) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; once(event: "close", listener: () => void): this; once(event: "error", listener: (error: Error) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "error", listener: (error: Error) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "error", listener: (error: Error) => void): this; } /** * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. * @since v0.1.93 */ export class ReadStream extends stream.Readable { close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; /** * The number of bytes that have been read so far. * @since v6.4.0 */ bytesRead: number; /** * The path to the file the stream is reading from as specified in the first * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. * @since v0.1.93 */ path: string | Buffer; /** * This property is `true` if the underlying file has not been opened yet, * i.e. before the `'ready'` event is emitted. * @since v11.2.0, v10.16.0
*/ pending: boolean; /** * events.EventEmitter * 1. open * 2. close * 3. ready */ addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: Buffer | string) => void): this; addListener(event: "end", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "open", listener: (fd: number) => void): this; addListener(event: "pause", listener: () => void): this; addListener(event: "readable", listener: () => void): this; addListener(event: "ready", listener: () => void): this; addListener(event: "resume", listener: () => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "data", listener: (chunk: Buffer | string) => void): this; on(event: "end", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "open", listener: (fd: number) => void): this; on(event: "pause", listener: () => void): this; on(event: "readable", listener: () => void): this; on(event: "ready", listener: () => void): this; on(event: "resume", listener: () => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "data", listener: (chunk: Buffer | string) => void): this; once(event: "end", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "open", listener: (fd: number) => void): this; once(event: "pause", listener: () => void): this; once(event: "readable", listener: () => void): this; once(event: "ready", listener: () => void): this; once(event: "resume", listener: () => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; prependListener(event: "end", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "open", listener: (fd: number) => void): this; prependListener(event: "pause", listener: () => void): this; prependListener(event: "readable", listener: () => void): this; prependListener(event: "ready", listener: () => void): this; prependListener(event: "resume", listener: () => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "open", listener: (fd: number) => void): this; prependOnceListener(event: "pause", listener: () => void): this; prependOnceListener(event: "readable", listener: () => void): this; prependOnceListener(event: "ready", listener: () => void): this; prependOnceListener(event: "resume", listener: () => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } /** * * Extends `stream.Writable` * * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. * @since v0.1.93 */ export class WriteStream extends stream.Writable { /** * Closes `writeStream`. Optionally accepts
a * callback that will be executed once the `writeStream`is closed. * @since v0.9.4 */ close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; /** * The number of bytes written so far. Does not include data that is still queued * for writing. * @since v0.4.7 */ bytesWritten: number; /** * The path to the file the stream is writing to as specified in the first * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a * `Buffer`. * @since v0.1.93 */ path: string | Buffer; /** * This property is `true` if the underlying file has not been opened yet, * i.e. before the `'ready'` event is emitted. * @since v11.2.0 */ pending: boolean; /** * events.EventEmitter * 1. open * 2. close * 3. ready */ addListener(event: "close", listener: () => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "finish", listener: () => void): this; addListener(event: "open", listener: (fd: number) => void): this; addListener(event: "pipe", listener: (src: stream.Readable) => void): this; addListener(event: "ready", listener: () => void): this; addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "drain", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "finish", listener: () => void): this; on(event: "open", listener: (fd: number) => void): this; on(event: "pipe", listener: (src: stream.Readable) => void): this; on(event: "ready", listener: () => void): this; on(event: "unpipe", listener: (src: stream.Readable) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "drain", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "finish", listener: () => void): this; once(event: "open", listener: (fd: number) => void): this; once(event: "pipe", listener: (src: stream.Readable) => void): this; once(event: "ready", listener: () => void): this; once(event: "unpipe", listener: (src: stream.Readable) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "drain", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "finish", listener: () => void): this; prependListener(event: "open", listener: (fd: number) => void): this; prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; prependListener(event: "ready", listener: () => void): this; prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "finish", listener: () => void): this; prependOnceListener(event: "open"
, listener: (fd: number) => void): this; prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; prependOnceListener(event: "ready", listener: () => void): this; prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } /** * Asynchronously rename file at `oldPath` to the pathname provided * as `newPath`. In the case that `newPath` already exists, it will * be overwritten. If there is a directory at `newPath`, an error will * be raised instead. No arguments other than a possible exception are * given to the completion callback. * * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). * * ```js * import { rename } from 'node:fs'; * * rename('oldFile.txt', 'newFile.txt', (err) => { * if (err) throw err; * console.log('Rename complete!'); * }); * ``` * @since v0.0.2 */ export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; export namespace rename { /** * Asynchronous rename(2) - Change the name or location of a file or directory. * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. * URL support is _experimental_. * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. * URL support is _experimental_. */ function __promisify__(oldPath: PathLike, newPath: PathLike): Promise<void>; } /** * Renames the file from `oldPath` to `newPath`. Returns `undefined`. * * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. * @since v0.1.21 */ export function renameSync(oldPath: PathLike, newPath: PathLike): void; /** * Truncates the file. No arguments other than a possible exception are * given to the completion callback. A file descriptor can also be passed as the * first argument. In this case, `fs.ftruncate()` is called. * * ```js * import { truncate } from 'node:fs'; * // Assuming that 'path/file.txt' is a regular file. * truncate('path/file.txt', (err) => { * if (err) throw err; * console.log('path/file.txt was truncated'); * }); * ``` * * Passing a file descriptor is deprecated and may result in an error being thrown * in the future. * * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. * @since v0.8.6 * @param [len=0] */ export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; /** * Asynchronous truncate(2) - Truncate a file to a specified length. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function truncate(path: PathLike, callback: NoParamCallback): void; export namespace truncate { /** * Asynchronous truncate(2) - Truncate a file to a specified length. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param len If not specified, defaults to `0`. */ function __promisify__(path: PathLike, len?: number | null): Promise<void>; } /** * Truncates the file. Returns `undefined`. A file descriptor can also be * passed as the first argument. In this case, `fs.ftruncateSync()` is called. * * Passing a file descriptor is deprecated and may result in an error being thrown * in the future. * @since v0.8.6 * @param [len=0] */ export function truncateSync(path: PathLike, len?: number | null): void; /** * Truncates th
e file descriptor. No arguments other than a possible exception are * given to the completion callback. * * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. * * If the file referred to by the file descriptor was larger than `len` bytes, only * the first `len` bytes will be retained in the file. * * For example, the following program retains only the first four bytes of the * file: * * ```js * import { open, close, ftruncate } from 'node:fs'; * * function closeFd(fd) { * close(fd, (err) => { * if (err) throw err; * }); * } * * open('temp.txt', 'r+', (err, fd) => { * if (err) throw err; * * try { * ftruncate(fd, 4, (err) => { * closeFd(fd); * if (err) throw err; * }); * } catch (err) { * closeFd(fd); * if (err) throw err; * } * }); * ``` * * If the file previously was shorter than `len` bytes, it is extended, and the * extended part is filled with null bytes (`'\0'`): * * If `len` is negative then `0` will be used. * @since v0.8.6 * @param [len=0] */ export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; /** * Asynchronous ftruncate(2) - Truncate a file to a specified length. * @param fd A file descriptor. */ export function ftruncate(fd: number, callback: NoParamCallback): void; export namespace ftruncate { /** * Asynchronous ftruncate(2) - Truncate a file to a specified length. * @param fd A file descriptor. * @param len If not specified, defaults to `0`. */ function __promisify__(fd: number, len?: number | null): Promise<void>; } /** * Truncates the file descriptor. Returns `undefined`. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link ftruncate}. * @since v0.8.6 * @param [len=0] */ export function ftruncateSync(fd: number, len?: number | null): void; /** * Asynchronously changes owner and group of a file. No arguments other than a * possible exception are given to the completion callback. * * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. * @since v0.1.97 */ export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; export namespace chown { /** * Asynchronous chown(2) - Change ownership of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>; } /** * Synchronously changes owner and group of a file. Returns `undefined`. * This is the synchronous version of {@link chown}. * * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. * @since v0.1.97 */ export function chownSync(path: PathLike, uid: number, gid: number): void; /** * Sets the owner of the file. No arguments other than a possible exception are * given to the completion callback. * * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. * @since v0.4.7 */ export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; export namespace fchown { /** * Asynchronous fchown(2) - Change ownership of a file. * @param fd A file descriptor. */ function __promisify__(fd: number, uid: number, gid: number): Promise<void>; } /** * Sets the owner of the file. R
eturns `undefined`. * * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. * @since v0.4.7 * @param uid The file's new owner's user id. * @param gid The file's new group's group id. */ export function fchownSync(fd: number, uid: number, gid: number): void; /** * Set the owner of the symbolic link. No arguments other than a possible * exception are given to the completion callback. * * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. */ export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; export namespace lchown { /** * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>; } /** * Set the owner for the path. Returns `undefined`. * * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. * @param uid The file's new owner's user id. * @param gid The file's new group's group id. */ export function lchownSync(path: PathLike, uid: number, gid: number): void; /** * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic * link, then the link is not dereferenced: instead, the timestamps of the * symbolic link itself are changed. * * No arguments other than a possible exception are given to the completion * callback. * @since v14.5.0, v12.19.0 */ export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; export namespace lutimes { /** * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, * with the difference that if the path refers to a symbolic link, then the link is not * dereferenced: instead, the timestamps of the symbolic link itself are changed. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param atime The last access time. If a string is provided, it will be coerced to number. * @param mtime The last modified time. If a string is provided, it will be coerced to number. */ function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>; } /** * Change the file system timestamps of the symbolic link referenced by `path`. * Returns `undefined`, or throws an exception when parameters are incorrect or * the operation fails. This is the synchronous version of {@link lutimes}. * @since v14.5.0, v12.19.0 */ export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; /** * Asynchronously changes the permissions of a file. No arguments other than a * possible exception are given to the completion callback. * * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. * * ```js * import { chmod } from 'node:fs'; * * chmod('my_file.txt', 0o775, (err) => { * if (err) throw err; * console.log('The permissions for file "my_file.txt" have been changed!'); * }); * ``` * @since v0.1.30 */ export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; export namespace chmod { /** * Asynchronous chmod(2) - Change permissions of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param mode A file
mode. If a string is passed, it is parsed as an octal integer. */ function __promisify__(path: PathLike, mode: Mode): Promise<void>; } /** * For detailed information, see the documentation of the asynchronous version of * this API: {@link chmod}. * * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. * @since v0.6.7 */ export function chmodSync(path: PathLike, mode: Mode): void; /** * Sets the permissions on the file. No arguments other than a possible exception * are given to the completion callback. * * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. * @since v0.4.7 */ export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; export namespace fchmod { /** * Asynchronous fchmod(2) - Change permissions of a file. * @param fd A file descriptor. * @param mode A file mode. If a string is passed, it is parsed as an octal integer. */ function __promisify__(fd: number, mode: Mode): Promise<void>; } /** * Sets the permissions on the file. Returns `undefined`. * * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. * @since v0.4.7 */ export function fchmodSync(fd: number, mode: Mode): void; /** * Changes the permissions on a symbolic link. No arguments other than a possible * exception are given to the completion callback. * * This method is only implemented on macOS. * * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. * @deprecated Since v0.4.7 */ export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; /** @deprecated */ export namespace lchmod { /** * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param mode A file mode. If a string is passed, it is parsed as an octal integer. */ function __promisify__(path: PathLike, mode: Mode): Promise<void>; } /** * Changes the permissions on a symbolic link. Returns `undefined`. * * This method is only implemented on macOS. * * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. * @deprecated Since v0.4.7 */ export function lchmodSync(path: PathLike, mode: Mode): void; /** * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. * * In case of an error, the `err.code` will be one of `Common System Errors`. * * {@link stat} follows symbolic links. Use {@link lstat} to look at the * links themselves. * * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. * Instead, user code should open/read/write the file directly and handle the * error raised if the file is not available. * * To check if a file exists without manipulating it afterwards, {@link access} is recommended. * * For example, given the following directory structure: * * ```text * - txtDir * -- file.txt * - app.js * ``` * * The next program will check for the stats of the given paths: * * ```js * import { stat } from 'node:fs'; * * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; * * for (let i = 0; i < pathsToCheck.length; i++) { * stat(pathsToCheck[i
], (err, stats) => { * console.log(stats.isDirectory()); * console.log(stats); * }); * } * ``` * * The resulting output will resemble: * * ```console * true * Stats { * dev: 16777220, * mode: 16877, * nlink: 3, * uid: 501, * gid: 20, * rdev: 0, * blksize: 4096, * ino: 14214262, * size: 96, * blocks: 0, * atimeMs: 1561174653071.963, * mtimeMs: 1561174614583.3518, * ctimeMs: 1561174626623.5366, * birthtimeMs: 1561174126937.2893, * atime: 2019-06-22T03:37:33.072Z, * mtime: 2019-06-22T03:36:54.583Z, * ctime: 2019-06-22T03:37:06.624Z, * birthtime: 2019-06-22T03:28:46.937Z * } * false * Stats { * dev: 16777220, * mode: 33188, * nlink: 1, * uid: 501, * gid: 20, * rdev: 0, * blksize: 4096, * ino: 14214074, * size: 8, * blocks: 8, * atimeMs: 1561174616618.8555, * mtimeMs: 1561174614584, * ctimeMs: 1561174614583.8145, * birthtimeMs: 1561174007710.7478, * atime: 2019-06-22T03:36:56.619Z, * mtime: 2019-06-22T03:36:54.584Z, * ctime: 2019-06-22T03:36:54.584Z, * birthtime: 2019-06-22T03:26:47.711Z * } * ``` * @since v0.0.2 */ export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; export function stat( path: PathLike, options: | (StatOptions & { bigint?: false | undefined; }) | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, ): void; export function stat( path: PathLike, options: StatOptions & { bigint: true; }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, ): void; export function stat( path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, ): void; export namespace stat { /** * Asynchronous stat(2) - Get file status. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ function __promisify__( path: PathLike, options?: StatOptions & { bigint?: false | undefined; }, ): Promise<Stats>; function __promisify__( path: PathLike, options: StatOptions & { bigint: true; }, ): Promise<BigIntStats>; function __promisify__(path: PathLike, options?: StatOptions): Promise<Stats | BigIntStats>; } export interface StatSyncFn extends Function { (path: PathLike, options?: undefined): Stats; ( path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined; throwIfNoEntry: false; }, ): Stats | undefined; ( path: PathLike, options: StatSyncOptions & { bigint: true; throwIfNoEntry: false; }, ): BigIntStats | undefined; ( path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined; }, ): Stats; ( path: PathLike, options: StatSyncOptions & { bigint: true; }, ): BigIntStats; ( path: PathLike, options: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false | undefined; }, ): Stats | BigIntStats; (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; } /** * Synchronous stat(2)
- Get file status. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export const statSync: StatSyncFn; /** * Invokes the callback with the `fs.Stats` for the file descriptor. * * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. * @since v0.1.95 */ export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; export function fstat( fd: number, options: | (StatOptions & { bigint?: false | undefined; }) | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, ): void; export function fstat( fd: number, options: StatOptions & { bigint: true; }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, ): void; export function fstat( fd: number, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, ): void; export namespace fstat { /** * Asynchronous fstat(2) - Get file status. * @param fd A file descriptor. */ function __promisify__( fd: number, options?: StatOptions & { bigint?: false | undefined; }, ): Promise<Stats>; function __promisify__( fd: number, options: StatOptions & { bigint: true; }, ): Promise<BigIntStats>; function __promisify__(fd: number, options?: StatOptions): Promise<Stats | BigIntStats>; } /** * Retrieves the `fs.Stats` for the file descriptor. * * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. * @since v0.1.95 */ export function fstatSync( fd: number, options?: StatOptions & { bigint?: false | undefined; }, ): Stats; export function fstatSync( fd: number, options: StatOptions & { bigint: true; }, ): BigIntStats; export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; /** * Retrieves the `fs.Stats` for the symbolic link referred to by the path. * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic * link, then the link itself is stat-ed, not the file that it refers to. * * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. * @since v0.1.30 */ export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; export function lstat( path: PathLike, options: | (StatOptions & { bigint?: false | undefined; }) | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, ): void; export function lstat( path: PathLike, options: StatOptions & { bigint: true; }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, ): void; export function lstat( path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, ): void; export namespace lstat { /** * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ function __promisify__( path: PathLike, options?: StatOptions &
{ bigint?: false | undefined; }, ): Promise<Stats>; function __promisify__( path: PathLike, options: StatOptions & { bigint: true; }, ): Promise<BigIntStats>; function __promisify__(path: PathLike, options?: StatOptions): Promise<Stats | BigIntStats>; } /** * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. * * In case of an error, the `err.code` will be one of `Common System Errors`. * @since v19.6.0, v18.15.0 * @param path A path to an existing file or directory on the file system to be queried. */ export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; export function statfs( path: PathLike, options: | (StatFsOptions & { bigint?: false | undefined; }) | undefined, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, ): void; export function statfs( path: PathLike, options: StatFsOptions & { bigint: true; }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, ): void; export function statfs( path: PathLike, options: StatFsOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, ): void; export namespace statfs { /** * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an <fs.StatFs> object. * @param path A path to an existing file or directory on the file system to be queried. */ function __promisify__( path: PathLike, options?: StatFsOptions & { bigint?: false | undefined; }, ): Promise<StatsFs>; function __promisify__( path: PathLike, options: StatFsOptions & { bigint: true; }, ): Promise<BigIntStatsFs>; function __promisify__(path: PathLike, options?: StatFsOptions): Promise<StatsFs | BigIntStatsFs>; } /** * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which * contains `path`. * * In case of an error, the `err.code` will be one of `Common System Errors`. * @since v19.6.0, v18.15.0 * @param path A path to an existing file or directory on the file system to be queried. */ export function statfsSync( path: PathLike, options?: StatFsOptions & { bigint?: false | undefined; }, ): StatsFs; export function statfsSync( path: PathLike, options: StatFsOptions & { bigint: true; }, ): BigIntStatsFs; export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; /** * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export const lstatSync: StatSyncFn; /** * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than * a possible * exception are given to the completion callback. * @since v0.1.31 */ export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; export namespace link { /** * A
synchronous link(2) - Create a new link (also known as a hard link) to an existing file. * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. */ function __promisify__(existingPath: PathLike, newPath: PathLike): Promise<void>; } /** * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. * @since v0.1.31 */ export function linkSync(existingPath: PathLike, newPath: PathLike): void; /** * Creates the link called `path` pointing to `target`. No arguments other than a * possible exception are given to the completion callback. * * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. * * The `type` argument is only available on Windows and ignored on other platforms. * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. * If the `target` does not exist, `'file'` will be used. Windows junction points * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction * points on NTFS volumes can only point to directories. * * Relative targets are relative to the link's parent directory. * * ```js * import { symlink } from 'node:fs'; * * symlink('./mew', './mewtwo', callback); * ``` * * The above example creates a symbolic link `mewtwo` which points to `mew` in the * same directory: * * ```bash * $ tree . * . * β”œβ”€β”€ mew * └── mewtwo -> ./mew * ``` * @since v0.1.31 * @param [type='null'] */ export function symlink( target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback, ): void; /** * Asynchronous symlink(2) - Create a new symbolic link to an existing file. * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. */ export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; export namespace symlink { /** * Asynchronous symlink(2) - Create a new symbolic link to an existing file. * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. */ function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise<void>; type Type = "dir" | "file" | "junction"; } /** * Returns `undefined`. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link symlink}. * @since v0.1.31 * @param [type='null'] */ export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; /** * Reads the contents of the symbolic link referred to by `path`. The callback gets * two arguments `(err, linkString)`. * * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details.
* * The optional `options` argument can be a string specifying an encoding, or an * object with an `encoding` property specifying the character encoding to use for * the link path passed to the callback. If the `encoding` is set to `'buffer'`, * the link path returned will be passed as a `Buffer` object. * @since v0.1.31 */ export function readlink( path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, ): void; /** * Asynchronous readlink(2) - read value of a symbolic link. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function readlink( path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, ): void; /** * Asynchronous readlink(2) - read value of a symbolic link. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function readlink( path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, ): void; /** * Asynchronous readlink(2) - read value of a symbolic link. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function readlink( path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, ): void; export namespace readlink { /** * Asynchronous readlink(2) - read value of a symbolic link. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__(path: PathLike, options?: EncodingOption): Promise<string>; /** * Asynchronous readlink(2) - read value of a symbolic link. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<Buffer>; /** * Asynchronous readlink(2) - read value of a symbolic link. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | Buffer>; } /** * Returns the symbolic link's string value. * * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. * * The optional `options` argument can be a string specifying an encoding, or an * object with an `encoding` property specifying the character encoding to use for * the link path returned. If the `encoding` is set to `'buffer'`, * the link path returned will be passed as a `Buffer` object. * @since v0.1.31 */ export function readlinkSync(path: PathLike, options?: EncodingOption): string; /** * Synchronous readlink(2) - read value of a symbolic link. * @param path A path to a file. If a URL is provided, it must use the `f
ile:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; /** * Synchronous readlink(2) - read value of a symbolic link. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; /** * Asynchronously computes the canonical pathname by resolving `.`, `..`, and * symbolic links. * * A canonical pathname is not necessarily unique. Hard links and bind mounts can * expose a file system entity through many pathnames. * * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: * * 1. No case conversion is performed on case-insensitive file systems. * 2. The maximum number of symbolic links is platform-independent and generally * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. * * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. * * Only paths that can be converted to UTF8 strings are supported. * * The optional `options` argument can be a string specifying an encoding, or an * object with an `encoding` property specifying the character encoding to use for * the path passed to the callback. If the `encoding` is set to `'buffer'`, * the path returned will be passed as a `Buffer` object. * * If `path` resolves to a socket or a pipe, the function will return a system * dependent name for that object. * @since v0.1.31 */ export function realpath( path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, ): void; /** * Asynchronous realpath(3) - return the canonicalized absolute pathname. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function realpath( path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, ): void; /** * Asynchronous realpath(3) - return the canonicalized absolute pathname. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function realpath( path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, ): void; /** * Asynchronous realpath(3) - return the canonicalized absolute pathname. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function realpath( path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, ): void; export namespace realpath { /** * Asynchronous realpath(3) - return the canonicalized absolute pathname. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ function __promisify__(path: PathLike, options?: EncodingOption): Promise<string>; /** * Asynchronous realpath(3) - return the canonicalized absolute pathname. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<Buffer>; /** * Asynchronous realpath(3) - return the canonicalized absolute pathname. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | Buffer>; /** * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). * * The `callback` gets two arguments `(err, resolvedPath)`. * * Only paths that can be converted to UTF8 strings are supported. * * The optional `options` argument can be a string specifying an encoding, or an * object with an `encoding` property specifying the character encoding to use for * the path passed to the callback. If the `encoding` is set to `'buffer'`, * the path returned will be passed as a `Buffer` object. * * On Linux, when Node.js is linked against musl libc, the procfs file system must * be mounted on `/proc` in order for this function to work. Glibc does not have * this restriction. * @since v9.2.0 */ function native( path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, ): void; function native( path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, ): void; function native( path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, ): void; function native( path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, ): void; } /** * Returns the resolved pathname. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link realpath}. * @since v0.1.31 */ export function realpathSync(path: PathLike, options?: EncodingOption): string; /** * Synchronous realpath(3) - return the canonicalized absolute pathname. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; /** * Synchronous realpath(3) - return the canonicalized absolute pathname. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; export namespace realpathSync { function native(path: PathLike, options?: EncodingOption): string; function native(path: PathLike, options: BufferEncodingOption): Buffer; function native(path: Pa
thLike, options?: EncodingOption): string | Buffer; } /** * Asynchronously removes a file or symbolic link. No arguments other than a * possible exception are given to the completion callback. * * ```js * import { unlink } from 'node:fs'; * // Assuming that 'path/file.txt' is a regular file. * unlink('path/file.txt', (err) => { * if (err) throw err; * console.log('path/file.txt was deleted'); * }); * ``` * * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a * directory, use {@link rmdir}. * * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. * @since v0.0.2 */ export function unlink(path: PathLike, callback: NoParamCallback): void; export namespace unlink { /** * Asynchronous unlink(2) - delete a name and possibly the file it refers to. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ function __promisify__(path: PathLike): Promise<void>; } /** * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. * @since v0.1.21 */ export function unlinkSync(path: PathLike): void; export interface RmDirOptions { /** * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or * `EPERM` error is encountered, Node.js will retry the operation with a linear * backoff wait of `retryDelay` ms longer on each try. This option represents the * number of retries. This option is ignored if the `recursive` option is not * `true`. * @default 0 */ maxRetries?: number | undefined; /** * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. * Use `fs.rm(path, { recursive: true, force: true })` instead. * * If `true`, perform a recursive directory removal. In * recursive mode, operations are retried on failure. * @default false */ recursive?: boolean | undefined; /** * The amount of time in milliseconds to wait between retries. * This option is ignored if the `recursive` option is not `true`. * @default 100 */ retryDelay?: number | undefined; } /** * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given * to the completion callback. * * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on * Windows and an `ENOTDIR` error on POSIX. * * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. * @since v0.0.2 */ export function rmdir(path: PathLike, callback: NoParamCallback): void; export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; export namespace rmdir { /** * Asynchronous rmdir(2) - delete a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ function __promisify__(path: PathLike, options?: RmDirOptions): Promise<void>; } /** * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. * * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error * on Windows and an `ENOTDIR` error on POSIX. * * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. * @since v0.1.21 */ export function rmdirSync(path: PathLike, options?: RmDirOptions): v
oid; export interface RmOptions { /** * When `true`, exceptions will be ignored if `path` does not exist. * @default false */ force?: boolean | undefined; /** * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or * `EPERM` error is encountered, Node.js will retry the operation with a linear * backoff wait of `retryDelay` ms longer on each try. This option represents the * number of retries. This option is ignored if the `recursive` option is not * `true`. * @default 0 */ maxRetries?: number | undefined; /** * If `true`, perform a recursive directory removal. In * recursive mode, operations are retried on failure. * @default false */ recursive?: boolean | undefined; /** * The amount of time in milliseconds to wait between retries. * This option is ignored if the `recursive` option is not `true`. * @default 100 */ retryDelay?: number | undefined; } /** * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the * completion callback. * @since v14.14.0 */ export function rm(path: PathLike, callback: NoParamCallback): void; export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; export namespace rm { /** * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). */ function __promisify__(path: PathLike, options?: RmOptions): Promise<void>; } /** * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. * @since v14.14.0 */ export function rmSync(path: PathLike, options?: RmOptions): void; export interface MakeDirectoryOptions { /** * Indicates whether parent folders should be created. * If a folder was created, the path to the first created folder will be returned. * @default false */ recursive?: boolean | undefined; /** * A file mode. If a string is passed, it is parsed as an octal integer. If not specified * @default 0o777 */ mode?: Mode | undefined; } /** * Asynchronously creates a directory. * * The callback is given a possible exception and, if `recursive` is `true`, the * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was * created (for instance, if it was previously created). * * The optional `options` argument can be an integer specifying `mode` (permission * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that * exists results in an error only * when `recursive` is false. If `recursive` is false and the directory exists, * an `EEXIST` error occurs. * * ```js * import { mkdir } from 'node:fs'; * * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. * mkdir('./tmp/a/apple', { recursive: true }, (err) => { * if (err) throw err; * }); * ``` * * On Windows, using `fs.mkdir()` on the root directory even with recursion will * result in an error: * * ```js * import { mkdir } from 'node:fs'; * * mkdir('/', { recursive: true }, (err) => { * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] * }); * ``` * * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. * @since v0.1.8 */ export function mkdir( path: PathLike,
options: MakeDirectoryOptions & { recursive: true; }, callback: (err: NodeJS.ErrnoException | null, path?: string) => void, ): void; /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ export function mkdir( path: PathLike, options: | Mode | (MakeDirectoryOptions & { recursive?: false | undefined; }) | null | undefined, callback: NoParamCallback, ): void; /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ export function mkdir( path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path?: string) => void, ): void; /** * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function mkdir(path: PathLike, callback: NoParamCallback): void; export namespace mkdir { /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ function __promisify__( path: PathLike, options: MakeDirectoryOptions & { recursive: true; }, ): Promise<string | undefined>; /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ function __promisify__( path: PathLike, options?: | Mode | (MakeDirectoryOptions & { recursive?: false | undefined; }) | null, ): Promise<void>; /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ function __promisify__( path: PathLike, options?: Mode | MakeDirectoryOptions | null, ): Promise<string | undefined>; } /** * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. * This is the synchronous version of {@link mkdir}. * * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. * @since v0.1.21
*/ export function mkdirSync( path: PathLike, options: MakeDirectoryOptions & { recursive: true; }, ): string | undefined; /** * Synchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ export function mkdirSync( path: PathLike, options?: | Mode | (MakeDirectoryOptions & { recursive?: false | undefined; }) | null, ): void; /** * Synchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; /** * Creates a unique temporary directory. * * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, * notably the BSDs, can return more than six random characters, and replace * trailing `X` characters in `prefix` with random characters. * * The created directory path is passed as a string to the callback's second * parameter. * * The optional `options` argument can be a string specifying an encoding, or an * object with an `encoding` property specifying the character encoding to use. * * ```js * import { mkdtemp } from 'node:fs'; * import { join } from 'node:path'; * import { tmpdir } from 'node:os'; * * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { * if (err) throw err; * console.log(directory); * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 * }); * ``` * * The `fs.mkdtemp()` method will append the six randomly selected characters * directly to the `prefix` string. For instance, given a directory `/tmp`, if the * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator * (`require('node:path').sep`). * * ```js * import { tmpdir } from 'node:os'; * import { mkdtemp } from 'node:fs'; * * // The parent directory for the new temporary directory * const tmpDir = tmpdir(); * * // This method is *INCORRECT*: * mkdtemp(tmpDir, (err, directory) => { * if (err) throw err; * console.log(directory); * // Will print something similar to `/tmpabc123`. * // A new temporary directory is created at the file system root * // rather than *within* the /tmp directory. * }); * * // This method is *CORRECT*: * import { sep } from 'node:path'; * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { * if (err) throw err; * console.log(directory); * // Will print something similar to `/tmp/abc123`. * // A new temporary directory is created within * // the /tmp directory. * }); * ``` * @since v5.10.0 */ export function mkdtemp( prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string) => void, ): void; /** * Asynchronously creates a unique temporary directory. * Generates six random characters to be appended b
ehind a required prefix to create a unique temporary directory. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function mkdtemp( prefix: string, options: | "buffer" | { encoding: "buffer"; }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void, ): void; /** * Asynchronously creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function mkdtemp( prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, ): void; /** * Asynchronously creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. */ export function mkdtemp( prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void, ): void; export namespace mkdtemp { /** * Asynchronously creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__(prefix: string, options?: EncodingOption): Promise<string>; /** * Asynchronously creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__(prefix: string, options: BufferEncodingOption): Promise<Buffer>; /** * Asynchronously creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__(prefix: string, options?: EncodingOption): Promise<string | Buffer>; } /** * Returns the created directory path. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link mkdtemp}. * * The optional `options` argument can be a string specifying an encoding, or an * object with an `encoding` property specifying the character encoding to use. * @since v5.10.0 */ export function mkdtempSync(prefix: string, options?: EncodingOption): string; /** * Synchronously creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; /** * Synchronously creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function
mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; /** * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. * * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. * * The optional `options` argument can be a string specifying an encoding, or an * object with an `encoding` property specifying the character encoding to use for * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, * the filenames returned will be passed as `Buffer` objects. * * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. * @since v0.1.8 */ export function readdir( path: PathLike, options: | { encoding: BufferEncoding | null; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, ): void; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function readdir( path: PathLike, options: | { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, ): void; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function readdir( path: PathLike, options: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; }) | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, ): void; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function readdir( path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, ): void; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. */ export function readdir( path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, ): void; export namespace readdir { /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__( path: PathLike, options?: | { encoding: BufferEncoding | nu
ll; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | BufferEncoding | null, ): Promise<string[]>; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__( path: PathLike, options: | "buffer" | { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; }, ): Promise<Buffer[]>; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ function __promisify__( path: PathLike, options?: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; }) | BufferEncoding | null, ): Promise<string[] | Buffer[]>; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options If called with `withFileTypes: true` the result data will be an array of Dirent */ function __promisify__( path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; }, ): Promise<Dirent[]>; } /** * Reads the contents of the directory. * * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. * * The optional `options` argument can be a string specifying an encoding, or an * object with an `encoding` property specifying the character encoding to use for * the filenames returned. If the `encoding` is set to `'buffer'`, * the filenames returned will be passed as `Buffer` objects. * * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. * @since v0.1.21 */ export function readdirSync( path: PathLike, options?: | { encoding: BufferEncoding | null; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | BufferEncoding | null, ): string[]; /** * Synchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function readdirSync( path: PathLike, options: | { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer", ): Buffer[]; /** * Synchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ export function readdirSync( path: PathLike, options?:
| (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; }) | BufferEncoding | null, ): string[] | Buffer[]; /** * Synchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. */ export function readdirSync( path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; }, ): Dirent[]; /** * Closes the file descriptor. No arguments other than a possible exception are * given to the completion callback. * * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use * through any other `fs` operation may lead to undefined behavior. * * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. * @since v0.0.2 */ export function close(fd: number, callback?: NoParamCallback): void; export namespace close { /** * Asynchronous close(2) - close a file descriptor. * @param fd A file descriptor. */ function __promisify__(fd: number): Promise<void>; } /** * Closes the file descriptor. Returns `undefined`. * * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use * through any other `fs` operation may lead to undefined behavior. * * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. * @since v0.1.21 */ export function closeSync(fd: number): void; /** * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. * * `mode` sets the file mode (permission and sticky bits), but only if the file was * created. On Windows, only the write permission can be manipulated; see {@link chmod}. * * The callback gets two arguments `(err, fd)`. * * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). * * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. * @since v0.0.2 * @param [flags='r'] See `support of file system `flags``. * @param [mode=0o666] */ export function open( path: PathLike, flags: OpenMode | undefined, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void, ): void; /** * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param [flags='r'] See `support of file system `flags``. */ export function open( path: PathLike, flags: OpenMode | undefined, callback: (err: NodeJS.ErrnoException | null, fd: number) => void, ): void; /** * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; export namespace open { /** * Asynchronous open(2) - open and possib
ly create a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. */ function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise<number>; } /** * Returns an integer representing the file descriptor. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link open}. * @since v0.1.21 * @param [flags='r'] * @param [mode=0o666] */ export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; /** * Change the file system timestamps of the object referenced by `path`. * * The `atime` and `mtime` arguments follow these rules: * * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. * @since v0.4.2 */ export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; export namespace utimes { /** * Asynchronously change file timestamps of the file referenced by the supplied path. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param atime The last access time. If a string is provided, it will be coerced to number. * @param mtime The last modified time. If a string is provided, it will be coerced to number. */ function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>; } /** * Returns `undefined`. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link utimes}. * @since v0.4.2 */ export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; /** * Change the file system timestamps of the object referenced by the supplied file * descriptor. See {@link utimes}. * @since v0.4.2 */ export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; export namespace futimes { /** * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param atime The last access time. If a string is provided, it will be coerced to number. * @param mtime The last modified time. If a string is provided, it will be coerced to number. */ function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise<void>; } /** * Synchronous version of {@link futimes}. Returns `undefined`. * @since v0.4.2 */ export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; /** * Request that all data for the open file descriptor is flushed to the storage * device. The specific implementation is operating system and device specific. * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other * than a possible exception are given to the completion callback. * @since v0.1.96 */ export function fsync(fd: number, callback: NoParamCallback): void; export namespace fsync { /** * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. * @param fd A file descriptor. */ function __promisify__(fd: number): Promise<void>; } /** * Request that all data for the open file descriptor is flushed to the storage * device. The specific implementation is operating system and device sp
ecific. * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. * @since v0.1.96 */ export function fsyncSync(fd: number): void; /** * Write `buffer` to the file specified by `fd`. * * `offset` determines the part of the buffer to be written, and `length` is * an integer specifying the number of bytes to write. * * `position` refers to the offset from the beginning of the file where this data * should be written. If `typeof position !== 'number'`, the data will be written * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). * * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. * * If this method is invoked as its `util.promisify()` ed version, it returns * a promise for an `Object` with `bytesWritten` and `buffer` properties. * * It is unsafe to use `fs.write()` multiple times on the same file without waiting * for the callback. For this scenario, {@link createWriteStream} is * recommended. * * On Linux, positional writes don't work when the file is opened in append mode. * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v0.0.2 * @param [offset=0] * @param [length=buffer.byteLength - offset] * @param [position='null'] */ export function write<TBuffer extends NodeJS.ArrayBufferView>( fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, ): void; /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. */ export function write<TBuffer extends NodeJS.ArrayBufferView>( fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, ): void; /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. */ export function write<TBuffer extends NodeJS.ArrayBufferView>( fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, ): void; /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. */ export function write<TBuffer extends NodeJS.ArrayBufferView>( fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, ): void; /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param string A string to write. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. * @param encoding The expected string encoding. */ export function write( fd: number, string: string, position: number | undefined | null, encoding: BufferEncoding | undefined
| null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, ): void; /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param string A string to write. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. */ export function write( fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, ): void; /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param string A string to write. */ export function write( fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, ): void; export namespace write { /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. */ function __promisify__<TBuffer extends NodeJS.ArrayBufferView>( fd: number, buffer?: TBuffer, offset?: number, length?: number, position?: number | null, ): Promise<{ bytesWritten: number; buffer: TBuffer; }>; /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param string A string to write. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. * @param encoding The expected string encoding. */ function __promisify__( fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null, ): Promise<{ bytesWritten: number; buffer: string; }>; } /** * For detailed information, see the documentation of the asynchronous version of * this API: {@link write}. * @since v0.1.21 * @param [offset=0] * @param [length=buffer.byteLength - offset] * @param [position='null'] * @return The number of bytes written. */ export function writeSync( fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null, ): number; /** * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. * @param fd A file descriptor. * @param string A string to write. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. * @param encoding The expected string encoding. */ export function writeSync( fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null, ): number; export type ReadPosition = number | bigint; export interface ReadSyncOptions { /** * @default 0 */ offset?: number | undefined; /** * @default `length of buffer` */ length?: number | undefined; /** * @defaul
t null */ position?: ReadPosition | null | undefined; } export interface ReadAsyncOptions<TBuffer extends NodeJS.ArrayBufferView> extends ReadSyncOptions { buffer?: TBuffer; } /** * Read data from the file specified by `fd`. * * The callback is given the three arguments, `(err, bytesRead, buffer)`. * * If the file is not modified concurrently, the end-of-file is reached when the * number of bytes read is zero. * * If this method is invoked as its `util.promisify()` ed version, it returns * a promise for an `Object` with `bytesRead` and `buffer` properties. * @since v0.0.2 * @param buffer The buffer that the data will be written to. * @param offset The position in `buffer` to write the data to. * @param length The number of bytes to read. * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If * `position` is an integer, the file position will be unchanged. */ export function read<TBuffer extends NodeJS.ArrayBufferView>( fd: number, buffer: TBuffer, offset: number, length: number, position: ReadPosition | null, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, ): void; /** * Similar to the above `fs.read` function, this version takes an optional `options` object. * If not otherwise specified in an `options` object, * `buffer` defaults to `Buffer.alloc(16384)`, * `offset` defaults to `0`, * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 * `position` defaults to `null` * @since v12.17.0, 13.11.0 */ export function read<TBuffer extends NodeJS.ArrayBufferView>( fd: number, options: ReadAsyncOptions<TBuffer>, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, ): void; export function read( fd: number, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, ): void; export namespace read { /** * @param fd A file descriptor. * @param buffer The buffer that the data will be written to. * @param offset The offset in the buffer at which to start writing. * @param length The number of bytes to read. * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. */ function __promisify__<TBuffer extends NodeJS.ArrayBufferView>( fd: number, buffer: TBuffer, offset: number, length: number, position: number | null, ): Promise<{ bytesRead: number; buffer: TBuffer; }>; function __promisify__<TBuffer extends NodeJS.ArrayBufferView>( fd: number, options: ReadAsyncOptions<TBuffer>, ): Promise<{ bytesRead: number; buffer: TBuffer; }>; function __promisify__(fd: number): Promise<{ bytesRead: number; buffer: NodeJS.ArrayBufferView; }>; } /** * Returns the number of `bytesRead`. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link read}. * @since v0.1.21 * @param [position='null'] */ export function readSync( fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null, ): number; /** * Similar to the above `fs.readSync` function, this version takes an optional `options` object. * If no `options` object is specified, it will default
with the above values. */ export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; /** * Asynchronously reads the entire contents of a file. * * ```js * import { readFile } from 'node:fs'; * * readFile('/etc/passwd', (err, data) => { * if (err) throw err; * console.log(data); * }); * ``` * * The callback is passed two arguments `(err, data)`, where `data` is the * contents of the file. * * If no encoding is specified, then the raw buffer is returned. * * If `options` is a string, then it specifies the encoding: * * ```js * import { readFile } from 'node:fs'; * * readFile('/etc/passwd', 'utf8', callback); * ``` * * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an * error will be returned. On FreeBSD, a representation of the directory's contents * will be returned. * * ```js * import { readFile } from 'node:fs'; * * // macOS, Linux, and Windows * readFile('<directory>', (err, data) => { * // => [Error: EISDIR: illegal operation on a directory, read <directory>] * }); * * // FreeBSD * readFile('<directory>', (err, data) => { * // => null, <data> * }); * ``` * * It is possible to abort an ongoing request using an `AbortSignal`. If a * request is aborted the callback is called with an `AbortError`: * * ```js * import { readFile } from 'node:fs'; * * const controller = new AbortController(); * const signal = controller.signal; * readFile(fileInfo[0].name, { signal }, (err, buf) => { * // ... * }); * // When you want to abort the request * controller.abort(); * ``` * * The `fs.readFile()` function buffers the entire file. To minimize memory costs, * when possible prefer streaming via `fs.createReadStream()`. * * Aborting an ongoing request does not abort individual operating * system requests but rather the internal buffering `fs.readFile` performs. * @since v0.1.29 * @param path filename or file descriptor */ export function readFile( path: PathOrFileDescriptor, options: | ({ encoding?: null | undefined; flag?: string | undefined; } & Abortable) | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, ): void; /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ export function readFile( path: PathOrFileDescriptor, options: | ({ encoding: BufferEncoding; flag?: string | undefined; } & Abortable) | BufferEncoding, callback: (err: NodeJS.ErrnoException | null, data: string) => void, ): void; /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ export function readFile( path: PathOrFileDescriptor, options: | (ObjectEncodingOp
tions & { flag?: string | undefined; } & Abortable) | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, ): void; /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. */ export function readFile( path: PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, ): void; export namespace readFile { /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options An object that may contain an optional flag. * If a flag is not provided, it defaults to `'r'`. */ function __promisify__( path: PathOrFileDescriptor, options?: { encoding?: null | undefined; flag?: string | undefined; } | null, ): Promise<Buffer>; /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * URL support is _experimental_. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ function __promisify__( path: PathOrFileDescriptor, options: | { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding, ): Promise<string>; /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * URL support is _experimental_. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ function __promisify__( path: PathOrFileDescriptor, options?: | (ObjectEncodingOptions & { flag?: string | undefined; }) | BufferEncoding | null, ): Promise<string | Buffer>; } /** * Returns the contents of the `path`. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link readFile}. * * If the `encoding` option is specified then this function returns a * string. Otherwise it returns a buffer. * * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. * * ```js * import { readFileSync } from 'node:fs'; * * // macOS, Linux, and Windows * readFileSync('<directory>'); * // => [Error: EISDIR: illegal operation on a directory, read <directory>] * * // FreeBSD * readFileSync('<directory>'); // => <data> * ``` * @since v0.1.8 * @param path filename or file descriptor */ export function readFileSync( path: PathOrFileDescriptor, options?: { encoding?: null | undefined; flag?: string | undefined; } | null, ): Buffer;
/** * Synchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ export function readFileSync( path: PathOrFileDescriptor, options: | { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding, ): string; /** * Synchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ export function readFileSync( path: PathOrFileDescriptor, options?: | (ObjectEncodingOptions & { flag?: string | undefined; }) | BufferEncoding | null, ): string | Buffer; export type WriteFileOptions = | ( & ObjectEncodingOptions & Abortable & { mode?: Mode | undefined; flag?: string | undefined; flush?: boolean | undefined; } ) | BufferEncoding | null; /** * When `file` is a filename, asynchronously writes data to the file, replacing the * file if it already exists. `data` can be a string or a buffer. * * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using * a file descriptor. * * The `encoding` option is ignored if `data` is a buffer. * * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js * import { writeFile } from 'node:fs'; * import { Buffer } from 'node:buffer'; * * const data = new Uint8Array(Buffer.from('Hello Node.js')); * writeFile('message.txt', data, (err) => { * if (err) throw err; * console.log('The file has been saved!'); * }); * ``` * * If `options` is a string, then it specifies the encoding: * * ```js * import { writeFile } from 'node:fs'; * * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); * ``` * * It is unsafe to use `fs.writeFile()` multiple times on the same file without * waiting for the callback. For this scenario, {@link createWriteStream} is * recommended. * * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that * performs multiple `write` calls internally to write the buffer passed to it. * For performance sensitive code consider using {@link createWriteStream}. * * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. * Cancelation is "best effort", and some amount of data is likely still * to be written. * * ```js * import { writeFile } from 'node:fs'; * import { Buffer } from 'node:buffer'; * * const controller = new AbortController(); * const { signal } = controller; * const data = new Uint8Array(Buffer.from('Hello Node.js')); * writeFile('message.txt', data, { signal }, (err) => { * // When a request is aborted - the callback is called with an AbortError * }); * // When the request should be aborted * controller.abort(); * ``` * * Aborting an ongoing request does not abort individual operating * syste
m requests but rather the internal buffering `fs.writeFile` performs. * @since v0.1.29 * @param file filename or file descriptor */ export function writeFile( file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback, ): void; /** * Asynchronously writes data to a file, replacing the file if it already exists. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. */ export function writeFile( path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback, ): void; export namespace writeFile { /** * Asynchronously writes data to a file, replacing the file if it already exists. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * URL support is _experimental_. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. * If `encoding` is not supplied, the default of `'utf8'` is used. * If `mode` is not supplied, the default of `0o666` is used. * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'w'` is used. */ function __promisify__( path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions, ): Promise<void>; } /** * Returns `undefined`. * * The `mode` option only affects the newly created file. See {@link open} for more details. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link writeFile}. * @since v0.1.29 * @param file filename or file descriptor */ export function writeFileSync( file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions, ): void; /** * Asynchronously append data to a file, creating the file if it does not yet * exist. `data` can be a string or a `Buffer`. * * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js * import { appendFile } from 'node:fs'; * * appendFile('message.txt', 'data to append', (err) => { * if (err) throw err; * console.log('The "data to append" was appended to file!'); * }); * ``` * * If `options` is a string, then it specifies the encoding: * * ```js * import { appendFile } from 'node:fs'; * * appendFile('message.txt', 'data to append', 'utf8', callback); * ``` * * The `path` may be specified as a numeric file descriptor that has been opened * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will * not be closed automatically. * * ```js * import { open, close, appendFile } from 'node:fs'; * * function closeFd(fd) { * close(fd, (err) => { * if (err) throw err; * }); * } * * open('message.txt', 'a', (err, fd) => { * if (err) throw err; * * try { * appendFile(fd, 'data to append', 'utf8', (err) => { * closeFd(fd); * if (err) throw err; * }); * } catch (err) { * closeFd(fd);
* throw err; * } * }); * ``` * @since v0.6.7 * @param path filename or file descriptor */ export function appendFile( path: PathOrFileDescriptor, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback, ): void; /** * Asynchronously append data to a file, creating the file if it does not exist. * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. */ export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; export namespace appendFile { /** * Asynchronously append data to a file, creating the file if it does not exist. * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. * URL support is _experimental_. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. * If `encoding` is not supplied, the default of `'utf8'` is used. * If `mode` is not supplied, the default of `0o666` is used. * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'a'` is used. */ function __promisify__( file: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions, ): Promise<void>; } /** * Synchronously append data to a file, creating the file if it does not yet * exist. `data` can be a string or a `Buffer`. * * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js * import { appendFileSync } from 'node:fs'; * * try { * appendFileSync('message.txt', 'data to append'); * console.log('The "data to append" was appended to file!'); * } catch (err) { * // Handle the error * } * ``` * * If `options` is a string, then it specifies the encoding: * * ```js * import { appendFileSync } from 'node:fs'; * * appendFileSync('message.txt', 'data to append', 'utf8'); * ``` * * The `path` may be specified as a numeric file descriptor that has been opened * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will * not be closed automatically. * * ```js * import { openSync, closeSync, appendFileSync } from 'node:fs'; * * let fd; * * try { * fd = openSync('message.txt', 'a'); * appendFileSync(fd, 'data to append', 'utf8'); * } catch (err) { * // Handle the error * } finally { * if (fd !== undefined) * closeSync(fd); * } * ``` * @since v0.6.7 * @param path filename or file descriptor */ export function appendFileSync( path: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions, ): void; /** * Watch for changes on `filename`. The callback `listener` will be called each * time the file is accessed. * * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates * whether the process should continue to run as long as files are being watched. * The `options` object may specify an `interval` property ind
icating how often the * target should be polled in milliseconds. * * The `listener` gets two arguments the current stat object and the previous * stat object: * * ```js * import { watchFile } from 'fs'; * * watchFile('message.text', (curr, prev) => { * console.log(`the current mtime is: ${curr.mtime}`); * console.log(`the previous mtime was: ${prev.mtime}`); * }); * ``` * * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, * the numeric values in these objects are specified as `BigInt`s. * * To be notified when the file was modified, not just accessed, it is necessary * to compare `curr.mtimeMs` and `prev.mtimeMs`. * * When an `fs.watchFile` operation results in an `ENOENT` error, it * will invoke the listener once, with all the fields zeroed (or, for dates, the * Unix Epoch). If the file is created later on, the listener will be called * again, with the latest stat objects. This is a change in functionality since * v0.10. * * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. * * When a file being watched by `fs.watchFile()` disappears and reappears, * then the contents of `previous` in the second callback event (the file's * reappearance) will be the same as the contents of `previous` in the first * callback event (its disappearance). * * This happens when: * * * the file is deleted, followed by a restore * * the file is renamed and then renamed a second time back to its original name * @since v0.1.31 */ export interface WatchFileOptions { bigint?: boolean | undefined; persistent?: boolean | undefined; interval?: number | undefined; } /** * Watch for changes on `filename`. The callback `listener` will be called each * time the file is accessed. * * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates * whether the process should continue to run as long as files are being watched. * The `options` object may specify an `interval` property indicating how often the * target should be polled in milliseconds. * * The `listener` gets two arguments the current stat object and the previous * stat object: * * ```js * import { watchFile } from 'node:fs'; * * watchFile('message.text', (curr, prev) => { * console.log(`the current mtime is: ${curr.mtime}`); * console.log(`the previous mtime was: ${prev.mtime}`); * }); * ``` * * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, * the numeric values in these objects are specified as `BigInt`s. * * To be notified when the file was modified, not just accessed, it is necessary * to compare `curr.mtimeMs` and `prev.mtimeMs`. * * When an `fs.watchFile` operation results in an `ENOENT` error, it * will invoke the listener once, with all the fields zeroed (or, for dates, the * Unix Epoch). If the file is created later on, the listener will be called * again, with the latest stat objects. This is a change in functionality since * v0.10. * * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. * * When a file being watched by `fs.watchFile()` disappears and reappears, * then the contents of `previous` in the second callback event (the file's * reappearance) will be the same as the contents of `previous` in the first * callback event (its disappearance). * * This happens when: *
* * the file is deleted, followed by a restore * * the file is renamed and then renamed a second time back to its original name * @since v0.1.31 */ export function watchFile( filename: PathLike, options: | (WatchFileOptions & { bigint?: false | undefined; }) | undefined, listener: StatsListener, ): StatWatcher; export function watchFile( filename: PathLike, options: | (WatchFileOptions & { bigint: true; }) | undefined, listener: BigIntStatsListener, ): StatWatcher; /** * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. */ export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; /** * Stop watching for changes on `filename`. If `listener` is specified, only that * particular listener is removed. Otherwise, _all_ listeners are removed, * effectively stopping watching of `filename`. * * Calling `fs.unwatchFile()` with a filename that is not being watched is a * no-op, not an error. * * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. * @since v0.1.31 * @param listener Optional, a listener previously attached using `fs.watchFile()` */ export function unwatchFile(filename: PathLike, listener?: StatsListener): void; export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; export interface WatchOptions extends Abortable { encoding?: BufferEncoding | "buffer" | undefined; persistent?: boolean | undefined; recursive?: boolean | undefined; } export type WatchEventType = "rename" | "change"; export type WatchListener<T> = (event: WatchEventType, filename: T | null) => void; export type StatsListener = (curr: Stats, prev: Stats) => void; export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; /** * Watch for changes on `filename`, where `filename` is either a file or a * directory. * * The second argument is optional. If `options` is provided as a string, it * specifies the `encoding`. Otherwise `options` should be passed as an object. * * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file * which triggered the event. * * On most platforms, `'rename'` is emitted whenever a filename appears or * disappears in the directory. * * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. * * If a `signal` is passed, aborting the corresponding AbortController will close * the returned `fs.FSWatcher`. * @since v0.5.10 * @param listener */ export function watch( filename: PathLike, options: | (WatchOptions & { encoding: "buffer"; }) | "buffer", listener?: WatchListener<Buffer>, ): FSWatcher; /** * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. * If `encoding` is not supplied, the default of `'utf8'` is used. * If `persistent` is not supplied, the
default of `true` is used. * If `recursive` is not supplied, the default of `false` is used. */ export function watch( filename: PathLike, options?: WatchOptions | BufferEncoding | null, listener?: WatchListener<string>, ): FSWatcher; /** * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. * If `encoding` is not supplied, the default of `'utf8'` is used. * If `persistent` is not supplied, the default of `true` is used. * If `recursive` is not supplied, the default of `false` is used. */ export function watch( filename: PathLike, options: WatchOptions | string, listener?: WatchListener<string | Buffer>, ): FSWatcher; /** * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. */ export function watch(filename: PathLike, listener?: WatchListener<string>): FSWatcher; /** * Test whether or not the given path exists by checking with the file system. * Then call the `callback` argument with either true or false: * * ```js * import { exists } from 'node:fs'; * * exists('/etc/passwd', (e) => { * console.log(e ? 'it exists' : 'no passwd!'); * }); * ``` * * **The parameters for this callback are not consistent with other Node.js** * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback * has only one boolean parameter. This is one reason `fs.access()` is recommended * instead of `fs.exists()`. * * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing * so introduces a race condition, since other processes may change the file's * state between the two calls. Instead, user code should open/read/write the * file directly and handle the error raised if the file does not exist. * * **write (NOT RECOMMENDED)** * * ```js * import { exists, open, close } from 'node:fs'; * * exists('myfile', (e) => { * if (e) { * console.error('myfile already exists'); * } else { * open('myfile', 'wx', (err, fd) => { * if (err) throw err; * * try { * writeMyData(fd); * } finally { * close(fd, (err) => { * if (err) throw err; * }); * } * }); * } * }); * ``` * * **write (RECOMMENDED)** * * ```js * import { open, close } from 'node:fs'; * open('myfile', 'wx', (err, fd) => { * if (err) { * if (err.code === 'EEXIST') { * console.error('myfile already exists'); * return; * } * * throw err; * } * * try { * writeMyData(fd); * } finally { * close(fd, (err) => { * if (err) throw err; * }); * } * }); * ``` * * **read (NOT RECOMMENDED)** * * ```js * import { open, close, exists } from 'node:fs'; * * exists('myfile', (e) => { * if (e) { * open('myfile', 'r', (err, fd) => { * if (err) throw err; * * try { * readMyData(fd); * } finally { * close(fd, (err) => { * if (err) throw err;
* }); * } * }); * } else { * console.error('myfile does not exist'); * } * }); * ``` * * **read (RECOMMENDED)** * * ```js * import { open, close } from 'node:fs'; * * open('myfile', 'r', (err, fd) => { * if (err) { * if (err.code === 'ENOENT') { * console.error('myfile does not exist'); * return; * } * * throw err; * } * * try { * readMyData(fd); * } finally { * close(fd, (err) => { * if (err) throw err; * }); * } * }); * ``` * * The "not recommended" examples above check for existence and then use the * file; the "recommended" examples are better because they use the file directly * and handle the error, if any. * * In general, check for the existence of a file only if the file won't be * used directly, for example when its existence is a signal from another * process. * @since v0.0.2 * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. */ export function exists(path: PathLike, callback: (exists: boolean) => void): void; /** @deprecated */ export namespace exists { /** * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. * URL support is _experimental_. */ function __promisify__(path: PathLike): Promise<boolean>; } /** * Returns `true` if the path exists, `false` otherwise. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link exists}. * * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other * Node.js callbacks. `fs.existsSync()` does not use a callback. * * ```js * import { existsSync } from 'node:fs'; * * if (existsSync('/etc/passwd')) * console.log('The path exists.'); * ``` * @since v0.1.21 */ export function existsSync(path: PathLike): boolean; export namespace constants { // File Access Constants /** Constant for fs.access(). File is visible to the calling process. */ const F_OK: number; /** Constant for fs.access(). File can be read by the calling process. */ const R_OK: number; /** Constant for fs.access(). File can be written by the calling process. */ const W_OK: number; /** Constant for fs.access(). File can be executed by the calling process. */ const X_OK: number; // File Copy Constants /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ const COPYFILE_EXCL: number; /** * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. */ const COPYFILE_FICLONE: number; /** * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. * If the underlying platform does not support copy-on-write, then the operation will fail with an error. */ const COPYFILE_FICLONE_FORCE: number; // File Open Constants /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ const O_RDONLY: number; /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ const O_WRONLY: number; /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ const O_RDWR: number; /** Constant for fs.open(). Flag indicating to create the file if it does not already ex
ist. */ const O_CREAT: number; /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ const O_EXCL: number; /** * Constant for fs.open(). Flag indicating that if path identifies a terminal device, * opening the path shall not cause that terminal to become the controlling terminal for the process * (if the process does not already have one). */ const O_NOCTTY: number; /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ const O_TRUNC: number; /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ const O_APPEND: number; /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ const O_DIRECTORY: number; /** * constant for fs.open(). * Flag indicating reading accesses to the file system will no longer result in * an update to the atime information associated with the file. * This flag is available on Linux operating systems only. */ const O_NOATIME: number; /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ const O_NOFOLLOW: number; /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ const O_SYNC: number; /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ const O_DSYNC: number; /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ const O_SYMLINK: number; /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ const O_DIRECT: number; /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ const O_NONBLOCK: number; // File Type Constants /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ const S_IFMT: number; /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ const S_IFREG: number; /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ const S_IFDIR: number; /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ const S_IFCHR: number; /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ const S_IFBLK: number; /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ const S_IFIFO: number; /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ const S_IFLNK: number; /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ const S_IFSOCK: number; // File Mode Constants /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ const S_IRWXU: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ const S_IRUSR: number; /** Constant for fs.Stats mode property for determining ac
cess permissions for a file. File mode indicating writable by owner. */ const S_IWUSR: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ const S_IXUSR: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ const S_IRWXG: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ const S_IRGRP: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ const S_IWGRP: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ const S_IXGRP: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ const S_IRWXO: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ const S_IROTH: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ const S_IWOTH: number; /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ const S_IXOTH: number; /** * When set, a memory file mapping is used to access the file. This flag * is available on Windows operating systems only. On other operating systems, * this flag is ignored. */ const UV_FS_O_FILEMAP: number; } /** * Tests a user's permissions for the file or directory specified by `path`. * The `mode` argument is an optional integer that specifies the accessibility * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for * possible values of `mode`. * * The final argument, `callback`, is a callback function that is invoked with * a possible error argument. If any of the accessibility checks fail, the error * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. * * ```js * import { access, constants } from 'node:fs'; * * const file = 'package.json'; * * // Check if the file exists in the current directory. * access(file, constants.F_OK, (err) => { * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); * }); * * // Check if the file is readable. * access(file, constants.R_OK, (err) => { * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); * }); * * // Check if the file is writable. * access(file, constants.W_OK, (err) => { * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); * }); * * // Check if the file is readable and writable. * access(file, constants.R_OK | constants.W_OK, (err) => { * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); * }); * ``` * * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing * so introduces a race condition, since other processes may change the file's * state between the two calls. Instead, user code should open/read/write the * file directly and hand
le the error raised if the file is not accessible. * * **write (NOT RECOMMENDED)** * * ```js * import { access, open, close } from 'node:fs'; * * access('myfile', (err) => { * if (!err) { * console.error('myfile already exists'); * return; * } * * open('myfile', 'wx', (err, fd) => { * if (err) throw err; * * try { * writeMyData(fd); * } finally { * close(fd, (err) => { * if (err) throw err; * }); * } * }); * }); * ``` * * **write (RECOMMENDED)** * * ```js * import { open, close } from 'node:fs'; * * open('myfile', 'wx', (err, fd) => { * if (err) { * if (err.code === 'EEXIST') { * console.error('myfile already exists'); * return; * } * * throw err; * } * * try { * writeMyData(fd); * } finally { * close(fd, (err) => { * if (err) throw err; * }); * } * }); * ``` * * **read (NOT RECOMMENDED)** * * ```js * import { access, open, close } from 'node:fs'; * access('myfile', (err) => { * if (err) { * if (err.code === 'ENOENT') { * console.error('myfile does not exist'); * return; * } * * throw err; * } * * open('myfile', 'r', (err, fd) => { * if (err) throw err; * * try { * readMyData(fd); * } finally { * close(fd, (err) => { * if (err) throw err; * }); * } * }); * }); * ``` * * **read (RECOMMENDED)** * * ```js * import { open, close } from 'node:fs'; * * open('myfile', 'r', (err, fd) => { * if (err) { * if (err.code === 'ENOENT') { * console.error('myfile does not exist'); * return; * } * * throw err; * } * * try { * readMyData(fd); * } finally { * close(fd, (err) => { * if (err) throw err; * }); * } * }); * ``` * * The "not recommended" examples above check for accessibility and then use the * file; the "recommended" examples are better because they use the file directly * and handle the error, if any. * * In general, check for the accessibility of a file only if the file will not be * used directly, for example when its accessibility is a signal from another * process. * * On Windows, access-control policies (ACLs) on a directory may limit access to * a file or directory. The `fs.access()` function, however, does not check the * ACL and therefore may report that a path is accessible even if the ACL restricts * the user from reading or writing to it. * @since v0.11.15 * @param [mode=fs.constants.F_OK] */ export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; /** * Asynchronously tests a user's permissions for the file specified by path. * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. */ export function access(path: PathLike, callback: NoParamCallback): void; export namespace access { /** * Asynchronously tests a user's permissions for the file specified by path. * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. * URL support is _experimental_. */ function __promisify__(path: PathLike, mode?: number): Promise<void>; } /** * Synchronously tests a user's permissions for the file or directory specified * by `path`. The `mode` argument is an optional integer that specifies the
* accessibility checks to be performed. `mode` should be either the value`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of`fs.constants.R_OK`, `fs.constants.W_OK`, and * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for * possible values of `mode`. * * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, * the method will return `undefined`. * * ```js * import { accessSync, constants } from 'node:fs'; * * try { * accessSync('etc/passwd', constants.R_OK | constants.W_OK); * console.log('can read/write'); * } catch (err) { * console.error('no access!'); * } * ``` * @since v0.11.15 * @param [mode=fs.constants.F_OK] */ export function accessSync(path: PathLike, mode?: number): void; interface StreamOptions { flags?: string | undefined; encoding?: BufferEncoding | undefined; fd?: number | promises.FileHandle | undefined; mode?: number | undefined; autoClose?: boolean | undefined; emitClose?: boolean | undefined; start?: number | undefined; signal?: AbortSignal | null | undefined; highWaterMark?: number | undefined; } interface FSImplementation { open?: (...args: any[]) => any; close?: (...args: any[]) => any; } interface CreateReadStreamFSImplementation extends FSImplementation { read: (...args: any[]) => any; } interface CreateWriteStreamFSImplementation extends FSImplementation { write: (...args: any[]) => any; writev?: (...args: any[]) => any; } interface ReadStreamOptions extends StreamOptions { fs?: CreateReadStreamFSImplementation | null | undefined; end?: number | undefined; } interface WriteStreamOptions extends StreamOptions { fs?: CreateWriteStreamFSImplementation | null | undefined; flush?: boolean | undefined; } /** * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream * returned by this method has a default `highWaterMark` of 64 KiB. * * `options` can include `start` and `end` values to read a range of bytes from * the file instead of the entire file. Both `start` and `end` are inclusive and * start counting at 0, allowed values are in the * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the * current file position. The `encoding` can be any one of those accepted by `Buffer`. * * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use * the specified file descriptor. This means that no `'open'` event will be * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. * * If `fd` points to a character device that only supports blocking reads * (such as keyboard or sound card), read operations do not finish until data is * available. This can prevent the process from exiting and the stream from * closing naturally. * * By default, the stream will emit a `'close'` event after it has been * destroyed. Set the `emitClose` option to `false` to change this behavior. * * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is * also required. * * ```js * import { createReadStream } from 'node:fs'; * * // Create a stream from some character device.
* const stream = createReadStream('/dev/input/event0'); * setTimeout(() => { * stream.close(); // This may not close the stream. * // Artificially marking end-of-stream, as if the underlying resource had * // indicated end-of-file by itself, allows the stream to close. * // This does not cancel pending read operations, and if there is such an * // operation, the process may still not be able to exit successfully * // until it finishes. * stream.push(null); * stream.read(0); * }, 100); * ``` * * If `autoClose` is false, then the file descriptor won't be closed, even if * there's an error. It is the application's responsibility to close it and make * sure there's no file descriptor leak. If `autoClose` is set to true (default * behavior), on `'error'` or `'end'` the file descriptor will be closed * automatically. * * `mode` sets the file mode (permission and sticky bits), but only if the * file was created. * * An example to read the last 10 bytes of a file which is 100 bytes long: * * ```js * import { createReadStream } from 'node:fs'; * * createReadStream('sample.txt', { start: 90, end: 99 }); * ``` * * If `options` is a string, then it specifies the encoding. * @since v0.1.31 */ export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; /** * `options` may also include a `start` option to allow writing data at some * position past the beginning of the file, allowed values are in the * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than * replacing it may require the `flags` option to be set to `r+` rather than the * default `w`. The `encoding` can be any one of those accepted by `Buffer`. * * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, * then the file descriptor won't be closed, even if there's an error. * It is the application's responsibility to close it and make sure there's no * file descriptor leak. * * By default, the stream will emit a `'close'` event after it has been * destroyed. Set the `emitClose` option to `false` to change this behavior. * * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev`, and `close`. Overriding `write()`without `writev()` can reduce * performance as some optimizations (`_writev()`) * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. * * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be * emitted. `fd` should be blocking; non-blocking `fd`s * should be passed to `net.Socket`. * * If `options` is a string, then it specifies the encoding. * @since v0.1.31 */ export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; /** * Forces all currently queued I/O operations associated with the file to the * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other * than a possible * exception are given to the completion callback. * @since v0.1.96 */ export function fdatasync(fd: number, callback
: NoParamCallback): void; export namespace fdatasync { /** * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. * @param fd A file descriptor. */ function __promisify__(fd: number): Promise<void>; } /** * Forces all currently queued I/O operations associated with the file to the * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. * @since v0.1.96 */ export function fdatasyncSync(fd: number): void; /** * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it * already exists. No arguments other than a possible exception are given to the * callback function. Node.js makes no guarantees about the atomicity of the copy * operation. If an error occurs after the destination file has been opened for * writing, Node.js will attempt to remove the destination. * * `mode` is an optional integer that specifies the behavior * of the copy operation. It is possible to create a mask consisting of the bitwise * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). * * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already * exists. * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a * copy-on-write reflink. If the platform does not support copy-on-write, then a * fallback copy mechanism is used. * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to * create a copy-on-write reflink. If the platform does not support * copy-on-write, then the operation will fail. * * ```js * import { copyFile, constants } from 'node:fs'; * * function callback(err) { * if (err) throw err; * console.log('source.txt was copied to destination.txt'); * } * * // destination.txt will be created or overwritten by default. * copyFile('source.txt', 'destination.txt', callback); * * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); * ``` * @since v8.5.0 * @param src source filename to copy * @param dest destination filename of the copy operation * @param [mode=0] modifiers for copy operation. */ export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; export namespace copyFile { function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise<void>; } /** * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it * already exists. Returns `undefined`. Node.js makes no guarantees about the * atomicity of the copy operation. If an error occurs after the destination file * has been opened for writing, Node.js will attempt to remove the destination. * * `mode` is an optional integer that specifies the behavior * of the copy operation. It is possible to create a mask consisting of the bitwise * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). * * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already * exists. * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a * copy-on-write reflink. If the platform does not support copy-on-write, then a * fallback copy mechanism is used. * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to * create a copy-on-write reflink. If the platform does not support *
copy-on-write, then the operation will fail. * * ```js * import { copyFileSync, constants } from 'node:fs'; * * // destination.txt will be created or overwritten by default. * copyFileSync('source.txt', 'destination.txt'); * console.log('source.txt was copied to destination.txt'); * * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); * ``` * @since v8.5.0 * @param src source filename to copy * @param dest destination filename of the copy operation * @param [mode=0] modifiers for copy operation. */ export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; /** * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. * * `position` is the offset from the beginning of the file where this data * should be written. If `typeof position !== 'number'`, the data will be written * at the current position. * * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. * * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. * * It is unsafe to use `fs.writev()` multiple times on the same file without * waiting for the callback. For this scenario, use {@link createWriteStream}. * * On Linux, positional writes don't work when the file is opened in append mode. * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v12.9.0 * @param [position='null'] */ export function writev( fd: number, buffers: readonly NodeJS.ArrayBufferView[], cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, ): void; export function writev( fd: number, buffers: readonly NodeJS.ArrayBufferView[], position: number, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, ): void; export interface WriteVResult { bytesWritten: number; buffers: NodeJS.ArrayBufferView[]; } export namespace writev { function __promisify__( fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number, ): Promise<WriteVResult>; } /** * For detailed information, see the documentation of the asynchronous version of * this API: {@link writev}. * @since v12.9.0 * @param [position='null'] * @return The number of bytes written. */ export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; /** * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s * using `readv()`. * * `position` is the offset from the beginning of the file from where data * should be read. If `typeof position !== 'number'`, the data will be read * from the current position. * * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. * * If this method is invoked as its `util.promisify()` ed version, it returns * a promise for an `Object` with `bytesRead` and `buffers` properties. * @since v13.13.0, v12.17.0 * @param [position='null'] */ export function readv( fd: number, buffers: readonly NodeJS.ArrayBufferView[], cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, ): void; export function readv( fd: number, buffers: readonly NodeJS.ArrayBufferView[], position:
number, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, ): void; export interface ReadVResult { bytesRead: number; buffers: NodeJS.ArrayBufferView[]; } export namespace readv { function __promisify__( fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number, ): Promise<ReadVResult>; } /** * For detailed information, see the documentation of the asynchronous version of * this API: {@link readv}. * @since v13.13.0, v12.17.0 * @param [position='null'] * @return The number of bytes read. */ export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; export interface OpenAsBlobOptions { /** * An optional mime type for the blob. * * @default 'undefined' */ type?: string | undefined; } /** * Returns a `Blob` whose data is backed by the given file. * * The file must not be modified after the `Blob` is created. Any modifications * will cause reading the `Blob` data to fail with a `DOMException` error. * Synchronous stat operations on the file when the `Blob` is created, and before * each read in order to detect whether the file data has been modified on disk. * * ```js * import { openAsBlob } from 'node:fs'; * * const blob = await openAsBlob('the.file.txt'); * const ab = await blob.arrayBuffer(); * blob.stream(); * ``` * @since v19.8.0 * @experimental */ export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise<Blob>; export interface OpenDirOptions { /** * @default 'utf8' */ encoding?: BufferEncoding | undefined; /** * Number of directory entries that are buffered * internally when reading from the directory. Higher values lead to better * performance but higher memory usage. * @default 32 */ bufferSize?: number | undefined; /** * @default false */ recursive?: boolean; } /** * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). * * Creates an `fs.Dir`, which contains all further functions for reading from * and cleaning up the directory. * * The `encoding` option sets the encoding for the `path` while opening the * directory and subsequent read operations. * @since v12.12.0 */ export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; /** * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for * more details. * * Creates an `fs.Dir`, which contains all further functions for reading from * and cleaning up the directory. * * The `encoding` option sets the encoding for the `path` while opening the * directory and subsequent read operations. * @since v12.12.0 */ export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; export function opendir( path: PathLike, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, ): void; export namespace opendir { function __promisify__(path: PathLike, options?: OpenDirOptions): Promise<Dir>; } export interface BigIntStats extends StatsBase<bigint> { atimeNs: bigint; mtimeNs: bigint; ctimeNs: bigint; birthtimeNs: bigint; } export interface BigIntOptions { bigint: true; } export interface StatOptions { bigint?: boolean | undefined; } export interface StatSyncOptions extends StatOptions {
throwIfNoEntry?: boolean | undefined; } interface CopyOptionsBase { /** * Dereference symlinks * @default false */ dereference?: boolean; /** * When `force` is `false`, and the destination * exists, throw an error. * @default false */ errorOnExist?: boolean; /** * Overwrite existing file or directory. _The copy * operation will ignore errors if you set this to false and the destination * exists. Use the `errorOnExist` option to change this behavior. * @default true */ force?: boolean; /** * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} */ mode?: number; /** * When `true` timestamps from `src` will * be preserved. * @default false */ preserveTimestamps?: boolean; /** * Copy directories recursively. * @default false */ recursive?: boolean; /** * When true, path resolution for symlinks will be skipped * @default false */ verbatimSymlinks?: boolean; } export interface CopyOptions extends CopyOptionsBase { /** * Function to filter copied files/directories. Return * `true` to copy the item, `false` to ignore it. */ filter?(source: string, destination: string): boolean | Promise<boolean>; } export interface CopySyncOptions extends CopyOptionsBase { /** * Function to filter copied files/directories. Return * `true` to copy the item, `false` to ignore it. */ filter?(source: string, destination: string): boolean; } /** * Asynchronously copies the entire directory structure from `src` to `dest`, * including subdirectories and files. * * When copying a directory to another directory, globs are not supported and * behavior is similar to `cp dir1/ dir2/`. * @since v16.7.0 * @experimental * @param src source path to copy. * @param dest destination path to copy to. */ export function cp( source: string | URL, destination: string | URL, callback: (err: NodeJS.ErrnoException | null) => void, ): void; export function cp( source: string | URL, destination: string | URL, opts: CopyOptions, callback: (err: NodeJS.ErrnoException | null) => void, ): void; /** * Synchronously copies the entire directory structure from `src` to `dest`, * including subdirectories and files. * * When copying a directory to another directory, globs are not supported and * behavior is similar to `cp dir1/ dir2/`. * @since v16.7.0 * @experimental * @param src source path to copy. * @param dest destination path to copy to. */ export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; } declare module "node:fs" { export * from "fs"; }
/** * The `node:child_process` module provides the ability to spawn subprocesses in * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability * is primarily provided by the {@link spawn} function: * * ```js * const { spawn } = require('node:child_process'); * const ls = spawn('ls', ['-lh', '/usr']); * * ls.stdout.on('data', (data) => { * console.log(`stdout: ${data}`); * }); * * ls.stderr.on('data', (data) => { * console.error(`stderr: ${data}`); * }); * * ls.on('close', (code) => { * console.log(`child process exited with code ${code}`); * }); * ``` * * By default, pipes for `stdin`, `stdout`, and `stderr` are established between * the parent Node.js process and the spawned subprocess. These pipes have * limited (and platform-specific) capacity. If the subprocess writes to * stdout in excess of that limit without the output being captured, the * subprocess blocks waiting for the pipe buffer to accept more data. This is * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. * * The command lookup is performed using the `options.env.PATH` environment * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is * used. If `options.env` is set without `PATH`, lookup on Unix is performed * on a default search path search of `/usr/bin:/bin` (see your operating system's * manual for execvpe/execvp), on Windows the current processes environment * variable `PATH` is used. * * On Windows, environment variables are case-insensitive. Node.js * lexicographically sorts the `env` keys and uses the first one that * case-insensitively matches. Only first (in lexicographic order) entry will be * passed to the subprocess. This might lead to issues on Windows when passing * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. * * The {@link spawn} method spawns the child process asynchronously, * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks * the event loop until the spawned process either exits or is terminated. * * For convenience, the `node:child_process` module provides a handful of * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on * top of {@link spawn} or {@link spawnSync}. * * * {@link exec}: spawns a shell and runs a command within that * shell, passing the `stdout` and `stderr` to a callback function when * complete. * * {@link execFile}: similar to {@link exec} except * that it spawns the command directly without first spawning a shell by * default. * * {@link fork}: spawns a new Node.js process and invokes a * specified module with an IPC communication channel established that allows * sending messages between parent and child. * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. * * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, * the synchronous methods can have significant impact on performance due to * stalling the event loop while spawned processes complete. * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/child_process.js) */ declare module "child_process" { import { ObjectEncodingOptions } from "node:fs"; import { Abortable, EventEmitter } from "node:events"; import * as net from "node:net"; import { Pipe, Readable, Stream, Writable } from "node:stream"; import { URL } from "node:url"; type Serializable = string | object | number | boolean | bigint; type SendHandle = net.Socket | net.Server; /**
* Instances of the `ChildProcess` represent spawned child processes. * * Instances of `ChildProcess` are not intended to be created directly. Rather, * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create * instances of `ChildProcess`. * @since v2.2.0 */ class ChildProcess extends EventEmitter { /** * A `Writable Stream` that represents the child process's `stdin`. * * If a child process waits to read all of its input, the child will not continue * until this stream has been closed via `end()`. * * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, * then this will be `null`. * * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will * refer to the same value. * * The `subprocess.stdin` property can be `null` or `undefined`if the child process could not be successfully spawned. * @since v0.1.90 */ stdin: Writable | null; /** * A `Readable Stream` that represents the child process's `stdout`. * * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, * then this will be `null`. * * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will * refer to the same value. * * ```js * const { spawn } = require('node:child_process'); * * const subprocess = spawn('ls'); * * subprocess.stdout.on('data', (data) => { * console.log(`Received chunk ${data}`); * }); * ``` * * The `subprocess.stdout` property can be `null` or `undefined`if the child process could not be successfully spawned. * @since v0.1.90 */ stdout: Readable | null; /** * A `Readable Stream` that represents the child process's `stderr`. * * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, * then this will be `null`. * * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will * refer to the same value. * * The `subprocess.stderr` property can be `null` or `undefined`if the child process could not be successfully spawned. * @since v0.1.90 */ stderr: Readable | null; /** * The `subprocess.channel` property is a reference to the child's IPC channel. If * no IPC channel exists, this property is `undefined`. * @since v7.1.0 */ readonly channel?: Pipe | null | undefined; /** * A sparse array of pipes to the child process, corresponding with positions in * the `stdio` option passed to {@link spawn} that have been set * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, * respectively. * * In the following example, only the child's fd `1` (stdout) is configured as a * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values * in the array are `null`. * * ```js * const assert = require('node:assert'); * const fs = require('node:fs'); * const child_process = require('node:child_process'); * * const subprocess = child_process.spawn('ls', { * stdio: [ * 0, // Use parent's stdin for child. * 'pipe', // Pipe child's stdout to parent. * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. * ], * }); * * assert.strictEqual(subprocess.stdio[0], null); * assert.strictEqua
l(subprocess.stdio[0], subprocess.stdin); * * assert(subprocess.stdout); * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); * * assert.strictEqual(subprocess.stdio[2], null); * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); * ``` * * The `subprocess.stdio` property can be `undefined` if the child process could * not be successfully spawned. * @since v0.7.10 */ readonly stdio: [ Writable | null, // stdin Readable | null, // stdout Readable | null, // stderr Readable | Writable | null | undefined, // extra Readable | Writable | null | undefined, // extra ]; /** * The `subprocess.killed` property indicates whether the child process * successfully received a signal from `subprocess.kill()`. The `killed` property * does not indicate that the child process has been terminated. * @since v0.5.10 */ readonly killed: boolean; /** * Returns the process identifier (PID) of the child process. If the child process * fails to spawn due to errors, then the value is `undefined` and `error` is * emitted. * * ```js * const { spawn } = require('node:child_process'); * const grep = spawn('grep', ['ssh']); * * console.log(`Spawned child pid: ${grep.pid}`); * grep.stdin.end(); * ``` * @since v0.1.90 */ readonly pid?: number | undefined; /** * The `subprocess.connected` property indicates whether it is still possible to * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. * @since v0.7.2 */ readonly connected: boolean; /** * The `subprocess.exitCode` property indicates the exit code of the child process. * If the child process is still running, the field will be `null`. */ readonly exitCode: number | null; /** * The `subprocess.signalCode` property indicates the signal received by * the child process if any, else `null`. */ readonly signalCode: NodeJS.Signals | null; /** * The `subprocess.spawnargs` property represents the full list of command-line * arguments the child process was launched with. */ readonly spawnargs: string[]; /** * The `subprocess.spawnfile` property indicates the executable file name of * the child process that is launched. * * For {@link fork}, its value will be equal to `process.execPath`. * For {@link spawn}, its value will be the name of * the executable file. * For {@link exec}, its value will be the name of the shell * in which the child process is launched. */ readonly spawnfile: string; /** * The `subprocess.kill()` method sends a signal to the child process. If no * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. * * ```js * const { spawn } = require('node:child_process'); * const grep = spawn('grep', ['ssh']); * * grep.on('close', (code, signal) => { * console.log( * `child process terminated due to receipt of signal ${signal}`); * }); * * // Send SIGHUP to process. * grep.kill('SIGHUP'); * ``` *
* The `ChildProcess` object may emit an `'error'` event if the signal * cannot be delivered. Sending a signal to a child process that has already exited * is not an error but may have unforeseen consequences. Specifically, if the * process identifier (PID) has been reassigned to another process, the signal will * be delivered to that process instead which can have unexpected results. * * While the function is called `kill`, the signal delivered to the child process * may not actually terminate the process. * * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. * * On Windows, where POSIX signals do not exist, the `signal` argument will be * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). * See `Signal Events` for more details. * * On Linux, child processes of child processes will not be terminated * when attempting to kill their parent. This is likely to happen when running a * new process in a shell or with the use of the `shell` option of `ChildProcess`: * * ```js * 'use strict'; * const { spawn } = require('node:child_process'); * * const subprocess = spawn( * 'sh', * [ * '-c', * `node -e "setInterval(() => { * console.log(process.pid, 'is alive') * }, 500);"`, * ], { * stdio: ['inherit', 'inherit', 'inherit'], * }, * ); * * setTimeout(() => { * subprocess.kill(); // Does not terminate the Node.js process in the shell. * }, 2000); * ``` * @since v0.1.90 */ kill(signal?: NodeJS.Signals | number): boolean; /** * Calls {@link ChildProcess.kill} with `'SIGTERM'`. * @since v20.5.0 */ [Symbol.dispose](): void; /** * When an IPC channel has been established between the parent and child ( * i.e. when using {@link fork}), the `subprocess.send()` method can * be used to send messages to the child process. When the child process is a * Node.js instance, these messages can be received via the `'message'` event. * * The message goes through serialization and parsing. The resulting * message might not be the same as what is originally sent. * * For example, in the parent script: * * ```js * const cp = require('node:child_process'); * const n = cp.fork(`${__dirname}/sub.js`); * * n.on('message', (m) => { * console.log('PARENT got message:', m); * }); * * // Causes the child to print: CHILD got message: { hello: 'world' } * n.send({ hello: 'world' }); * ``` * * And then the child script, `'sub.js'` might look like this: * * ```js * process.on('message', (m) => { * console.log('CHILD got message:', m); * }); * * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } * process.send({ foo: 'bar', baz: NaN }); * ``` * * Child Node.js processes will have a `process.send()` method of their own * that allows the child to send messages back to the parent. * * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages * containing a `NODE_` prefix in the `cmd` property are reserved for use within * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. * Applications should avoid using such messages or listening for`'
internalMessage'` events as it is subject to change without notice. * * The optional `sendHandle` argument that may be passed to `subprocess.send()` is * for passing a TCP server or socket object to the child process. The child will * receive the object as the second argument passed to the callback function * registered on the `'message'` event. Any data that is received * and buffered in the socket will not be sent to the child. * * The optional `callback` is a function that is invoked after the message is * sent but before the child may have received it. The function is called with a * single argument: `null` on success, or an `Error` object on failure. * * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can * happen, for instance, when the child process has already exited. * * `subprocess.send()` will return `false` if the channel has closed or when the * backlog of unsent messages exceeds a threshold that makes it unwise to send * more. Otherwise, the method returns `true`. The `callback` function can be * used to implement flow control. * * #### Example: sending a server object * * The `sendHandle` argument can be used, for instance, to pass the handle of * a TCP server object to the child process as illustrated in the example below: * * ```js * const subprocess = require('node:child_process').fork('subprocess.js'); * * // Open up the server object and send the handle. * const server = require('node:net').createServer(); * server.on('connection', (socket) => { * socket.end('handled by parent'); * }); * server.listen(1337, () => { * subprocess.send('server', server); * }); * ``` * * The child would then receive the server object as: * * ```js * process.on('message', (m, server) => { * if (m === 'server') { * server.on('connection', (socket) => { * socket.end('handled by child'); * }); * } * }); * ``` * * Once the server is now shared between the parent and child, some connections * can be handled by the parent and some by the child. * * While the example above uses a server created using the `node:net` module,`node:dgram` module servers use exactly the same workflow with the exceptions of * listening on a `'message'` event instead of `'connection'` and using`server.bind()` instead of `server.listen()`. This is, however, only * supported on Unix platforms. * * #### Example: sending a socket object * * Similarly, the `sendHandler` argument can be used to pass the handle of a * socket to the child process. The example below spawns two children that each * handle connections with "normal" or "special" priority: * * ```js * const { fork } = require('node:child_process'); * const normal = fork('subprocess.js', ['normal']); * const special = fork('subprocess.js', ['special']); * * // Open up the server and send sockets to child. Use pauseOnConnect to prevent * // the sockets from being read before they are sent to the child process. * const server = require('node:net').createServer({ pauseOnConnect: true }); * server.on('connection', (socket) => { * * // If this is special priority... * if (socket.remoteAddress === '74.125.127.100') { * special.send('socket', socket); * return; * } * // This is normal priority.
* normal.send('socket', socket); * }); * server.listen(1337); * ``` * * The `subprocess.js` would receive the socket handle as the second argument * passed to the event callback function: * * ```js * process.on('message', (m, socket) => { * if (m === 'socket') { * if (socket) { * // Check that the client socket exists. * // It is possible for the socket to be closed between the time it is * // sent and the time it is received in the child process. * socket.end(`Request handled with ${process.argv[2]} priority`); * } * } * }); * ``` * * Do not use `.maxConnections` on a socket that has been passed to a subprocess. * The parent cannot track when the socket is destroyed. * * Any `'message'` handlers in the subprocess should verify that `socket` exists, * as the connection may have been closed during the time it takes to send the * connection to the child. * @since v0.5.9 * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: */ send(message: Serializable, callback?: (error: Error | null) => void): boolean; send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; send( message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void, ): boolean; /** * Closes the IPC channel between parent and child, allowing the child to exit * gracefully once there are no other connections keeping it alive. After calling * this method the `subprocess.connected` and `process.connected` properties in * both the parent and child (respectively) will be set to `false`, and it will be * no longer possible to pass messages between the processes. * * The `'disconnect'` event will be emitted when there are no messages in the * process of being received. This will most often be triggered immediately after * calling `subprocess.disconnect()`. * * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked * within the child process to close the IPC channel as well. * @since v0.7.2 */ disconnect(): void; /** * By default, the parent will wait for the detached child to exit. To prevent the * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not * include the child in its reference count, allowing the parent to exit * independently of the child, unless there is an established IPC channel between * the child and the parent. * * ```js * const { spawn } = require('node:child_process'); * * const subprocess = spawn(process.argv[0], ['child_program.js'], { * detached: true, * stdio: 'ignore', * }); * * subprocess.unref(); * ``` * @since v0.7.10 */ unref(): void; /** * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will * restore the removed reference count for the child process, forcing the parent * to wait for the child to exit before exiting itself. * * ```js * const { spawn } = require('node:child_process'); * * const subprocess = spawn(process.argv[0], ['child_program.js'], { * detached:
true, * stdio: 'ignore', * }); * * subprocess.unref(); * subprocess.ref(); * ``` * @since v0.7.10 */ ref(): void; /** * events.EventEmitter * 1. close * 2. disconnect * 3. error * 4. exit * 5. message * 6. spawn */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; addListener(event: "disconnect", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; addListener(event: "spawn", listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; emit(event: "disconnect"): boolean; emit(event: "error", err: Error): boolean; emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; emit(event: "spawn", listener: () => void): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; on(event: "disconnect", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; on(event: "spawn", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; once(event: "disconnect", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; once(event: "spawn", listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; prependListener(event: "disconnect", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; prependListener(event: "spawn", listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener( event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void, ): this; prependOnceListener(event: "disconnect", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener( event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void, ): this; prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; prependOnceLi
stener(event: "spawn", listener: () => void): this; } // return this object when stdio option is undefined or not specified interface ChildProcessWithoutNullStreams extends ChildProcess { stdin: Writable; stdout: Readable; stderr: Readable; readonly stdio: [ Writable, Readable, Readable, // stderr Readable | Writable | null | undefined, // extra, no modification Readable | Writable | null | undefined, // extra, no modification ]; } // return this object when stdio option is a tuple of 3 interface ChildProcessByStdio<I extends null | Writable, O extends null | Readable, E extends null | Readable> extends ChildProcess { stdin: I; stdout: O; stderr: E; readonly stdio: [ I, O, E, Readable | Writable | null | undefined, // extra, no modification Readable | Writable | null | undefined, // extra, no modification ]; } interface MessageOptions { keepOpen?: boolean | undefined; } type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; type StdioOptions = IOType | Array<IOType | "ipc" | Stream | number | null | undefined>; type SerializationType = "json" | "advanced"; interface MessagingOptions extends Abortable { /** * Specify the kind of serialization used for sending messages between processes. * @default 'json' */ serialization?: SerializationType | undefined; /** * The signal value to be used when the spawned process will be killed by the abort signal. * @default 'SIGTERM' */ killSignal?: NodeJS.Signals | number | undefined; /** * In milliseconds the maximum amount of time the process is allowed to run. */ timeout?: number | undefined; } interface ProcessEnvOptions { uid?: number | undefined; gid?: number | undefined; cwd?: string | URL | undefined; env?: NodeJS.ProcessEnv | undefined; } interface CommonOptions extends ProcessEnvOptions { /** * @default false */ windowsHide?: boolean | undefined; /** * @default 0 */ timeout?: number | undefined; } interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { argv0?: string | undefined; /** * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. * If passed as an array, the first element is used for `stdin`, the second for * `stdout`, and the third for `stderr`. A fourth element can be used to * specify the `stdio` behavior beyond the standard streams. See * {@link ChildProcess.stdio} for more information. * * @default 'pipe' */ stdio?: StdioOptions | undefined; shell?: boolean | string | undefined; windowsVerbatimArguments?: boolean | undefined; } interface SpawnOptions extends CommonSpawnOptions { detached?: boolean | undefined; } interface SpawnOptionsWithoutStdio extends SpawnOptions { stdio?: StdioPipeNamed | StdioPipe[] | undefined; } type StdioNull = "inherit" | "ignore" | Stream; type StdioPipeNamed = "pipe" | "overlapped"; type StdioPipe = undefined | null | StdioPipeNamed; interface SpawnOptionsWithStdioTuple< Stdin extends StdioNull | StdioPipe, Stdout extends StdioNull | StdioPipe, Stderr extends StdioNull | StdioPipe, > extends SpawnOptions { stdio: [Stdin, Stdout, Stderr]; } /** * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults * to an empty array. *
* **If the `shell` option is enabled, do not pass unsanitized user input to this** * **function. Any input containing shell metacharacters may be used to trigger** * **arbitrary command execution.** * * A third argument may be used to specify additional options, with these defaults: * * ```js * const defaults = { * cwd: undefined, * env: process.env, * }; * ``` * * Use `cwd` to specify the working directory from which the process is spawned. * If not given, the default is to inherit the current working directory. If given, * but the path does not exist, the child process emits an `ENOENT` error * and exits immediately. `ENOENT` is also emitted when the command * does not exist. * * Use `env` to specify environment variables that will be visible to the new * process, the default is `process.env`. * * `undefined` values in `env` will be ignored. * * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the * exit code: * * ```js * const { spawn } = require('node:child_process'); * const ls = spawn('ls', ['-lh', '/usr']); * * ls.stdout.on('data', (data) => { * console.log(`stdout: ${data}`); * }); * * ls.stderr.on('data', (data) => { * console.error(`stderr: ${data}`); * }); * * ls.on('close', (code) => { * console.log(`child process exited with code ${code}`); * }); * ``` * * Example: A very elaborate way to run `ps ax | grep ssh` * * ```js * const { spawn } = require('node:child_process'); * const ps = spawn('ps', ['ax']); * const grep = spawn('grep', ['ssh']); * * ps.stdout.on('data', (data) => { * grep.stdin.write(data); * }); * * ps.stderr.on('data', (data) => { * console.error(`ps stderr: ${data}`); * }); * * ps.on('close', (code) => { * if (code !== 0) { * console.log(`ps process exited with code ${code}`); * } * grep.stdin.end(); * }); * * grep.stdout.on('data', (data) => { * console.log(data.toString()); * }); * * grep.stderr.on('data', (data) => { * console.error(`grep stderr: ${data}`); * }); * * grep.on('close', (code) => { * if (code !== 0) { * console.log(`grep process exited with code ${code}`); * } * }); * ``` * * Example of checking for failed `spawn`: * * ```js * const { spawn } = require('node:child_process'); * const subprocess = spawn('bad_command'); * * subprocess.on('error', (err) => { * console.error('Failed to start subprocess.'); * }); * ``` * * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process * title while others (Windows, SunOS) will use `command`. * * Node.js overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent. Retrieve * it with the`process.argv0` property instead. * * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js * const { spawn } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const grep = spawn('grep', ['ssh'], { signal }); * grep.on('error', (err) => { * // This will be called with err being an AbortError if the controller aborts * }); * controller.abort(); // Stops the child process * ``` * @since v0.1.90 * @param command The command to run. * @param args List of string arguments. */ funct
ion spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; function spawn( command: string, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>, ): ChildProcessByStdio<Writable, Readable, Readable>; function spawn( command: string, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>, ): ChildProcessByStdio<Writable, Readable, null>; function spawn( command: string, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>, ): ChildProcessByStdio<Writable, null, Readable>; function spawn( command: string, options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>, ): ChildProcessByStdio<null, Readable, Readable>; function spawn( command: string, options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>, ): ChildProcessByStdio<Writable, null, null>; function spawn( command: string, options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>, ): ChildProcessByStdio<null, Readable, null>; function spawn( command: string, options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>, ): ChildProcessByStdio<null, null, Readable>; function spawn( command: string, options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>, ): ChildProcessByStdio<null, null, null>; function spawn(command: string, options: SpawnOptions): ChildProcess; // overloads of spawn with 'args' function spawn( command: string, args?: readonly string[], options?: SpawnOptionsWithoutStdio, ): ChildProcessWithoutNullStreams; function spawn( command: string, args: readonly string[], options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>, ): ChildProcessByStdio<Writable, Readable, Readable>; function spawn( command: string, args: readonly string[], options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>, ): ChildProcessByStdio<Writable, Readable, null>; function spawn( command: string, args: readonly string[], options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>, ): ChildProcessByStdio<Writable, null, Readable>; function spawn( command: string, args: readonly string[], options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>, ): ChildProcessByStdio<null, Readable, Readable>; function spawn( command: string, args: readonly string[], options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>, ): ChildProcessByStdio<Writable, null, null>; function spawn( command: string, args: readonly string[], options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>, ): ChildProcessByStdio<null, Readable, null>; function spawn( command: string, args: readonly string[], options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>, ): ChildProcessByStdio<null, null, Readable>; function spawn( command: string, args: readonly string[], options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>, ): ChildProcessByStdio<null, null, null>; function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; interface ExecOptions extends CommonOptions { shell?: string | undefined; signal?: AbortSignal | undefined; maxBuffer?: number | undefined; killSignal?: NodeJS.Signals | number | undefined; } interface ExecOptionsWithStringEncoding extends ExecOptions { encoding: BufferEncoding; } interface ExecOptionsWithBufferEncoding extends ExecOptions { encoding: BufferEncoding | null; // specify `null`.
} interface ExecException extends Error { cmd?: string | undefined; killed?: boolean | undefined; code?: number | undefined; signal?: NodeJS.Signals | undefined; } /** * Spawns a shell then executes the `command` within that shell, buffering any * generated output. The `command` string passed to the exec function is processed * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) * need to be dealt with accordingly: * * ```js * const { exec } = require('node:child_process'); * * exec('"/path/to/test file/test.sh" arg1 arg2'); * // Double quotes are used so that the space in the path is not interpreted as * // a delimiter of multiple arguments. * * exec('echo "The \\$HOME variable is $HOME"'); * // The $HOME variable is escaped in the first instance, but not in the second. * ``` * * **Never pass unsanitized user input to this function. Any input containing shell** * **metacharacters may be used to trigger arbitrary command execution.** * * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The * `error.code` property will be * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the * process. * * The `stdout` and `stderr` arguments passed to the callback will contain the * stdout and stderr output of the child process. By default, Node.js will decode * the output as UTF-8 and pass strings to the callback. The `encoding` option * can be used to specify the character encoding used to decode the stdout and * stderr output. If `encoding` is `'buffer'`, or an unrecognized character * encoding, `Buffer` objects will be passed to the callback instead. * * ```js * const { exec } = require('node:child_process'); * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { * if (error) { * console.error(`exec error: ${error}`); * return; * } * console.log(`stdout: ${stdout}`); * console.error(`stderr: ${stderr}`); * }); * ``` * * If `timeout` is greater than `0`, the parent will send the signal * identified by the `killSignal` property (the default is `'SIGTERM'`) if the * child runs longer than `timeout` milliseconds. * * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace * the existing process and uses a shell to execute the command. * * If this method is invoked as its `util.promisify()` ed version, it returns * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In * case of an error (including any error resulting in an exit code other than 0), a * rejected promise is returned, with the same `error` object given in the * callback, but with two additional properties `stdout` and `stderr`. * * ```js * const util = require('node:util'); * const exec = util.promisify(require('node:child_process').exec); * * async function lsExample() { * const { stdout, stderr } = await exec('ls'); * console.log('stdout:', stdout); * console.error('stderr:', stderr); * } * lsExample(); * ``` * * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js * const { exec } = require('node:
child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = exec('grep ssh', { signal }, (error) => { * console.error(error); // an AbortError * }); * controller.abort(); * ``` * @since v0.1.90 * @param command The command to run, with space-separated arguments. * @param callback called with the output when process terminates. */ function exec( command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void, ): ChildProcess; // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. function exec( command: string, options: { encoding: "buffer" | null; } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, ): ChildProcess; // `options` with well known `encoding` means stdout/stderr are definitely `string`. function exec( command: string, options: { encoding: BufferEncoding; } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void, ): ChildProcess; // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. function exec( command: string, options: { encoding: BufferEncoding; } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, ): ChildProcess; // `options` without an `encoding` means stdout/stderr are definitely `string`. function exec( command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void, ): ChildProcess; // fallback if nothing else matches. Worst case is always `string | Buffer`. function exec( command: string, options: (ObjectEncodingOptions & ExecOptions) | undefined | null, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, ): ChildProcess; interface PromiseWithChild<T> extends Promise<T> { child: ChildProcess; } namespace exec { function __promisify__(command: string): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( command: string, options: { encoding: "buffer" | null; } & ExecOptions, ): PromiseWithChild<{ stdout: Buffer; stderr: Buffer; }>; function __promisify__( command: string, options: { encoding: BufferEncoding; } & ExecOptions, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( command: string, options: ExecOptions, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( command: string, options?: (ObjectEncodingOptions & ExecOptions) | null, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; }>; } interface ExecFileOptions extends CommonOptions, Abortable { maxBuffer?: number | undefined; killSignal?: NodeJS.Signals | number | undefined; windowsVerbatimArguments?: boolean | undefined; shell?: boolean | string | undefined; signal?: AbortSignal | undefined; } interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { encoding: BufferEncoding; } interface ExecFileOptionsWithBufferEnc
oding extends ExecFileOptions { encoding: "buffer" | null; } interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { encoding: BufferEncoding; } type ExecFileException = & Omit<ExecException, "code"> & Omit<NodeJS.ErrnoException, "code"> & { code?: string | number | undefined | null }; /** * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified * executable `file` is spawned directly as a new process making it slightly more * efficient than {@link exec}. * * The same options as {@link exec} are supported. Since a shell is * not spawned, behaviors such as I/O redirection and file globbing are not * supported. * * ```js * const { execFile } = require('node:child_process'); * const child = execFile('node', ['--version'], (error, stdout, stderr) => { * if (error) { * throw error; * } * console.log(stdout); * }); * ``` * * The `stdout` and `stderr` arguments passed to the callback will contain the * stdout and stderr output of the child process. By default, Node.js will decode * the output as UTF-8 and pass strings to the callback. The `encoding` option * can be used to specify the character encoding used to decode the stdout and * stderr output. If `encoding` is `'buffer'`, or an unrecognized character * encoding, `Buffer` objects will be passed to the callback instead. * * If this method is invoked as its `util.promisify()` ed version, it returns * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In * case of an error (including any error resulting in an exit code other than 0), a * rejected promise is returned, with the same `error` object given in the * callback, but with two additional properties `stdout` and `stderr`. * * ```js * const util = require('node:util'); * const execFile = util.promisify(require('node:child_process').execFile); * async function getVersion() { * const { stdout } = await execFile('node', ['--version']); * console.log(stdout); * } * getVersion(); * ``` * * **If the `shell` option is enabled, do not pass unsanitized user input to this** * **function. Any input containing shell metacharacters may be used to trigger** * **arbitrary command execution.** * * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js * const { execFile } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = execFile('node', ['--version'], { signal }, (error) => { * console.error(error); // an AbortError * }); * controller.abort(); * ``` * @since v0.1.91 * @param file The name or path of the executable file to run. * @param args List of string arguments. * @param callback Called with the output when process terminates. */ function execFile(file: string): ChildProcess; function execFile( file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, ): ChildProcess; function execFile(file: string, args?: readonly string[] | null): ChildProcess; function execFile( file: string, args: readonly string[] | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, ): ChildProcess; // no `options` definitely means stdout/stderr are `string`. function execFile( file: string, callback: (
error: ExecFileException | null, stdout: string, stderr: string) => void, ): ChildProcess; function execFile( file: string, args: readonly string[] | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, ): ChildProcess; // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. function execFile( file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, ): ChildProcess; function execFile( file: string, args: readonly string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, ): ChildProcess; // `options` with well known `encoding` means stdout/stderr are definitely `string`. function execFile( file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, ): ChildProcess; function execFile( file: string, args: readonly string[] | undefined | null, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, ): ChildProcess; // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. function execFile( file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, ): ChildProcess; function execFile( file: string, args: readonly string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding, callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, ): ChildProcess; // `options` without an `encoding` means stdout/stderr are definitely `string`. function execFile( file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, ): ChildProcess; function execFile( file: string, args: readonly string[] | undefined | null, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, ): ChildProcess; // fallback if nothing else matches. Worst case is always `string | Buffer`. function execFile( file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, callback: | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, ): ChildProcess; function execFile( file: string, args: readonly string[] | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, callback: | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, ): ChildProcess; namespace execFile { function __promisify__(file: string): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, args: readonly string[] | undefined | null, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, options: ExecFileOptionsWithBufferEncoding, ): PromiseWithChild<{ stdout: Buffer;
stderr: Buffer; }>; function __promisify__( file: string, args: readonly string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding, ): PromiseWithChild<{ stdout: Buffer; stderr: Buffer; }>; function __promisify__( file: string, options: ExecFileOptionsWithStringEncoding, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, args: readonly string[] | undefined | null, options: ExecFileOptionsWithStringEncoding, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, options: ExecFileOptionsWithOtherEncoding, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; }>; function __promisify__( file: string, args: readonly string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; }>; function __promisify__( file: string, options: ExecFileOptions, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, args: readonly string[] | undefined | null, options: ExecFileOptions, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; }>; function __promisify__( file: string, args: readonly string[] | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; }>; } interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { execPath?: string | undefined; execArgv?: string[] | undefined; silent?: boolean | undefined; /** * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. * If passed as an array, the first element is used for `stdin`, the second for * `stdout`, and the third for `stderr`. A fourth element can be used to * specify the `stdio` behavior beyond the standard streams. See * {@link ChildProcess.stdio} for more information. * * @default 'pipe' */ stdio?: StdioOptions | undefined; detached?: boolean | undefined; windowsVerbatimArguments?: boolean | undefined; } /** * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. * Like {@link spawn}, a `ChildProcess` object is returned. The * returned `ChildProcess` will have an additional communication channel * built-in that allows messages to be passed back and forth between the parent and * child. See `subprocess.send()` for details. * * Keep in mind that spawned Node.js child processes are * independent of the parent with exception of the IPC communication channel * that is established between the two. Each process has its own memory, with * their own V8 instances. Because of the additional resource allocations * required, spawning a large number of child Node.js processes is not * recommended. * * By default, `child_process.fork(
)` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative * execution path to be used. * * Node.js processes launched with a custom `execPath` will communicate with the * parent process using the file descriptor (fd) identified using the * environment variable `NODE_CHANNEL_FD` on the child process. * * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the * current process. * * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. * * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js * if (process.argv[2] === 'child') { * setTimeout(() => { * console.log(`Hello from ${process.argv[2]}!`); * }, 1_000); * } else { * const { fork } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = fork(__filename, ['child'], { signal }); * child.on('error', (err) => { * // This will be called with err being an AbortError if the controller aborts * }); * controller.abort(); // Stops the child process * } * ``` * @since v0.5.0 * @param modulePath The module to run in the child. * @param args List of string arguments. */ function fork(modulePath: string, options?: ForkOptions): ChildProcess; function fork(modulePath: string, args?: readonly string[], options?: ForkOptions): ChildProcess; interface SpawnSyncOptions extends CommonSpawnOptions { input?: string | NodeJS.ArrayBufferView | undefined; maxBuffer?: number | undefined; encoding?: BufferEncoding | "buffer" | null | undefined; } interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { encoding: BufferEncoding; } interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { encoding?: "buffer" | null | undefined; } interface SpawnSyncReturns<T> { pid: number; output: Array<T | null>; stdout: T; stderr: T; status: number | null; signal: NodeJS.Signals | null; error?: Error | undefined; } /** * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return * until the child process has fully closed. When a timeout has been encountered * and `killSignal` is sent, the method won't return until the process has * completely exited. If the process intercepts and handles the `SIGTERM` signal * and doesn't exit, the parent process will wait until the child process has * exited. * * **If the `shell` option is enabled, do not pass unsanitized user input to this** * **function. Any input containing shell metacharacters may be used to trigger** * **arbitrary command execution.** * @since v0.11.12 * @param command The command to run. * @param args List of string arguments. */ function spawnSync(command: string): SpawnSyncReturns<Buffer>; function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>; function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>; function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<string | Buffer>; function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns<Buffer>; function spawnSync( command: string, args: readonly string[],
options: SpawnSyncOptionsWithStringEncoding, ): SpawnSyncReturns<string>; function spawnSync( command: string, args: readonly string[], options: SpawnSyncOptionsWithBufferEncoding, ): SpawnSyncReturns<Buffer>; function spawnSync( command: string, args?: readonly string[], options?: SpawnSyncOptions, ): SpawnSyncReturns<string | Buffer>; interface CommonExecOptions extends CommonOptions { input?: string | NodeJS.ArrayBufferView | undefined; /** * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. * If passed as an array, the first element is used for `stdin`, the second for * `stdout`, and the third for `stderr`. A fourth element can be used to * specify the `stdio` behavior beyond the standard streams. See * {@link ChildProcess.stdio} for more information. * * @default 'pipe' */ stdio?: StdioOptions | undefined; killSignal?: NodeJS.Signals | number | undefined; maxBuffer?: number | undefined; encoding?: BufferEncoding | "buffer" | null | undefined; } interface ExecSyncOptions extends CommonExecOptions { shell?: string | undefined; } interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { encoding: BufferEncoding; } interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { encoding?: "buffer" | null | undefined; } /** * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return * until the child process has fully closed. When a timeout has been encountered * and `killSignal` is sent, the method won't return until the process has * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process * has exited. * * If the process times out or has a non-zero exit code, this method will throw. * The `Error` object will contain the entire result from {@link spawnSync}. * * **Never pass unsanitized user input to this function. Any input containing shell** * **metacharacters may be used to trigger arbitrary command execution.** * @since v0.11.12 * @param command The command to run. * @return The stdout from the command. */ function execSync(command: string): Buffer; function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; function execSync(command: string, options?: ExecSyncOptions): string | Buffer; interface ExecFileSyncOptions extends CommonExecOptions { shell?: boolean | string | undefined; } interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { encoding: BufferEncoding; } interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { encoding?: "buffer" | null; // specify `null`. } /** * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not * return until the child process has fully closed. When a timeout has been * encountered and `killSignal` is sent, the method won't return until the process * has completely exited. * * If the child process intercepts and handles the `SIGTERM` signal and * does not exit, the parent process will still wait until the child process has * exited. * * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. * * **If the `shell` option is enabled, do not pass unsanitized user input to this** * **function. Any inp
ut containing shell metacharacters may be used to trigger** * **arbitrary command execution.** * @since v0.11.12 * @param file The name or path of the executable file to run. * @param args List of string arguments. * @return The stdout from the command. */ function execFileSync(file: string): Buffer; function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; function execFileSync(file: string, args: readonly string[]): Buffer; function execFileSync( file: string, args: readonly string[], options: ExecFileSyncOptionsWithStringEncoding, ): string; function execFileSync( file: string, args: readonly string[], options: ExecFileSyncOptionsWithBufferEncoding, ): Buffer; function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; } declare module "node:child_process" { export * from "child_process"; }
/** * @since v0.3.7 * @experimental */ declare module "module" { import { URL } from "node:url"; import { MessagePort } from "node:worker_threads"; namespace Module { /** * The `module.syncBuiltinESMExports()` method updates all the live bindings for * builtin `ES Modules` to match the properties of the `CommonJS` exports. It * does not add or remove exported names from the `ES Modules`. * * ```js * const fs = require('node:fs'); * const assert = require('node:assert'); * const { syncBuiltinESMExports } = require('node:module'); * * fs.readFile = newAPI; * * delete fs.readFileSync; * * function newAPI() { * // ... * } * * fs.newAPI = newAPI; * * syncBuiltinESMExports(); * * import('node:fs').then((esmFS) => { * // It syncs the existing readFile property with the new value * assert.strictEqual(esmFS.readFile, newAPI); * // readFileSync has been deleted from the required fs * assert.strictEqual('readFileSync' in fs, false); * // syncBuiltinESMExports() does not remove readFileSync from esmFS * assert.strictEqual('readFileSync' in esmFS, true); * // syncBuiltinESMExports() does not add names * assert.strictEqual(esmFS.newAPI, undefined); * }); * ``` * @since v12.12.0 */ function syncBuiltinESMExports(): void; /** * `path` is the resolved path for the file for which a corresponding source map * should be fetched. * @since v13.7.0, v12.17.0 * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. */ function findSourceMap(path: string, error?: Error): SourceMap; interface SourceMapPayload { file: string; version: number; sources: string[]; sourcesContent: string[]; names: string[]; mappings: string; sourceRoot: string; } interface SourceMapping { generatedLine: number; generatedColumn: number; originalSource: string; originalLine: number; originalColumn: number; } interface SourceOrigin { /** * The name of the range in the source map, if one was provided */ name?: string; /** * The file name of the original source, as reported in the SourceMap */ fileName: string; /** * The 1-indexed lineNumber of the corresponding call site in the original source */ lineNumber: number; /** * The 1-indexed columnNumber of the corresponding call site in the original source */ columnNumber: number; } /** * @since v13.7.0, v12.17.0 */ class SourceMap { /** * Getter for the payload used to construct the `SourceMap` instance. */ readonly payload: SourceMapPayload; constructor(payload: SourceMapPayload); /** * Given a line offset and column offset in the generated source * file, returns an object representing the SourceMap range in the * original file if found, or an empty object if not. * * The object returned contains the following keys: * * The returned value represents the raw range as it appears in the * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and * column numbers as they appear in Error messages and CallSite * objects. * * To get the correspondin
g 1-indexed line and column numbers from a * lineNumber and columnNumber as they are reported by Error stacks * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` * @param lineOffset The zero-indexed line number offset in the generated source * @param columnOffset The zero-indexed column number offset in the generated source */ findEntry(lineOffset: number, columnOffset: number): SourceMapping; /** * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, * find the corresponding call site location in the original source. * * If the `lineNumber` and `columnNumber` provided are not found in any source map, * then an empty object is returned. * @param lineNumber The 1-indexed line number of the call site in the generated source * @param columnNumber The 1-indexed column number of the call site in the generated source */ findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; } /** @deprecated Use `ImportAttributes` instead */ interface ImportAssertions extends ImportAttributes {} interface ImportAttributes extends NodeJS.Dict<string> { type?: string | undefined; } type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; interface GlobalPreloadContext { port: MessagePort; } /** * @deprecated This hook will be removed in a future version. * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. * * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. * This hook allows the return of a string that is run as a sloppy-mode script on startup. * * @param context Information to assist the preload code * @return Code to run before application startup */ type GlobalPreloadHook = (context: GlobalPreloadContext) => string; /** * The `initialize` hook provides a way to define a custom function that runs in the hooks thread * when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`. * * This hook can receive data from a `register` invocation, including ports and other transferrable objects. * The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes. */ type InitializeHook<Data = any> = (data: Data) => void | Promise<void>; interface ResolveHookContext { /** * Export conditions of the relevant `package.json` */ conditions: string[]; /** * @deprecated Use `importAttributes` instead */ importAssertions: ImportAttributes; /** * An object whose key-value pairs represent the assertions for the module to import */ importAttributes: ImportAttributes; /** * The module importing this one, or undefined if this is the Node.js entry point */ parentURL: string | undefined; } interface ResolveFnOutput { /** * A hint to the load hook (it might be ignored) */ format?: ModuleFormat | null | undefined; /** * @deprecated Use `importAttributes` instead */ importAssertions?: ImportAttributes | undefined; /** * The import attributes to use when caching the module (optional;
if excluded the input will be used) */ importAttributes?: ImportAttributes | undefined; /** * A signal that this hook intends to terminate the chain of `resolve` hooks. * @default false */ shortCircuit?: boolean | undefined; /** * The absolute URL to which this input resolves */ url: string; } /** * The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook. * If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`); * if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook. * * @param specifier The specified URL path of the module to be resolved * @param context * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook */ type ResolveHook = ( specifier: string, context: ResolveHookContext, nextResolve: ( specifier: string, context?: ResolveHookContext, ) => ResolveFnOutput | Promise<ResolveFnOutput>, ) => ResolveFnOutput | Promise<ResolveFnOutput>; interface LoadHookContext { /** * Export conditions of the relevant `package.json` */ conditions: string[]; /** * The format optionally supplied by the `resolve` hook chain */ format: ModuleFormat; /** * @deprecated Use `importAttributes` instead */ importAssertions: ImportAttributes; /** * An object whose key-value pairs represent the assertions for the module to import */ importAttributes: ImportAttributes; } interface LoadFnOutput { format: ModuleFormat; /** * A signal that this hook intends to terminate the chain of `resolve` hooks. * @default false */ shortCircuit?: boolean | undefined; /** * The source for Node.js to evaluate */ source?: ModuleSource; } /** * The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. * It is also in charge of validating the import assertion. * * @param url The URL/path of the module to be loaded * @param context Metadata about the module * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook */ type LoadHook = ( url: string, context: LoadHookContext, nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise<LoadFnOutput>, ) => LoadFnOutput | Promise<LoadFnOutput>; } interface RegisterOptions<Data> { parentURL: string | URL; data?: Data | undefined; transferList?: any[] | undefined; } interface Module extends NodeModule {} class Module { static runMain(): void; static wrap(code: string): string; static createRequire(path: string | URL): NodeRequire; static builtinModules: string[]; static isBuiltin(moduleName: string): boolean; static Module: typeof Module; static register<Data = any>( specifier: string | URL, parentURL?: string | URL, options?: RegisterOptions<Data>,
): void; static register<Data = any>(specifier: string | URL, options?: RegisterOptions<Data>): void; constructor(id: string, parent?: Module); } global { interface ImportMeta { /** * The directory name of the current module. This is the same as the `path.dirname()` of the `import.meta.filename`. * **Caveat:** only present on `file:` modules. */ dirname: string; /** * The full absolute path and filename of the current module, with symlinks resolved. * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. * **Caveat:** only local modules support this property. Modules not using the `file:` protocol will not provide it. */ filename: string; /** * The absolute `file:` URL of the module. */ url: string; /** * Provides a module-relative resolution function scoped to each module, returning * the URL string. * * Second `parent` parameter is only used when the `--experimental-import-meta-resolve` * command flag enabled. * * @since v20.6.0 * * @param specifier The module specifier to resolve relative to `parent`. * @param parent The absolute parent module URL to resolve from. * @returns The absolute (`file:`) URL string for the resolved module. */ resolve(specifier: string, parent?: string | URL | undefined): string; } } export = Module; } declare module "node:module" { import module = require("module"); export = module; }
declare module "process" { import * as tty from "node:tty"; import { Worker } from "node:worker_threads"; global { var process: NodeJS.Process; namespace NodeJS { // this namespace merge is here because these are specifically used // as the type for process.stdin, process.stdout, and process.stderr. // they can't live in tty.d.ts because we need to disambiguate the imported name. interface ReadStream extends tty.ReadStream {} interface WriteStream extends tty.WriteStream {} interface MemoryUsageFn { /** * The `process.memoryUsage()` method iterate over each page to gather informations about memory * usage which can be slow depending on the program memory allocations. */ (): MemoryUsage; /** * method returns an integer representing the Resident Set Size (RSS) in bytes. */ rss(): number; } interface MemoryUsage { rss: number; heapTotal: number; heapUsed: number; external: number; arrayBuffers: number; } interface CpuUsage { user: number; system: number; } interface ProcessRelease { name: string; sourceUrl?: string | undefined; headersUrl?: string | undefined; libUrl?: string | undefined; lts?: string | undefined; } interface ProcessVersions extends Dict<string> { http_parser: string; node: string; v8: string; ares: string; uv: string; zlib: string; modules: string; openssl: string; } type Platform = | "aix" | "android" | "darwin" | "freebsd" | "haiku" | "linux" | "openbsd" | "sunos" | "win32" | "cygwin" | "netbsd"; type Architecture = | "arm" | "arm64" | "ia32" | "mips" | "mipsel" | "ppc" | "ppc64" | "riscv64" | "s390" | "s390x" | "x64"; type Signals = | "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; type MultipleResolveType = "resolve" | "reject"; type BeforeExitListener = (code: number) => void; type DisconnectListener = () => void; type ExitListener = (code: number) => void;
type RejectionHandledListener = (promise: Promise<unknown>) => void; type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; /** * Most of the time the unhandledRejection will be an Error, but this should not be relied upon * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. */ type UnhandledRejectionListener = (reason: unknown, promise: Promise<unknown>) => void; type WarningListener = (warning: Error) => void; type MessageListener = (message: unknown, sendHandle: unknown) => void; type SignalsListener = (signal: Signals) => void; type MultipleResolveListener = ( type: MultipleResolveType, promise: Promise<unknown>, value: unknown, ) => void; type WorkerListener = (worker: Worker) => void; interface Socket extends ReadWriteStream { isTTY?: true | undefined; } // Alias for compatibility interface ProcessEnv extends Dict<string> { /** * Can be used to change the default timezone at runtime */ TZ?: string; } interface HRTime { (time?: [number, number]): [number, number]; bigint(): bigint; } interface ProcessReport { /** * Directory where the report is written. * working directory of the Node.js process. * @default '' indicating that reports are written to the current */ directory: string; /** * Filename where the report is written. * The default value is the empty string. * @default '' the output filename will be comprised of a timestamp, * PID, and sequence number. */ filename: string; /** * Returns a JSON-formatted diagnostic report for the running process. * The report's JavaScript stack trace is taken from err, if present. */ getReport(err?: Error): string; /** * If true, a diagnostic report is generated on fatal errors, * such as out of memory errors or failed C++ assertions. * @default false */ reportOnFatalError: boolean; /** * If true, a diagnostic report is generated when the process * receives the signal specified by process.report.signal. * @default false */ reportOnSignal: boolean; /** * If true, a diagnostic report is generated on uncaught exception. * @default false */ reportOnUncaughtException: boolean; /** * The signal used to trigger the creation of a diagnostic report. * @default 'SIGUSR2' */ signal: Signals; /** * Writes a diagnostic report to a file. If filename is not provided, the default filename * includes the date, time, PID, and a sequence number. * The report's JavaScript stack trace is taken from err, if present. * * @param fileName Name of the file where the report is written. * This should be a relative path, that will be appended to the directory specified in * `process.report.directory`, or the current working directory of the Node.js process, * if unspecified. * @param error A custom error used
for reporting the JavaScript stack. * @return Filename of the generated report. */ writeReport(fileName?: string): string; writeReport(error?: Error): string; writeReport(fileName?: string, err?: Error): string; } interface ResourceUsage { fsRead: number; fsWrite: number; involuntaryContextSwitches: number; ipcReceived: number; ipcSent: number; majorPageFault: number; maxRSS: number; minorPageFault: number; sharedMemorySize: number; signalsCount: number; swappedOut: number; systemCPUTime: number; unsharedDataSize: number; unsharedStackSize: number; userCPUTime: number; voluntaryContextSwitches: number; } interface EmitWarningOptions { /** * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. * * @default 'Warning' */ type?: string | undefined; /** * A unique identifier for the warning instance being emitted. */ code?: string | undefined; /** * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. * * @default process.emitWarning */ ctor?: Function | undefined; /** * Additional text to include with the error. */ detail?: string | undefined; } interface ProcessConfig { readonly target_defaults: { readonly cflags: any[]; readonly default_configuration: string; readonly defines: string[]; readonly include_dirs: string[]; readonly libraries: string[]; }; readonly variables: { readonly clang: number; readonly host_arch: string; readonly node_install_npm: boolean; readonly node_install_waf: boolean; readonly node_prefix: string; readonly node_shared_openssl: boolean; readonly node_shared_v8: boolean; readonly node_shared_zlib: boolean; readonly node_use_dtrace: boolean; readonly node_use_etw: boolean; readonly node_use_openssl: boolean; readonly target_arch: string; readonly v8_no_strict_aliasing: number; readonly v8_use_snapshot: boolean; readonly visibility: string; }; } interface Process extends EventEmitter { /** * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is * a `Writable` stream. * * For example, to copy `process.stdin` to `process.stdout`: * * ```js * import { stdin, stdout } from 'node:process'; * * stdin.pipe(stdout); * ``` * * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. */ stdout: WriteStream & { fd: 1; }; /**
* The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is * a `Writable` stream. * * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. */ stderr: WriteStream & { fd: 2; }; /** * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is * a `Readable` stream. * * For details of how to read from `stdin` see `readable.read()`. * * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that * is compatible with scripts written for Node.js prior to v0.10\. * For more information see `Stream compatibility`. * * In "old" streams mode the `stdin` stream is paused by default, so one * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. */ stdin: ReadStream & { fd: 0; }; openStdin(): Socket; /** * The `process.argv` property returns an array containing the command-line * arguments passed when the Node.js process was launched. The first element will * be {@link execPath}. See `process.argv0` if access to the original value * of `argv[0]` is needed. The second element will be the path to the JavaScript * file being executed. The remaining elements will be any additional command-line * arguments. * * For example, assuming the following script for `process-args.js`: * * ```js * import { argv } from 'node:process'; * * // print process.argv * argv.forEach((val, index) => { * console.log(`${index}: ${val}`); * }); * ``` * * Launching the Node.js process as: * * ```bash * node process-args.js one two=three four * ``` * * Would generate the output: * * ```text * 0: /usr/local/bin/node * 1: /Users/mjr/work/node/process-args.js * 2: one * 3: two=three * 4: four * ``` * @since v0.1.27 */ argv: string[]; /** * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. * * ```console * $ bash -c 'exec -a customArgv0 ./node' * > process.argv[0] * '/Volumes/code/external/node/out/Release/node' * > process.argv0 * 'customArgv0' * ``` * @since v6.4.0 */ argv0: string; /** * The `process.execArgv` property returns the set of Node.js-specific command-line * options passed when the Node.js process was launched. These options do not * appear in the array returned by the {@link argv} property, and do not * include the Node.js executable, the name of the script, or any options
following * the script name. These options are useful in order to spawn child processes with * the same execution environment as the parent. * * ```bash * node --harmony script.js --version * ``` * * Results in `process.execArgv`: * * ```js * ['--harmony'] * ``` * * And `process.argv`: * * ```js * ['/usr/local/bin/node', 'script.js', '--version'] * ``` * * Refer to `Worker constructor` for the detailed behavior of worker * threads with this property. * @since v0.7.7 */ execArgv: string[]; /** * The `process.execPath` property returns the absolute pathname of the executable * that started the Node.js process. Symbolic links, if any, are resolved. * * ```js * '/usr/local/bin/node' * ``` * @since v0.1.100 */ execPath: string; /** * The `process.abort()` method causes the Node.js process to exit immediately and * generate a core file. * * This feature is not available in `Worker` threads. * @since v0.7.0 */ abort(): never; /** * The `process.chdir()` method changes the current working directory of the * Node.js process or throws an exception if doing so fails (for instance, if * the specified `directory` does not exist). * * ```js * import { chdir, cwd } from 'node:process'; * * console.log(`Starting directory: ${cwd()}`); * try { * chdir('/tmp'); * console.log(`New directory: ${cwd()}`); * } catch (err) { * console.error(`chdir: ${err}`); * } * ``` * * This feature is not available in `Worker` threads. * @since v0.1.17 */ chdir(directory: string): void; /** * The `process.cwd()` method returns the current working directory of the Node.js * process. * * ```js * import { cwd } from 'node:process'; * * console.log(`Current directory: ${cwd()}`); * ``` * @since v0.1.8 */ cwd(): string; /** * The port used by the Node.js debugger when enabled. * * ```js * import process from 'node:process'; * * process.debugPort = 5858; * ``` * @since v0.7.2 */ debugPort: number; /** * The `process.emitWarning()` method can be used to emit custom or application * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. * * ```js * import { emitWarning } from 'node:process'; * * // Emit a warning with a code and additional detail. * emitWarning('Something happened!', { * code: 'MY_WARNING', * detail: 'This is some additional information', * }); * // Emits:
* // (node:56338) [MY_WARNING] Warning: Something happened! * // This is some additional information * ``` * * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. * * ```js * import process from 'node:process'; * * process.on('warning', (warning) => { * console.warn(warning.name); // 'Warning' * console.warn(warning.message); // 'Something happened!' * console.warn(warning.code); // 'MY_WARNING' * console.warn(warning.stack); // Stack trace * console.warn(warning.detail); // 'This is some additional information' * }); * ``` * * If `warning` is passed as an `Error` object, the `options` argument is ignored. * @since v8.0.0 * @param warning The warning to emit. */ emitWarning(warning: string | Error, ctor?: Function): void; emitWarning(warning: string | Error, type?: string, ctor?: Function): void; emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; emitWarning(warning: string | Error, options?: EmitWarningOptions): void; /** * The `process.env` property returns an object containing the user environment. * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). * * An example of this object looks like: * * ```js * { * TERM: 'xterm-256color', * SHELL: '/usr/local/bin/bash', * USER: 'maciej', * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', * PWD: '/Users/maciej', * EDITOR: 'vim', * SHLVL: '1', * HOME: '/Users/maciej', * LOGNAME: 'maciej', * _: '/usr/local/bin/node' * } * ``` * * It is possible to modify this object, but such modifications will not be * reflected outside the Node.js process, or (unless explicitly requested) * to other `Worker` threads. * In other words, the following example would not work: * * ```bash * node -e 'process.env.foo = "bar"' &#x26;&#x26; echo $foo * ``` * * While the following will: * * ```js * import { env } from 'node:process'; * * env.foo = 'bar'; * console.log(env.foo); * ``` * * Assigning a property on `process.env` will implicitly convert the value * to a string. **This behavior is deprecated.** Future versions of Node.js may * throw an error when the value is not a string, number, or boolean. * * ```js * import { env } from 'node:process'; * * env.test = null; * console.log(env.test); * // => 'null' * env.test = undefined; * console.log(env.test); * // => 'undefined' * ``` * * Use `delete` to delete a property from `process.env`. * * ```js * import { env } from 'node:process'; * * env
.TEST = 1; * delete env.TEST; * console.log(env.TEST); * // => undefined * ``` * * On Windows operating systems, environment variables are case-insensitive. * * ```js * import { env } from 'node:process'; * * env.TEST = 1; * console.log(env.test); * // => 1 * ``` * * Unless explicitly specified when creating a `Worker` instance, * each `Worker` thread has its own copy of `process.env`, based on its * parent thread's `process.env`, or whatever was specified as the `env` option * to the `Worker` constructor. Changes to `process.env` will not be visible * across `Worker` threads, and only the main thread can make changes that * are visible to the operating system or to native add-ons. On Windows, a copy of`process.env` on a `Worker` instance operates in a case-sensitive manner * unlike the main thread. * @since v0.1.27 */ env: ProcessEnv; /** * The `process.exit()` method instructs Node.js to terminate the process * synchronously with an exit status of `code`. If `code` is omitted, exit uses * either the 'success' code `0` or the value of `process.exitCode` if it has been * set. Node.js will not terminate until all the `'exit'` event listeners are * called. * * To exit with a 'failure' code: * * ```js * import { exit } from 'node:process'; * * exit(1); * ``` * * The shell that executed Node.js should see the exit code as `1`. * * Calling `process.exit()` will force the process to exit as quickly as possible * even if there are still asynchronous operations pending that have not yet * completed fully, including I/O operations to `process.stdout` and`process.stderr`. * * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ * _work pending_ in the event loop. The `process.exitCode` property can be set to * tell the process which exit code to use when the process exits gracefully. * * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being * truncated and lost: * * ```js * import { exit } from 'node:process'; * * // This is an example of what *not* to do: * if (someConditionNotMet()) { * printUsageToStdout(); * exit(1); * } * ``` * * The reason this is problematic is because writes to `process.stdout` in Node.js * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. * * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding * scheduling any additional work for the event loop: * * ```js * import process fro
m 'node:process'; * * // How to properly set the exit code while letting * // the process exit gracefully. * if (someConditionNotMet()) { * printUsageToStdout(); * process.exitCode = 1; * } * ``` * * If it is necessary to terminate the Node.js process due to an error condition, * throwing an _uncaught_ error and allowing the process to terminate accordingly * is safer than calling `process.exit()`. * * In `Worker` threads, this function stops the current thread rather * than the current process. * @since v0.1.13 * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. */ exit(code?: number): never; /** * A number which will be the process exit code, when the process either * exits gracefully, or is exited via {@link exit} without specifying * a code. * * Specifying a code to {@link exit} will override any * previous setting of `process.exitCode`. * @since v0.11.8 */ exitCode?: number | undefined; /** * The `process.getgid()` method returns the numerical group identity of the * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) * * ```js * import process from 'process'; * * if (process.getgid) { * console.log(`Current gid: ${process.getgid()}`); * } * ``` * * This function is only available on POSIX platforms (i.e. not Windows or * Android). * @since v0.1.31 */ getgid?: () => number; /** * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a * numeric ID or a group name * string. If a group name is specified, this method blocks while resolving the * associated numeric ID. * * ```js * import process from 'process'; * * if (process.getgid &#x26;&#x26; process.setgid) { * console.log(`Current gid: ${process.getgid()}`); * try { * process.setgid(501); * console.log(`New gid: ${process.getgid()}`); * } catch (err) { * console.log(`Failed to set gid: ${err}`); * } * } * ``` * * This function is only available on POSIX platforms (i.e. not Windows or * Android). * This feature is not available in `Worker` threads. * @since v0.1.31 * @param id The group name or ID */ setgid?: (id: number | string) => void; /** * The `process.getuid()` method returns the numeric user identity of the process. * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) * * ```js * import process from 'process'; * * if (process.getuid) { * console.log(`Current uid: ${process.getuid()}`); * } * ``` *
* This function is only available on POSIX platforms (i.e. not Windows or * Android). * @since v0.1.28 */ getuid?: () => number; /** * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a * numeric ID or a username string. * If a username is specified, the method blocks while resolving the associated * numeric ID. * * ```js * import process from 'process'; * * if (process.getuid &#x26;&#x26; process.setuid) { * console.log(`Current uid: ${process.getuid()}`); * try { * process.setuid(501); * console.log(`New uid: ${process.getuid()}`); * } catch (err) { * console.log(`Failed to set uid: ${err}`); * } * } * ``` * * This function is only available on POSIX platforms (i.e. not Windows or * Android). * This feature is not available in `Worker` threads. * @since v0.1.28 */ setuid?: (id: number | string) => void; /** * The `process.geteuid()` method returns the numerical effective user identity of * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) * * ```js * import process from 'process'; * * if (process.geteuid) { * console.log(`Current uid: ${process.geteuid()}`); * } * ``` * * This function is only available on POSIX platforms (i.e. not Windows or * Android). * @since v2.0.0 */ geteuid?: () => number; /** * The `process.seteuid()` method sets the effective user identity of the process. * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username * string. If a username is specified, the method blocks while resolving the * associated numeric ID. * * ```js * import process from 'process'; * * if (process.geteuid &#x26;&#x26; process.seteuid) { * console.log(`Current uid: ${process.geteuid()}`); * try { * process.seteuid(501); * console.log(`New uid: ${process.geteuid()}`); * } catch (err) { * console.log(`Failed to set uid: ${err}`); * } * } * ``` * * This function is only available on POSIX platforms (i.e. not Windows or * Android). * This feature is not available in `Worker` threads. * @since v2.0.0 * @param id A user name or ID */ seteuid?: (id: number | string) => void; /** * The `process.getegid()` method returns the numerical effective group identity * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) * * ```js * import process from 'process'; * * if (process.getegid) { * console.log(`Current gid: ${process.getegid()}`);
* } * ``` * * This function is only available on POSIX platforms (i.e. not Windows or * Android). * @since v2.0.0 */ getegid?: () => number; /** * The `process.setegid()` method sets the effective group identity of the process. * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group * name string. If a group name is specified, this method blocks while resolving * the associated a numeric ID. * * ```js * import process from 'process'; * * if (process.getegid &#x26;&#x26; process.setegid) { * console.log(`Current gid: ${process.getegid()}`); * try { * process.setegid(501); * console.log(`New gid: ${process.getegid()}`); * } catch (err) { * console.log(`Failed to set gid: ${err}`); * } * } * ``` * * This function is only available on POSIX platforms (i.e. not Windows or * Android). * This feature is not available in `Worker` threads. * @since v2.0.0 * @param id A group name or ID */ setegid?: (id: number | string) => void; /** * The `process.getgroups()` method returns an array with the supplementary group * IDs. POSIX leaves it unspecified if the effective group ID is included but * Node.js ensures it always is. * * ```js * import process from 'process'; * * if (process.getgroups) { * console.log(process.getgroups()); // [ 16, 21, 297 ] * } * ``` * * This function is only available on POSIX platforms (i.e. not Windows or * Android). * @since v0.9.4 */ getgroups?: () => number[]; /** * The `process.setgroups()` method sets the supplementary group IDs for the * Node.js process. This is a privileged operation that requires the Node.js * process to have `root` or the `CAP_SETGID` capability. * * The `groups` array can contain numeric group IDs, group names, or both. * * ```js * import process from 'process'; * * if (process.getgroups &#x26;&#x26; process.setgroups) { * try { * process.setgroups([501]); * console.log(process.getgroups()); // new groups * } catch (err) { * console.log(`Failed to set groups: ${err}`); * } * } * ``` * * This function is only available on POSIX platforms (i.e. not Windows or * Android). * This feature is not available in `Worker` threads. * @since v0.9.4 */ setgroups?: (groups: ReadonlyArray<string | number>) => void; /** * The `process.setUncaughtExceptionCaptureCallback()` function sets a function * that will be invoked when an uncaught exception occurs, which will receive the * exception value itself as its first argument. * * If such a function is set, the `'uncaughtExceptio
n'` event will * not be emitted. If `--abort-on-uncaught-exception` was passed from the * command line or set through `v8.setFlagsFromString()`, the process will * not abort. Actions configured to take place on exceptions such as report * generations will be affected too * * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this * method with a non-`null` argument while another capture function is set will * throw an error. * * Using this function is mutually exclusive with using the deprecated `domain` built-in module. * @since v9.3.0 */ setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; /** * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. * @since v9.3.0 */ hasUncaughtExceptionCaptureCallback(): boolean; /** * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. * @since v20.7.0 * @experimental */ readonly sourceMapsEnabled: boolean; /** * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for * stack traces. * * It provides same features as launching Node.js process with commandline options`--enable-source-maps`. * * Only source maps in JavaScript files that are loaded after source maps has been * enabled will be parsed and loaded. * @since v16.6.0, v14.18.0 * @experimental */ setSourceMapsEnabled(value: boolean): void; /** * The `process.version` property contains the Node.js version string. * * ```js * import { version } from 'node:process'; * * console.log(`Version: ${version}`); * // Version: v14.8.0 * ``` * * To get the version string without the prepended _v_, use`process.versions.node`. * @since v0.1.3 */ readonly version: string; /** * The `process.versions` property returns an object listing the version strings of * Node.js and its dependencies. `process.versions.modules` indicates the current * ABI version, which is increased whenever a C++ API changes. Node.js will refuse * to load modules that were compiled against a different module ABI version. * * ```js * import { versions } from 'node:process'; * * console.log(versions); * ``` * * Will generate an object similar to: * * ```console * { node: '20.2.0', * acorn: '8.8.2', * ada: '2.4.0', * ares: '1.19.0', * base64: '0.5.0', * brotli: '1.0.9', * cjs_module_lexer: '1.2.2', * cldr: '43.0', * icu: '73.1', * llhttp: '8.1.0', * modules: '115', * napi: '8', * nghttp2: '1.52.0', * nghttp3: '0.7.0', * ngtcp2: '0.8.1', * openssl: '3.0.8+qu
ic', * simdutf: '3.2.9', * tz: '2023c', * undici: '5.22.0', * unicode: '15.0', * uv: '1.44.2', * uvwasi: '0.0.16', * v8: '11.3.244.8-node.9', * zlib: '1.2.13' } * ``` * @since v0.2.0 */ readonly versions: ProcessVersions; /** * The `process.config` property returns a frozen `Object` containing the * JavaScript representation of the configure options used to compile the current * Node.js executable. This is the same as the `config.gypi` file that was produced * when running the `./configure` script. * * An example of the possible output looks like: * * ```js * { * target_defaults: * { cflags: [], * default_configuration: 'Release', * defines: [], * include_dirs: [], * libraries: [] }, * variables: * { * host_arch: 'x64', * napi_build_version: 5, * node_install_npm: 'true', * node_prefix: '', * node_shared_cares: 'false', * node_shared_http_parser: 'false', * node_shared_libuv: 'false', * node_shared_zlib: 'false', * node_use_openssl: 'true', * node_shared_openssl: 'false', * strict_aliasing: 'true', * target_arch: 'x64', * v8_use_snapshot: 1 * } * } * ``` * @since v0.7.7 */ readonly config: ProcessConfig; /** * The `process.kill()` method sends the `signal` to the process identified by`pid`. * * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. * * This method will throw an error if the target `pid` does not exist. As a special * case, a signal of `0` can be used to test for the existence of a process. * Windows platforms will throw an error if the `pid` is used to kill a process * group. * * Even though the name of this function is `process.kill()`, it is really just a * signal sender, like the `kill` system call. The signal sent may do something * other than kill the target process. * * ```js * import process, { kill } from 'node:process'; * * process.on('SIGHUP', () => { * console.log('Got SIGHUP signal.'); * }); * * setTimeout(() => { * console.log('Exiting.'); * process.exit(0); * }, 100); * * kill(process.pid, 'SIGHUP'); * ``` * * When `SIGUSR1` is received by a Node.js process, Node.js will start the * debugger. See `Signal Events`. * @since v0.0.6 * @param pid A process ID * @param [signal='SIGTERM'] The signal to send, either as a string or number. */ kill(pid: number, signal?: string | number): true; /** * The `process.pid` property returns
the PID of the process. * * ```js * import { pid } from 'node:process'; * * console.log(`This process is pid ${pid}`); * ``` * @since v0.1.15 */ readonly pid: number; /** * The `process.ppid` property returns the PID of the parent of the * current process. * * ```js * import { ppid } from 'node:process'; * * console.log(`The parent process is pid ${ppid}`); * ``` * @since v9.2.0, v8.10.0, v6.13.0 */ readonly ppid: number; /** * The `process.title` property returns the current process title (i.e. returns * the current value of `ps`). Assigning a new value to `process.title` modifies * the current value of `ps`. * * When a new value is assigned, different platforms will impose different maximum * length restrictions on the title. Usually such restrictions are quite limited. * For instance, on Linux and macOS, `process.title` is limited to the size of the * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) * cases. * * Assigning a value to `process.title` might not result in an accurate label * within process manager applications such as macOS Activity Monitor or Windows * Services Manager. * @since v0.1.104 */ title: string; /** * The operating system CPU architecture for which the Node.js binary was compiled. * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. * * ```js * import { arch } from 'node:process'; * * console.log(`This processor architecture is ${arch}`); * ``` * @since v0.5.0 */ readonly arch: Architecture; /** * The `process.platform` property returns a string identifying the operating * system platform for which the Node.js binary was compiled. * * Currently possible values are: * * * `'aix'` * * `'darwin'` * * `'freebsd'` * * `'linux'` * * `'openbsd'` * * `'sunos'` * * `'win32'` * * ```js * import { platform } from 'node:process'; * * console.log(`This platform is ${platform}`); * ``` * * The value `'android'` may also be returned if the Node.js is built on the * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). * @since v0.1.16 */ readonly platform: Platform; /** * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at * runtime, `require.
main` may still refer to the original main module in * modules that were required before the change occurred. Generally, it's * safe to assume that the two refer to the same module. * * As with `require.main`, `process.mainModule` will be `undefined` if there * is no entry script. * @since v0.1.17 * @deprecated Since v14.0.0 - Use `main` instead. */ mainModule?: Module | undefined; memoryUsage: MemoryUsageFn; /** * Gets the amount of memory available to the process (in bytes) based on * limits imposed by the OS. If there is no such constraint, or the constraint * is unknown, `undefined` is returned. * * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more * information. * @since v19.6.0, v18.15.0 * @experimental */ constrainedMemory(): number | undefined; /** * The `process.cpuUsage()` method returns the user and system CPU time usage of * the current process, in an object with properties `user` and `system`, whose * values are microsecond values (millionth of a second). These values measure time * spent in user and system code respectively, and may end up being greater than * actual elapsed time if multiple CPU cores are performing work for this process. * * The result of a previous call to `process.cpuUsage()` can be passed as the * argument to the function, to get a diff reading. * * ```js * import { cpuUsage } from 'node:process'; * * const startUsage = cpuUsage(); * // { user: 38579, system: 6986 } * * // spin the CPU for 500 milliseconds * const now = Date.now(); * while (Date.now() - now < 500); * * console.log(cpuUsage(startUsage)); * // { user: 514883, system: 11226 } * ``` * @since v6.1.0 * @param previousValue A previous return value from calling `process.cpuUsage()` */ cpuUsage(previousValue?: CpuUsage): CpuUsage; /** * `process.nextTick()` adds `callback` to the "next tick queue". This queue is * fully drained after the current operation on the JavaScript stack runs to * completion and before the event loop is allowed to continue. It's possible to * create an infinite loop if one were to recursively call `process.nextTick()`. * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. * * ```js * import { nextTick } from 'node:process'; * * console.log('start'); * nextTick(() => { * console.log('nextTick callback'); * }); * console.log('scheduled'); * // Output: * // start * // scheduled * // nextTick callback * ``` * * This is important when developing APIs in order to give users the opportunity * to assign event handlers _after_ an object has been constructed but before any * I/O has occurred: * * ```js * import { nextTick } from 'node
:process'; * * function MyThing(options) { * this.setupOptions(options); * * nextTick(() => { * this.startDoingStuff(); * }); * } * * const thing = new MyThing(); * thing.getReadyForStuff(); * * // thing.startDoingStuff() gets called now, not before. * ``` * * It is very important for APIs to be either 100% synchronous or 100% * asynchronous. Consider this example: * * ```js * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! * function maybeSync(arg, cb) { * if (arg) { * cb(); * return; * } * * fs.stat('file', cb); * } * ``` * * This API is hazardous because in the following case: * * ```js * const maybeTrue = Math.random() > 0.5; * * maybeSync(maybeTrue, () => { * foo(); * }); * * bar(); * ``` * * It is not clear whether `foo()` or `bar()` will be called first. * * The following approach is much better: * * ```js * import { nextTick } from 'node:process'; * * function definitelyAsync(arg, cb) { * if (arg) { * nextTick(cb); * return; * } * * fs.stat('file', cb); * } * ``` * @since v0.1.26 * @param args Additional arguments to pass when invoking the `callback` */ nextTick(callback: Function, ...args: any[]): void; /** * The `process.release` property returns an `Object` containing metadata related * to the current release, including URLs for the source tarball and headers-only * tarball. * * `process.release` contains the following properties: * * ```js * { * name: 'node', * lts: 'Hydrogen', * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' * } * ``` * * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be * relied upon to exist. * @since v3.0.0 */ readonly release: ProcessRelease; features: { inspector: boolean; debug: boolean; uv: boolean; ipv6: boolean; tls_alpn: boolean; tls_sni: boolean; tls_ocsp: boolean; tls: boolean; }; /** * `process.umask()` returns the Node.js process's file mode creation mask. Child * processes inherit the mask from the parent process. * @since v0.1.19 * @deprecated Calling `process.umask()` with no argum
ent causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * * security vulnerability. There is no safe, cross-platform alternative API. */ umask(): number; /** * Can only be set if not in worker thread. */ umask(mask: string | number): number; /** * The `process.uptime()` method returns the number of seconds the current Node.js * process has been running. * * The return value includes fractions of a second. Use `Math.floor()` to get whole * seconds. * @since v0.5.0 */ uptime(): number; hrtime: HRTime; /** * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. * If no IPC channel exists, this property is undefined. * @since v7.1.0 */ channel?: { /** * This method makes the IPC channel keep the event loop of the process running if .unref() has been called before. * @since v7.1.0 */ ref(): void; /** * This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. * @since v7.1.0 */ unref(): void; }; /** * If Node.js is spawned with an IPC channel, the `process.send()` method can be * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. * * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. * * The message goes through serialization and parsing. The resulting message might * not be the same as what is originally sent. * @since v0.5.9 * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: */ send?( message: any, sendHandle?: any, options?: { swallowErrors?: boolean | undefined; }, callback?: (error: Error | null) => void, ): boolean; /** * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the * IPC channel to the parent process, allowing the child process to exit gracefully * once there are no other connections keeping it alive. * * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. * * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. * @since v0.7.2 */ disconnect(): void; /** * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC * channel is connected and will return `false` after`process.disconnect()` is called. * * Once `process.connected` is `false`, it is no longer possible to send messages
* over the IPC channel using `process.send()`. * @since v0.7.2 */ connected: boolean; /** * The `process.allowedNodeEnvironmentFlags` property is a special, * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. * * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag * representations. `process.allowedNodeEnvironmentFlags.has()` will * return `true` in the following cases: * * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. * * Flags passed through to V8 (as listed in `--v8-options`) may replace * one or more _non-leading_ dashes for an underscore, or vice-versa; * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, * etc. * * Flags may contain one or more equals (`=`) characters; all * characters after and including the first equals will be ignored; * e.g., `--stack-trace-limit=100`. * * Flags _must_ be allowable within `NODE_OPTIONS`. * * When iterating over `process.allowedNodeEnvironmentFlags`, flags will * appear only _once_; each will begin with one or more dashes. Flags * passed through to V8 will contain underscores instead of non-leading * dashes: * * ```js * import { allowedNodeEnvironmentFlags } from 'node:process'; * * allowedNodeEnvironmentFlags.forEach((flag) => { * // -r * // --inspect-brk * // --abort_on_uncaught_exception * // ... * }); * ``` * * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail * silently. * * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will * contain what _would have_ been allowable. * @since v10.10.0 */ allowedNodeEnvironmentFlags: ReadonlySet<string>; /** * `process.report` is an object whose methods are used to generate diagnostic * reports for the current process. Additional documentation is available in the `report documentation`. * @since v11.8.0 */ report?: ProcessReport | undefined; /** * ```js * import { resourceUsage } from 'node:process'; * * console.log(resourceUsage()); * /* * Will output: * { * userCPUTime: 82872, * systemCPUTime: 4143, * maxRSS: 33164, * sharedMemorySize: 0, * unsharedDataSize: 0, * unsharedStackSize: 0, * minorPageFault: 2469, * majorPageFault: 0, * swappedOut: 0, * fsRead: 0, * fsWrite: 8, * ipcSent: 0, * ipcReceived: 0, * signalsCount: 0, * voluntaryContextSwitches: 79, * involuntaryContextSwitches: 1 * } * * ``` * @since v12.6.0
* @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. */ resourceUsage(): ResourceUsage; /** * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the * documentation for the `'warning' event` and the `emitWarning() method` for more information about this * flag's behavior. * @since v0.8.0 */ traceDeprecation: boolean; /* EventEmitter */ addListener(event: "beforeExit", listener: BeforeExitListener): this; addListener(event: "disconnect", listener: DisconnectListener): this; addListener(event: "exit", listener: ExitListener): this; addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; addListener(event: "warning", listener: WarningListener): this; addListener(event: "message", listener: MessageListener): this; addListener(event: Signals, listener: SignalsListener): this; addListener(event: "multipleResolves", listener: MultipleResolveListener): this; addListener(event: "worker", listener: WorkerListener): this; emit(event: "beforeExit", code: number): boolean; emit(event: "disconnect"): boolean; emit(event: "exit", code: number): boolean; emit(event: "rejectionHandled", promise: Promise<unknown>): boolean; emit(event: "uncaughtException", error: Error): boolean; emit(event: "uncaughtExceptionMonitor", error: Error): boolean; emit(event: "unhandledRejection", reason: unknown, promise: Promise<unknown>): boolean; emit(event: "warning", warning: Error): boolean; emit(event: "message", message: unknown, sendHandle: unknown): this; emit(event: Signals, signal?: Signals): boolean; emit( event: "multipleResolves", type: MultipleResolveType, promise: Promise<unknown>, value: unknown, ): this; emit(event: "worker", listener: WorkerListener): this; on(event: "beforeExit", listener: BeforeExitListener): this; on(event: "disconnect", listener: DisconnectListener): this; on(event: "exit", listener: ExitListener): this; on(event: "rejectionHandled", listener: RejectionHandledListener): this; on(event: "uncaughtException", listener: UncaughtExceptionListener): this; on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; on(event: "warning", listener: WarningListener): this; on(event: "message", listener: MessageListener): this; on(event: Signals, listener: SignalsListener): this; on(event: "multipleResolves", listener: MultipleResolveListener): this; on(event: "worker", listener: WorkerListener): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: "beforeExit", listener: BeforeExitListener): this; once(event: "disconnect", listener: DisconnectListener): this;
once(event: "exit", listener: ExitListener): this; once(event: "rejectionHandled", listener: RejectionHandledListener): this; once(event: "uncaughtException", listener: UncaughtExceptionListener): this; once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; once(event: "warning", listener: WarningListener): this; once(event: "message", listener: MessageListener): this; once(event: Signals, listener: SignalsListener): this; once(event: "multipleResolves", listener: MultipleResolveListener): this; once(event: "worker", listener: WorkerListener): this; once(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: "beforeExit", listener: BeforeExitListener): this; prependListener(event: "disconnect", listener: DisconnectListener): this; prependListener(event: "exit", listener: ExitListener): this; prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; prependListener(event: "warning", listener: WarningListener): this; prependListener(event: "message", listener: MessageListener): this; prependListener(event: Signals, listener: SignalsListener): this; prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; prependListener(event: "worker", listener: WorkerListener): this; prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; prependOnceListener(event: "disconnect", listener: DisconnectListener): this; prependOnceListener(event: "exit", listener: ExitListener): this; prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; prependOnceListener(event: "warning", listener: WarningListener): this; prependOnceListener(event: "message", listener: MessageListener): this; prependOnceListener(event: Signals, listener: SignalsListener): this; prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; prependOnceListener(event: "worker", listener: WorkerListener): this; listeners(event: "beforeExit"): BeforeExitListener[]; listeners(event: "disconnect"): DisconnectListener[]; listeners(event: "exit"): ExitListener[]; listeners(event: "rejectionHandled"): RejectionHandledListener[]; listeners(event: "uncaughtException"): UncaughtExceptionListener[]; listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; listeners(event: "warning"): WarningListener[]; listeners(event: "message"): MessageListener[]; listeners(event: Signals): SignalsListener[]; listeners(event: "multipleResolves"): MultipleResolveListener[];
listeners(event: "worker"): WorkerListener[]; } } } export = process; } declare module "node:process" { import process = require("process"); export = process; }
/** * **The `node:wasi` module does not currently provide the** * **comprehensive file system security properties provided by some WASI runtimes.** * **Full support for secure file system sandboxing may or may not be implemented in** * **future. In the mean time, do not rely on it to run untrusted code.** * * The WASI API provides an implementation of the [WebAssembly System Interface](https://wasi.dev/) specification. WASI gives WebAssembly applications access to the underlying * operating system via a collection of POSIX-like functions. * * ```js * import { readFile } from 'node:fs/promises'; * import { WASI } from 'wasi'; * import { argv, env } from 'node:process'; * * const wasi = new WASI({ * version: 'preview1', * args: argv, * env, * preopens: { * '/local': '/some/real/path/that/wasm/can/access', * }, * }); * * const wasm = await WebAssembly.compile( * await readFile(new URL('./demo.wasm', import.meta.url)), * ); * const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject()); * * wasi.start(instance); * ``` * * To run the above example, create a new WebAssembly text format file named`demo.wat`: * * ```text * (module * ;; Import the required fd_write WASI function which will write the given io vectors to stdout * ;; The function signature for fd_write is: * ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written * (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32))) * * (memory 1) * (export "memory" (memory 0)) * * ;; Write 'hello world\n' to memory at an offset of 8 bytes * ;; Note the trailing newline which is required for the text to appear * (data (i32.const 8) "hello world\n") * * (func $main (export "_start") * ;; Creating a new io vector within linear memory * (i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string * (i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\n' string * * (call $fd_write * (i32.const 1) ;; file_descriptor - 1 for stdout * (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0 * (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one. * (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written * ) * drop ;; Discard the number of bytes written from the top of the stack * ) * ) * ``` * * Use [wabt](https://github.com/WebAssembly/wabt) to compile `.wat` to `.wasm` * * ```bash * wat2wasm demo.wat * ``` * @experimental * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/wasi.js) */ declare module "wasi" { interface WASIOptions { /** * An array of strings that the WebAssembly application will * see as command line arguments. The first argument is the virtual path to the * WASI command itself. */ args?: string[] | undefined; /** * An object similar to `process.env` that the WebAssembly * application will see as its environment. */ env?: object | undefined; /** * This object represents the WebAssembly application's * sandbox directory structure. The string keys of `preopens` are treated as * directories within the sandbox. The corresponding values in `preopens` are * the real paths to those directories on the host machine. */ preopens?: NodeJS.Dict<string> | undefined; /** * By default, when WASI applications call `__wasi_proc_exit()` * `wasi.start()` will return with the exit code specified rather than terminatng the process. * Setting this option to `false` will cause the Node.js process to exit wi
th * the specified exit code instead. * @default true */ returnOnExit?: boolean | undefined; /** * The file descriptor used as standard input in the WebAssembly application. * @default 0 */ stdin?: number | undefined; /** * The file descriptor used as standard output in the WebAssembly application. * @default 1 */ stdout?: number | undefined; /** * The file descriptor used as standard error in the WebAssembly application. * @default 2 */ stderr?: number | undefined; /** * The version of WASI requested. * Currently the only supported versions are `'unstable'` and `'preview1'`. * @since v20.0.0 */ version: string; } /** * The `WASI` class provides the WASI system call API and additional convenience * methods for working with WASI-based applications. Each `WASI` instance * represents a distinct environment. * @since v13.3.0, v12.16.0 */ class WASI { constructor(options?: WASIOptions); /** * Return an import object that can be passed to `WebAssembly.instantiate()` if no other WASM imports are needed beyond those provided by WASI. * * If version `unstable` was passed into the constructor it will return: * * ```js * { wasi_unstable: wasi.wasiImport } * ``` * * If version `preview1` was passed into the constructor or no version was specified it will return: * * ```js * { wasi_snapshot_preview1: wasi.wasiImport } * ``` * @since v19.8.0 */ getImportObject(): object; /** * Attempt to begin execution of `instance` as a WASI command by invoking its`_start()` export. If `instance` does not contain a `_start()` export, or if`instance` contains an `_initialize()` * export, then an exception is thrown. * * `start()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named`memory`. If * `instance` does not have a `memory` export an exception is thrown. * * If `start()` is called more than once, an exception is thrown. * @since v13.3.0, v12.16.0 */ start(instance: object): number; // TODO: avoid DOM dependency until WASM moved to own lib. /** * Attempt to initialize `instance` as a WASI reactor by invoking its`_initialize()` export, if it is present. If `instance` contains a `_start()`export, then an exception is thrown. * * `initialize()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named`memory`. * If `instance` does not have a `memory` export an exception is thrown. * * If `initialize()` is called more than once, an exception is thrown. * @since v14.6.0, v12.19.0 */ initialize(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib. /** * `wasiImport` is an object that implements the WASI system call API. This object * should be passed as the `wasi_snapshot_preview1` import during the instantiation * of a [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance). * @since v13.3.0, v12.16.0 */ readonly wasiImport: NodeJS.Dict<any>; // TODO: Narrow to DOM types } } declare module "node:wasi" { export * from "wasi"; }
/** * License for programmatically and manually incorporated * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc * * Copyright Node.js contributors. All rights reserved. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ // NOTE: These definitions support NodeJS and TypeScript 4.9+. // Reference required types from the default lib: /// <reference lib="es2020" /> /// <reference lib="esnext.asynciterable" /> /// <reference lib="esnext.intl" /> /// <reference lib="esnext.bigint" /> // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: /// <reference path="assert.d.ts" /> /// <reference path="assert/strict.d.ts" /> /// <reference path="globals.d.ts" /> /// <reference path="async_hooks.d.ts" /> /// <reference path="buffer.d.ts" /> /// <reference path="child_process.d.ts" /> /// <reference path="cluster.d.ts" /> /// <reference path="console.d.ts" /> /// <reference path="constants.d.ts" /> /// <reference path="crypto.d.ts" /> /// <reference path="dgram.d.ts" /> /// <reference path="diagnostics_channel.d.ts" /> /// <reference path="dns.d.ts" /> /// <reference path="dns/promises.d.ts" /> /// <reference path="dns/promises.d.ts" /> /// <reference path="domain.d.ts" /> /// <reference path="dom-events.d.ts" /> /// <reference path="events.d.ts" /> /// <reference path="fs.d.ts" /> /// <reference path="fs/promises.d.ts" /> /// <reference path="http.d.ts" /> /// <reference path="http2.d.ts" /> /// <reference path="https.d.ts" /> /// <reference path="inspector.d.ts" /> /// <reference path="module.d.ts" /> /// <reference path="net.d.ts" /> /// <reference path="os.d.ts" /> /// <reference path="path.d.ts" /> /// <reference path="perf_hooks.d.ts" /> /// <reference path="process.d.ts" /> /// <reference path="punycode.d.ts" /> /// <reference path="querystring.d.ts" /> /// <reference path="readline.d.ts" /> /// <reference path="readline/promises.d.ts" /> /// <reference path="repl.d.ts" /> /// <reference path="stream.d.ts" /> /// <reference path="stream/promises.d.ts" /> /// <reference path="stream/consumers.d.ts" /> /// <reference path="stream/web.d.ts" /> /// <reference path="string_decoder.d.ts" /> /// <reference path="test.d.ts" /> /// <reference path="timers.d.ts" /> /// <reference path="timers/promises.d.ts" /> /// <reference path="tls.d.ts" /> /// <reference path="trace_events.d.ts" /> /// <reference path="tty.d.ts" /> /// <reference path="url.d.ts" /> /// <reference path="util.d.ts" /> /// <reference path="v8.d.ts" /> /// <reference path="vm.d.ts" /> /// <reference path="wasi.d.ts" /> /// <reference path="worker_threads.d.ts" /> /// <reference path="zlib.d.ts" /> /// <reference path="globals.global.d.ts" />
/** * > Stability: 2 - Stable * * The `node:net` module provides an asynchronous network API for creating stream-based * TCP or `IPC` servers ({@link createServer}) and clients * ({@link createConnection}). * * It can be accessed using: * * ```js * const net = require('node:net'); * ``` * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/net.js) */ declare module "net" { import * as stream from "node:stream"; import { Abortable, EventEmitter } from "node:events"; import * as dns from "node:dns"; type LookupFunction = ( hostname: string, options: dns.LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, ) => void; interface AddressInfo { address: string; family: string; port: number; } interface SocketConstructorOpts { fd?: number | undefined; allowHalfOpen?: boolean | undefined; readable?: boolean | undefined; writable?: boolean | undefined; signal?: AbortSignal; } interface OnReadOpts { buffer: Uint8Array | (() => Uint8Array); /** * This function is called for every chunk of incoming data. * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. * Return false from this function to implicitly pause() the socket. */ callback(bytesWritten: number, buf: Uint8Array): boolean; } interface ConnectOpts { /** * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will * still be emitted as normal and methods like pause() and resume() will also behave as expected. */ onread?: OnReadOpts | undefined; } interface TcpSocketConnectOpts extends ConnectOpts { port: number; host?: string | undefined; localAddress?: string | undefined; localPort?: number | undefined; hints?: number | undefined; family?: number | undefined; lookup?: LookupFunction | undefined; noDelay?: boolean | undefined; keepAlive?: boolean | undefined; keepAliveInitialDelay?: number | undefined; /** * @since v18.13.0 */ autoSelectFamily?: boolean | undefined; /** * @since v18.13.0 */ autoSelectFamilyAttemptTimeout?: number | undefined; } interface IpcSocketConnectOpts extends ConnectOpts { path: string; } type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; /** * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also * an `EventEmitter`. * * A `net.Socket` can be created by the user and used directly to interact with * a server. For example, it is returned by {@link createConnection}, * so the user can use it to talk to the server. * * It can also be created by Node.js and passed to the user when a connection * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use * it to interact with the client. * @since v0.3.4 */ class Socket extends stream.Duplex { constructor(options?: SocketConstructorOpts); /** * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. * If the socket is still writable it implicitly calls `socket.end()`. * @since v0.3.4 */ dest
roySoon(): void; /** * Sends data on the socket. The second parameter specifies the encoding in the * case of a string. It defaults to UTF8 encoding. * * Returns `true` if the entire data was flushed successfully to the kernel * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. * * The optional `callback` parameter will be executed when the data is finally * written out, which may not be immediately. * * See `Writable` stream `write()` method for more * information. * @since v0.1.90 * @param [encoding='utf8'] Only used when data is `string`. */ write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; /** * Initiate a connection on a given socket. * * Possible signatures: * * * `socket.connect(options[, connectListener])` * * `socket.connect(path[, connectListener])` for `IPC` connections. * * `socket.connect(port[, host][, connectListener])` for TCP connections. * * Returns: `net.Socket` The socket itself. * * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, * instead of a `'connect'` event, an `'error'` event will be emitted with * the error passed to the `'error'` listener. * The last parameter `connectListener`, if supplied, will be added as a listener * for the `'connect'` event **once**. * * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined * behavior. */ connect(options: SocketConnectOpts, connectionListener?: () => void): this; connect(port: number, host: string, connectionListener?: () => void): this; connect(port: number, connectionListener?: () => void): this; connect(path: string, connectionListener?: () => void): this; /** * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. * @since v0.1.90 * @return The socket itself. */ setEncoding(encoding?: BufferEncoding): this; /** * Pauses the reading of data. That is, `'data'` events will not be emitted. * Useful to throttle back an upload. * @return The socket itself. */ pause(): this; /** * Close the TCP connection by sending an RST packet and destroy the stream. * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. * @since v18.3.0, v16.17.0 */ resetAndDestroy(): this; /** * Resumes reading after a call to `socket.pause()`. * @return The socket itself. */ resume(): this; /** * Sets the socket to timeout after `timeout` milliseconds of inactivity on * the socket. By default `net.Socket` do not have a timeout. * * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to * end the connection. * * ```js * socket.setTimeout(3000); * socket.on('timeout', () => { * console.log('socket timeout');
* socket.end(); * }); * ``` * * If `timeout` is 0, then the existing idle timeout is disabled. * * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. * @since v0.1.90 * @return The socket itself. */ setTimeout(timeout: number, callback?: () => void): this; /** * Enable/disable the use of Nagle's algorithm. * * When a TCP connection is created, it will have Nagle's algorithm enabled. * * Nagle's algorithm delays data before it is sent via the network. It attempts * to optimize throughput at the expense of latency. * * Passing `true` for `noDelay` or not passing an argument will disable Nagle's * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's * algorithm. * @since v0.1.90 * @param [noDelay=true] * @return The socket itself. */ setNoDelay(noDelay?: boolean): this; /** * Enable/disable keep-alive functionality, and optionally set the initial * delay before the first keepalive probe is sent on an idle socket. * * Set `initialDelay` (in milliseconds) to set the delay between the last * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default * (or previous) setting. * * Enabling the keep-alive functionality will set the following socket options: * * * `SO_KEEPALIVE=1` * * `TCP_KEEPIDLE=initialDelay` * * `TCP_KEEPCNT=10` * * `TCP_KEEPINTVL=1` * @since v0.1.92 * @param [enable=false] * @param [initialDelay=0] * @return The socket itself. */ setKeepAlive(enable?: boolean, initialDelay?: number): this; /** * Returns the bound `address`, the address `family` name and `port` of the * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` * @since v0.1.90 */ address(): AddressInfo | {}; /** * Calling `unref()` on a socket will allow the program to exit if this is the only * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. * @since v0.9.1 * @return The socket itself. */ unref(): this; /** * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). * If the socket is `ref`ed calling `ref` again will have no effect. * @since v0.9.1 * @return The socket itself. */ ref(): this; /** * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` * and it is an array of the addresses that have been attempted. * * Each address is a string in the form of `$IP:$PORT`. * If the connection was successful, then the last address is the one that the socket is currently connected to. * @since v19.4.0 */ readonly autoSelectFamilyAttemptedAddresses: string[]; /** * This property shows the number of characters buffered for writing. The buffer * may contain strings whose length after encoding is not yet known. So this number * is only an approximation of the number of bytes in the buffer. * * `net.Socket` has the property that `socket.write()` always works. This is to * help users get up and running quickly. The computer cannot always keep up * with the amount of data that is written to a socket. The network connection * simply might
be too slow. Node.js will internally queue up the data written to a * socket and send it out over the wire when it is possible. * * The consequence of this internal buffering is that memory may grow. * Users who experience large or growing `bufferSize` should attempt to * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. * @since v0.3.8 * @deprecated Since v14.6.0 - Use `writableLength` instead. */ readonly bufferSize: number; /** * The amount of received bytes. * @since v0.5.3 */ readonly bytesRead: number; /** * The amount of bytes sent. * @since v0.5.3 */ readonly bytesWritten: number; /** * If `true`,`socket.connect(options[, connectListener])` was * called and has not yet finished. It will stay `true` until the socket becomes * connected, then it is set to `false` and the `'connect'` event is emitted. Note * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. * @since v6.1.0 */ readonly connecting: boolean; /** * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting * (see `socket.connecting`). * @since v11.2.0, v10.16.0 */ readonly pending: boolean; /** * See `writable.destroyed` for further details. */ readonly destroyed: boolean; /** * The string representation of the local IP address the remote client is * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. * @since v0.9.6 */ readonly localAddress?: string; /** * The numeric representation of the local port. For example, `80` or `21`. * @since v0.9.6 */ readonly localPort?: number; /** * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. * @since v18.8.0, v16.18.0 */ readonly localFamily?: string; /** * This property represents the state of the connection as a string. * * * If the stream is connecting `socket.readyState` is `opening`. * * If the stream is readable and writable, it is `open`. * * If the stream is readable and not writable, it is `readOnly`. * * If the stream is not readable and writable, it is `writeOnly`. * @since v0.5.0 */ readonly readyState: SocketReadyState; /** * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if * the socket is destroyed (for example, if the client disconnected). * @since v0.5.10 */ readonly remoteAddress?: string | undefined; /** * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if * the socket is destroyed (for example, if the client disconnected). * @since v0.11.14 */ readonly remoteFamily?: string | undefined; /** * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if * the socket is destroyed (for example, if the client disconnected). * @since v0.5.10 */ readonly remotePort?: number | undefined; /** * The socket timeout in milliseconds as set by `socket.setTimeout()`. * It is `undefined` if a timeout has not been set. * @since v10.7.0 */ readonly timeout?: number | unde
fined; /** * Half-closes the socket. i.e., it sends a FIN packet. It is possible the * server will still send some data. * * See `writable.end()` for further details. * @since v0.1.90 * @param [encoding='utf8'] Only used when data is `string`. * @param callback Optional callback for when the socket is finished. * @return The socket itself. */ end(callback?: () => void): this; end(buffer: Uint8Array | string, callback?: () => void): this; end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; /** * events.EventEmitter * 1. close * 2. connect * 3. data * 4. drain * 5. end * 6. error * 7. lookup * 8. ready * 9. timeout */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: (hadError: boolean) => void): this; addListener(event: "connect", listener: () => void): this; addListener(event: "data", listener: (data: Buffer) => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "end", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener( event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void, ): this; addListener(event: "ready", listener: () => void): this; addListener(event: "timeout", listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close", hadError: boolean): boolean; emit(event: "connect"): boolean; emit(event: "data", data: Buffer): boolean; emit(event: "drain"): boolean; emit(event: "end"): boolean; emit(event: "error", err: Error): boolean; emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; emit(event: "ready"): boolean; emit(event: "timeout"): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: (hadError: boolean) => void): this; on(event: "connect", listener: () => void): this; on(event: "data", listener: (data: Buffer) => void): this; on(event: "drain", listener: () => void): this; on(event: "end", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on( event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void, ): this; on(event: "ready", listener: () => void): this; on(event: "timeout", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: (hadError: boolean) => void): this; once(event: "connect", listener: () => void): this; once(event: "data", listener: (data: Buffer) => void): this; once(event: "drain", listener: () => void): this; once(event: "end", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once( event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void, ): this; once(event: "ready", listener: () => void): this; once(event: "timeout", listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: (hadError: boolean) => void): this; prependListener(event: "connect", listener: () => void): this; prependListener(event: "data", listener: (data: Buffer) => void): this;
prependListener(event: "drain", listener: () => void): this; prependListener(event: "end", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener( event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void, ): this; prependListener(event: "ready", listener: () => void): this; prependListener(event: "timeout", listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; prependOnceListener(event: "connect", listener: () => void): this; prependOnceListener(event: "data", listener: (data: Buffer) => void): this; prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener( event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void, ): this; prependOnceListener(event: "ready", listener: () => void): this; prependOnceListener(event: "timeout", listener: () => void): this; } interface ListenOptions extends Abortable { port?: number | undefined; host?: string | undefined; backlog?: number | undefined; path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; /** * @default false */ ipv6Only?: boolean | undefined; } interface ServerOpts { /** * Indicates whether half-opened TCP connections are allowed. * @default false */ allowHalfOpen?: boolean | undefined; /** * Indicates whether the socket should be paused on incoming connections. * @default false */ pauseOnConnect?: boolean | undefined; /** * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. * @default false * @since v16.5.0 */ noDelay?: boolean | undefined; /** * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. * @default false * @since v16.5.0 */ keepAlive?: boolean | undefined; /** * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. * @default 0 * @since v16.5.0 */ keepAliveInitialDelay?: number | undefined; } interface DropArgument { localAddress?: string; localPort?: number; localFamily?: string; remoteAddress?: string; remotePort?: number; remoteFamily?: string; } /** * This class is used to create a TCP or `IPC` server. * @since v0.1.90 */ class Server extends EventEmitter { constructor(connectionListener?: (socket: Socket) => void); constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); /** * Start a server listening for connections. A `net.Server` can be a TCP or * an `IPC` server depending on what it listens to. * * Possible signatures: * * * `server.listen(handle[, backlog][, callback])` * * `server.listen(options[, callback])` * * `server.listen(path[, backlog][, callback])` for `IPC` servers * * `server.listen([port[, host[, backlog]]
][, callback])` for TCP servers * * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` * event. * * All `listen()` methods can take a `backlog` parameter to specify the maximum * length of the queue of pending connections. The actual length will be determined * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). * * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for * details). * * The `server.listen()` method can be called again if and only if there was an * error during the first `server.listen()` call or `server.close()` has been * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. * * One of the most common errors raised when listening is `EADDRINUSE`. * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry * after a certain amount of time: * * ```js * server.on('error', (e) => { * if (e.code === 'EADDRINUSE') { * console.error('Address in use, retrying...'); * setTimeout(() => { * server.close(); * server.listen(PORT, HOST); * }, 1000); * } * }); * ``` */ listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; listen(port?: number, hostname?: string, listeningListener?: () => void): this; listen(port?: number, backlog?: number, listeningListener?: () => void): this; listen(port?: number, listeningListener?: () => void): this; listen(path: string, backlog?: number, listeningListener?: () => void): this; listen(path: string, listeningListener?: () => void): this; listen(options: ListenOptions, listeningListener?: () => void): this; listen(handle: any, backlog?: number, listeningListener?: () => void): this; listen(handle: any, listeningListener?: () => void): this; /** * Stops the server from accepting new connections and keeps existing * connections. This function is asynchronous, the server is finally closed * when all connections are ended and the server emits a `'close'` event. * The optional `callback` will be called once the `'close'` event occurs. Unlike * that event, it will be called with an `Error` as its only argument if the server * was not open when it was closed. * @since v0.1.90 * @param callback Called when the server is closed. */ close(callback?: (err?: Error) => void): this; /** * Returns the bound `address`, the address `family` name, and `port` of the server * as reported by the operating system if listening on an IP socket * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. * * For a server listening on a pipe or Unix domain socket, the name is returned * as a string. * * ```js * const server = net.createServer((socket) => { * socket.end('goodbye\n'); * }).on('error', (err) => { * // Handle errors here. * throw err; * }); * * // Grab an arbitrary unused port. * server.listen(() => { * console.log('opened server on', server.address()); * }); * ``` * * `server.address()` returns `null` before the `'listening'` even
t has been * emitted or after calling `server.close()`. * @since v0.1.90 */ address(): AddressInfo | string | null; /** * Asynchronously get the number of concurrent connections on the server. Works * when sockets were sent to forks. * * Callback should take two arguments `err` and `count`. * @since v0.9.7 */ getConnections(cb: (error: Error | null, count: number) => void): void; /** * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). * If the server is `ref`ed calling `ref()` again will have no effect. * @since v0.9.1 */ ref(): this; /** * Calling `unref()` on a server will allow the program to exit if this is the only * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. * @since v0.9.1 */ unref(): this; /** * Set this property to reject connections when the server's connection count gets * high. * * It is not recommended to use this option once a socket has been sent to a child * with `child_process.fork()`. * @since v0.2.0 */ maxConnections: number; connections: number; /** * Indicates whether or not the server is listening for connections. * @since v5.7.0 */ readonly listening: boolean; /** * events.EventEmitter * 1. close * 2. connection * 3. error * 4. listening * 5. drop */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "connection", listener: (socket: Socket) => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "listening", listener: () => void): this; addListener(event: "drop", listener: (data?: DropArgument) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close"): boolean; emit(event: "connection", socket: Socket): boolean; emit(event: "error", err: Error): boolean; emit(event: "listening"): boolean; emit(event: "drop", data?: DropArgument): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "connection", listener: (socket: Socket) => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "listening", listener: () => void): this; on(event: "drop", listener: (data?: DropArgument) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "connection", listener: (socket: Socket) => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "listening", listener: () => void): this; once(event: "drop", listener: (data?: DropArgument) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "connection", listener: (socket: Socket) => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "listening", listener: () => void): this; prependListener(event: "drop", listener: (data?: DropArgument) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void)
: this; prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "listening", listener: () => void): this; prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; /** * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. * @since v20.5.0 */ [Symbol.asyncDispose](): Promise<void>; } type IPVersion = "ipv4" | "ipv6"; /** * The `BlockList` object can be used with some network APIs to specify rules for * disabling inbound or outbound access to specific IP addresses, IP ranges, or * IP subnets. * @since v15.0.0, v14.18.0 */ class BlockList { /** * Adds a rule to block the given IP address. * @since v15.0.0, v14.18.0 * @param address An IPv4 or IPv6 address. * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. */ addAddress(address: string, type?: IPVersion): void; addAddress(address: SocketAddress): void; /** * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). * @since v15.0.0, v14.18.0 * @param start The starting IPv4 or IPv6 address in the range. * @param end The ending IPv4 or IPv6 address in the range. * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. */ addRange(start: string, end: string, type?: IPVersion): void; addRange(start: SocketAddress, end: SocketAddress): void; /** * Adds a rule to block a range of IP addresses specified as a subnet mask. * @since v15.0.0, v14.18.0 * @param net The network IPv4 or IPv6 address. * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. */ addSubnet(net: SocketAddress, prefix: number): void; addSubnet(net: string, prefix: number, type?: IPVersion): void; /** * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. * * ```js * const blockList = new net.BlockList(); * blockList.addAddress('123.123.123.123'); * blockList.addRange('10.0.0.1', '10.0.0.10'); * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); * * console.log(blockList.check('123.123.123.123')); // Prints: true * console.log(blockList.check('10.0.0.3')); // Prints: true * console.log(blockList.check('222.111.111.222')); // Prints: false * * // IPv6 notation for IPv4 addresses works: * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true * ``` * @since v15.0.0, v14.18.0 * @param address The IP address to check * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. */ check(address: SocketAddress): boolean; check(address: string, type?: IPVersion): boolean; } interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { timeout?: number | undefined; } interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { timeout?: number | undefined; } type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; /** * Creates a new TCP or `IPC` server. * * If `allowHalfOpen` is set to `true`, when the other end of the socket * signals the end of transmission, the server will only send back the end of * transmission when `socket.end()` is explicitly called. For example, in the
* context of TCP, when a FIN packed is received, a FIN packed is sent * back only when `socket.end()` is explicitly called. Until then the * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. * * If `pauseOnConnect` is set to `true`, then the socket associated with each * incoming connection will be paused, and no data will be read from its handle. * This allows connections to be passed between processes without any data being * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. * * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. * * Here is an example of a TCP echo server which listens for connections * on port 8124: * * ```js * const net = require('node:net'); * const server = net.createServer((c) => { * // 'connection' listener. * console.log('client connected'); * c.on('end', () => { * console.log('client disconnected'); * }); * c.write('hello\r\n'); * c.pipe(c); * }); * server.on('error', (err) => { * throw err; * }); * server.listen(8124, () => { * console.log('server bound'); * }); * ``` * * Test this by using `telnet`: * * ```bash * telnet localhost 8124 * ``` * * To listen on the socket `/tmp/echo.sock`: * * ```js * server.listen('/tmp/echo.sock', () => { * console.log('server bound'); * }); * ``` * * Use `nc` to connect to a Unix domain socket server: * * ```bash * nc -U /tmp/echo.sock * ``` * @since v0.5.0 * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. */ function createServer(connectionListener?: (socket: Socket) => void): Server; function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; /** * Aliases to {@link createConnection}. * * Possible signatures: * * * {@link connect} * * {@link connect} for `IPC` connections. * * {@link connect} for TCP connections. */ function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; function connect(port: number, host?: string, connectionListener?: () => void): Socket; function connect(path: string, connectionListener?: () => void): Socket; /** * A factory function, which creates a new {@link Socket}, * immediately initiates connection with `socket.connect()`, * then returns the `net.Socket` that starts the connection. * * When the connection is established, a `'connect'` event will be emitted * on the returned socket. The last parameter `connectListener`, if supplied, * will be added as a listener for the `'connect'` event **once**. * * Possible signatures: * * * {@link createConnection} * * {@link createConnection} for `IPC` connections. * * {@link createConnection} for TCP connections. * * The {@link connect} function is an alias to this function. */ function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; function createConnection(path: string, connectionListener?: () => void): Socket; /** * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. * @since v19.4.0 */ function getDefaultAutoSelectFamily(): boolean; /** * Sets the default value of the `autoSelectFamily` option of `socket.connect(o