CoolFace
Apppublic

Pinsave/counterstrike

sourceHugging Faceupdated 3mo agoView on Hugging Face
1likes
promises.d.ts1281 linesDownload Raw Back to fs
1/**2 * The `fs/promises` API provides asynchronous file system methods that return3 * promises.4 *5 * The promise APIs use the underlying Node.js threadpool to perform file6 * system operations off the event loop thread. These operations are not7 * synchronized or threadsafe. Care must be taken when performing multiple8 * concurrent modifications on the same file or data corruption may occur.9 * @since v10.0.010 */11declare module "fs/promises" {12    import { Abortable } from "node:events";13    import { Stream } from "node:stream";14    import { ReadableStream } from "node:stream/web";15    import {16        BigIntStats,17        BigIntStatsFs,18        BufferEncodingOption,19        constants as fsConstants,20        CopyOptions,21        Dir,22        Dirent,23        GlobOptions,24        GlobOptionsWithFileTypes,25        GlobOptionsWithoutFileTypes,26        MakeDirectoryOptions,27        Mode,28        ObjectEncodingOptions,29        OpenDirOptions,30        OpenMode,31        PathLike,32        ReadPosition,33        ReadStream,34        ReadVResult,35        RmDirOptions,36        RmOptions,37        StatFsOptions,38        StatOptions,39        Stats,40        StatsFs,41        TimeLike,42        WatchEventType,43        WatchOptions,44        WriteStream,45        WriteVResult,46    } from "node:fs";47    import { Interface as ReadlineInterface } from "node:readline";48    interface FileChangeInfo<T extends string | Buffer> {49        eventType: WatchEventType;50        filename: T | null;51    }52    interface FlagAndOpenMode {53        mode?: Mode | undefined;54        flag?: OpenMode | undefined;55    }56    interface FileReadResult<T extends NodeJS.ArrayBufferView> {57        bytesRead: number;58        buffer: T;59    }60    interface FileReadOptions<T extends NodeJS.ArrayBufferView = Buffer> {61        /**62         * @default `Buffer.alloc(0xffff)`63         */64        buffer?: T;65        /**66         * @default 067         */68        offset?: number | null;69        /**70         * @default `buffer.byteLength`71         */72        length?: number | null;73        position?: ReadPosition | null;74    }75    interface CreateReadStreamOptions extends Abortable {76        encoding?: BufferEncoding | null | undefined;77        autoClose?: boolean | undefined;78        emitClose?: boolean | undefined;79        start?: number | undefined;80        end?: number | undefined;81        highWaterMark?: number | undefined;82    }83    interface CreateWriteStreamOptions {84        encoding?: BufferEncoding | null | undefined;85        autoClose?: boolean | undefined;86        emitClose?: boolean | undefined;87        start?: number | undefined;88        highWaterMark?: number | undefined;89        flush?: boolean | undefined;90    }91    // TODO: Add `EventEmitter` close92    interface FileHandle {93        /**94         * The numeric file descriptor managed by the {FileHandle} object.95         * @since v10.0.096         */97        readonly fd: number;98        /**99         * Alias of `filehandle.writeFile()`.100         *101         * When operating on file handles, the mode cannot be changed from what it was set102         * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`.103         * @since v10.0.0104         * @return Fulfills with `undefined` upon success.105         */106        appendFile(107            data: string | Uint8Array,108            options?:109                | (ObjectEncodingOptions & Abortable)110                | BufferEncoding111                | null,112        ): Promise<void>;113        /**114         * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html).115         * @since v10.0.0116         * @param uid The file's new owner's user id.117         * @param gid The file's new group's group id.118         * @return Fulfills with `undefined` upon success.119         */120        chown(uid: number, gid: number): Promise<void>;121        /**122         * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html).123         * @since v10.0.0124         * @param mode the file mode bit mask.125         * @return Fulfills with `undefined` upon success.126         */127        chmod(mode: Mode): Promise<void>;128        /**129         * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream130         * returned by this method has a default `highWaterMark` of 64 KiB.131         *132         * `options` can include `start` and `end` values to read a range of bytes from133         * the file instead of the entire file. Both `start` and `end` are inclusive and134         * start counting at 0, allowed values are in the135         * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is136         * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from137         * the current file position. The `encoding` can be any one of those accepted by `Buffer`.138         *139         * If the `FileHandle` points to a character device that only supports blocking140         * reads (such as keyboard or sound card), read operations do not finish until data141         * is available. This can prevent the process from exiting and the stream from142         * closing naturally.143         *144         * By default, the stream will emit a `'close'` event after it has been145         * destroyed.  Set the `emitClose` option to `false` to change this behavior.146         *147         * ```js148         * import { open } from 'node:fs/promises';149         *150         * const fd = await open('/dev/input/event0');151         * // Create a stream from some character device.152         * const stream = fd.createReadStream();153         * setTimeout(() => {154         *   stream.close(); // This may not close the stream.155         *   // Artificially marking end-of-stream, as if the underlying resource had156         *   // indicated end-of-file by itself, allows the stream to close.157         *   // This does not cancel pending read operations, and if there is such an158         *   // operation, the process may still not be able to exit successfully159         *   // until it finishes.160         *   stream.push(null);161         *   stream.read(0);162         * }, 100);163         * ```164         *165         * If `autoClose` is false, then the file descriptor won't be closed, even if166         * there's an error. It is the application's responsibility to close it and make167         * sure there's no file descriptor leak. If `autoClose` is set to true (default168         * behavior), on `'error'` or `'end'` the file descriptor will be closed169         * automatically.170         *171         * An example to read the last 10 bytes of a file which is 100 bytes long:172         *173         * ```js174         * import { open } from 'node:fs/promises';175         *176         * const fd = await open('sample.txt');177         * fd.createReadStream({ start: 90, end: 99 });178         * ```179         * @since v16.11.0180         */181        createReadStream(options?: CreateReadStreamOptions): ReadStream;182        /**183         * `options` may also include a `start` option to allow writing data at some184         * position past the beginning of the file, allowed values are in the185         * \[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 than186         * replacing it may require the `flags` `open` option to be set to `r+` rather than187         * the default `r`. The `encoding` can be any one of those accepted by `Buffer`.188         *189         * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false,190         * then the file descriptor won't be closed, even if there's an error.191         * It is the application's responsibility to close it and make sure there's no192         * file descriptor leak.193         *194         * By default, the stream will emit a `'close'` event after it has been195         * destroyed.  Set the `emitClose` option to `false` to change this behavior.196         * @since v16.11.0197         */198        createWriteStream(options?: CreateWriteStreamOptions): WriteStream;199        /**200         * Forces all currently queued I/O operations associated with the file to the201         * 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.202         *203         * Unlike `filehandle.sync` this method does not flush modified metadata.204         * @since v10.0.0205         * @return Fulfills with `undefined` upon success.206         */207        datasync(): Promise<void>;208        /**209         * Request that all data for the open file descriptor is flushed to the storage210         * device. The specific implementation is operating system and device specific.211         * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail.212         * @since v10.0.0213         * @return Fulfills with `undefined` upon success.214         */215        sync(): Promise<void>;216        /**217         * Reads data from the file and stores that in the given buffer.218         *219         * If the file is not modified concurrently, the end-of-file is reached when the220         * number of bytes read is zero.221         * @since v10.0.0222         * @param buffer A buffer that will be filled with the file data read.223         * @param offset The location in the buffer at which to start filling.224         * @param length The number of bytes to read.225         * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an226         * integer, the current file position will remain unchanged.227         * @return Fulfills upon success with an object with two properties:228         */229        read<T extends NodeJS.ArrayBufferView>(230            buffer: T,231            offset?: number | null,232            length?: number | null,233            position?: ReadPosition | null,234        ): Promise<FileReadResult<T>>;235        read<T extends NodeJS.ArrayBufferView = Buffer>(236            buffer: T,237            options?: FileReadOptions<T>,238        ): Promise<FileReadResult<T>>;239        read<T extends NodeJS.ArrayBufferView = Buffer>(options?: FileReadOptions<T>): Promise<FileReadResult<T>>;240        /**241         * Returns a byte-oriented `ReadableStream` that may be used to read the file's242         * contents.243         *244         * An error will be thrown if this method is called more than once or is called245         * after the `FileHandle` is closed or closing.246         *247         * ```js248         * import {249         *   open,250         * } from 'node:fs/promises';251         *252         * const file = await open('./some/file/to/read');253         *254         * for await (const chunk of file.readableWebStream())255         *   console.log(chunk);256         *257         * await file.close();258         * ```259         *260         * While the `ReadableStream` will read the file to completion, it will not261         * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method.262         * @since v17.0.0263         */264        readableWebStream(): ReadableStream;265        /**266         * Asynchronously reads the entire contents of a file.267         *268         * If `options` is a string, then it specifies the `encoding`.269         *270         * The `FileHandle` has to support reading.271         *272         * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current273         * position till the end of the file. It doesn't always read from the beginning274         * of the file.275         * @since v10.0.0276         * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the277         * data will be a string.278         */279        readFile(280            options?:281                | ({ encoding?: null | undefined } & Abortable)282                | null,283        ): Promise<Buffer>;284        /**285         * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically.286         * The `FileHandle` must have been opened for reading.287         */288        readFile(289            options:290                | ({ encoding: BufferEncoding } & Abortable)291                | BufferEncoding,292        ): Promise<string>;293        /**294         * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically.295         * The `FileHandle` must have been opened for reading.296         */297        readFile(298            options?:299                | (ObjectEncodingOptions & Abortable)300                | BufferEncoding301                | null,302        ): Promise<string | Buffer>;303        /**304         * Convenience method to create a `readline` interface and stream over the file.305         * See `filehandle.createReadStream()` for the options.306         *307         * ```js308         * import { open } from 'node:fs/promises';309         *310         * const file = await open('./some/file/to/read');311         *312         * for await (const line of file.readLines()) {313         *   console.log(line);314         * }315         * ```316         * @since v18.11.0317         */318        readLines(options?: CreateReadStreamOptions): ReadlineInterface;319        /**320         * @since v10.0.0321         * @return Fulfills with an {fs.Stats} for the file.322         */323        stat(324            opts?: StatOptions & {325                bigint?: false | undefined;326            },327        ): Promise<Stats>;328        stat(329            opts: StatOptions & {330                bigint: true;331            },332        ): Promise<BigIntStats>;333        stat(opts?: StatOptions): Promise<Stats | BigIntStats>;334        /**335         * Truncates the file.336         *337         * If the file was larger than `len` bytes, only the first `len` bytes will be338         * retained in the file.339         *340         * The following example retains only the first four bytes of the file:341         *342         * ```js343         * import { open } from 'node:fs/promises';344         *345         * let filehandle = null;346         * try {347         *   filehandle = await open('temp.txt', 'r+');348         *   await filehandle.truncate(4);349         * } finally {350         *   await filehandle?.close();351         * }352         * ```353         *354         * If the file previously was shorter than `len` bytes, it is extended, and the355         * extended part is filled with null bytes (`'\0'`):356         *357         * If `len` is negative then `0` will be used.358         * @since v10.0.0359         * @param [len=0]360         * @return Fulfills with `undefined` upon success.361         */362        truncate(len?: number): Promise<void>;363        /**364         * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success.365         * @since v10.0.0366         */367        utimes(atime: TimeLike, mtime: TimeLike): Promise<void>;368        /**369         * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an370         * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an371         * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object.372         * The promise is fulfilled with no arguments upon success.373         *374         * If `options` is a string, then it specifies the `encoding`.375         *376         * The `FileHandle` has to support writing.377         *378         * It is unsafe to use `filehandle.writeFile()` multiple times on the same file379         * without waiting for the promise to be fulfilled (or rejected).380         *381         * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the382         * current position till the end of the file. It doesn't always write from the383         * beginning of the file.384         * @since v10.0.0385         */386        writeFile(387            data: string | Uint8Array,388            options?:389                | (ObjectEncodingOptions & Abortable)390                | BufferEncoding391                | null,392        ): Promise<void>;393        /**394         * Write `buffer` to the file.395         *396         * The promise is fulfilled with an object containing two properties:397         *398         * It is unsafe to use `filehandle.write()` multiple times on the same file399         * without waiting for the promise to be fulfilled (or rejected). For this400         * scenario, use `filehandle.createWriteStream()`.401         *402         * On Linux, positional writes do not work when the file is opened in append mode.403         * The kernel ignores the position argument and always appends the data to404         * the end of the file.405         * @since v10.0.0406         * @param offset The start position from within `buffer` where the data to write begins.407         * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write.408         * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current409         * position. See the POSIX pwrite(2) documentation for more detail.410         */411        write<TBuffer extends Uint8Array>(412            buffer: TBuffer,413            offset?: number | null,414            length?: number | null,415            position?: number | null,416        ): Promise<{417            bytesWritten: number;418            buffer: TBuffer;419        }>;420        write<TBuffer extends Uint8Array>(421            buffer: TBuffer,422            options?: { offset?: number; length?: number; position?: number },423        ): Promise<{424            bytesWritten: number;425            buffer: TBuffer;426        }>;427        write(428            data: string,429            position?: number | null,430            encoding?: BufferEncoding | null,431        ): Promise<{432            bytesWritten: number;433            buffer: string;434        }>;435        /**436         * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file.437         *438         * The promise is fulfilled with an object containing a two properties:439         *440         * It is unsafe to call `writev()` multiple times on the same file without waiting441         * for the promise to be fulfilled (or rejected).442         *443         * On Linux, positional writes don't work when the file is opened in append mode.444         * The kernel ignores the position argument and always appends the data to445         * the end of the file.446         * @since v12.9.0447         * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current448         * position.449         */450        writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise<WriteVResult>;451        /**452         * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s453         * @since v13.13.0, v12.17.0454         * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position.455         * @return Fulfills upon success an object containing two properties:456         */457        readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise<ReadVResult>;458        /**459         * Closes the file handle after waiting for any pending operation on the handle to460         * complete.461         *462         * ```js463         * import { open } from 'node:fs/promises';464         *465         * let filehandle;466         * try {467         *   filehandle = await open('thefile.txt', 'r');468         * } finally {469         *   await filehandle?.close();470         * }471         * ```472         * @since v10.0.0473         * @return Fulfills with `undefined` upon success.474         */475        close(): Promise<void>;476        /**477         * An alias for {@link FileHandle.close()}.478         * @since v20.4.0479         */480        [Symbol.asyncDispose](): Promise<void>;481    }482    const constants: typeof fsConstants;483    /**484     * Tests a user's permissions for the file or directory specified by `path`.485     * The `mode` argument is an optional integer that specifies the accessibility486     * 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`487     * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for488     * possible values of `mode`.489     *490     * If the accessibility check is successful, the promise is fulfilled with no491     * value. If any of the accessibility checks fail, the promise is rejected492     * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and493     * written by the current process.494     *495     * ```js496     * import { access, constants } from 'node:fs/promises';497     *498     * try {499     *   await access('/etc/passwd', constants.R_OK | constants.W_OK);500     *   console.log('can access');501     * } catch {502     *   console.error('cannot access');503     * }504     * ```505     *506     * Using `fsPromises.access()` to check for the accessibility of a file before507     * calling `fsPromises.open()` is not recommended. Doing so introduces a race508     * condition, since other processes may change the file's state between the two509     * calls. Instead, user code should open/read/write the file directly and handle510     * the error raised if the file is not accessible.511     * @since v10.0.0512     * @param [mode=fs.constants.F_OK]513     * @return Fulfills with `undefined` upon success.514     */515    function access(path: PathLike, mode?: number): Promise<void>;516    /**517     * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it518     * already exists.519     *520     * No guarantees are made about the atomicity of the copy operation. If an521     * error occurs after the destination file has been opened for writing, an attempt522     * will be made to remove the destination.523     *524     * ```js525     * import { copyFile, constants } from 'node:fs/promises';526     *527     * try {528     *   await copyFile('source.txt', 'destination.txt');529     *   console.log('source.txt was copied to destination.txt');530     * } catch {531     *   console.error('The file could not be copied');532     * }533     *534     * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists.535     * try {536     *   await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);537     *   console.log('source.txt was copied to destination.txt');538     * } catch {539     *   console.error('The file could not be copied');540     * }541     * ```542     * @since v10.0.0543     * @param src source filename to copy544     * @param dest destination filename of the copy operation545     * @param [mode=0] Optional modifiers that specify 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.546     * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`)547     * @return Fulfills with `undefined` upon success.548     */549    function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise<void>;550    /**551     * Opens a `FileHandle`.552     *553     * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail.554     *555     * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented556     * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains557     * 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).558     * @since v10.0.0559     * @param [flags='r'] See `support of file system `flags``.560     * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created.561     * @return Fulfills with a {FileHandle} object.562     */563    function open(path: PathLike, flags?: string | number, mode?: Mode): Promise<FileHandle>;564    /**565     * Renames `oldPath` to `newPath`.566     * @since v10.0.0567     * @return Fulfills with `undefined` upon success.568     */569    function rename(oldPath: PathLike, newPath: PathLike): Promise<void>;570    /**571     * Truncates (shortens or extends the length) of the content at `path` to `len` bytes.572     * @since v10.0.0573     * @param [len=0]574     * @return Fulfills with `undefined` upon success.575     */576    function truncate(path: PathLike, len?: number): Promise<void>;577    /**578     * Removes the directory identified by `path`.579     *580     * Using `fsPromises.rmdir()` on a file (not a directory) results in the581     * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX.582     *583     * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`.584     * @since v10.0.0585     * @return Fulfills with `undefined` upon success.586     */587    function rmdir(path: PathLike, options?: RmDirOptions): Promise<void>;588    /**589     * Removes files and directories (modeled on the standard POSIX `rm` utility).590     * @since v14.14.0591     * @return Fulfills with `undefined` upon success.592     */593    function rm(path: PathLike, options?: RmOptions): Promise<void>;594    /**595     * Asynchronously creates a directory.596     *597     * The optional `options` argument can be an integer specifying `mode` (permission598     * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory599     * that exists results in a600     * rejection only when `recursive` is false.601     *602     * ```js603     * import { mkdir } from 'node:fs/promises';604     *605     * try {606     *   const projectFolder = new URL('./test/project/', import.meta.url);607     *   const createDir = await mkdir(projectFolder, { recursive: true });608     *609     *   console.log(`created ${createDir}`);610     * } catch (err) {611     *   console.error(err.message);612     * }613     * ```614     * @since v10.0.0615     * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`.616     */617    function mkdir(618        path: PathLike,619        options: MakeDirectoryOptions & {620            recursive: true;621        },622    ): Promise<string | undefined>;623    /**624     * Asynchronous mkdir(2) - create a directory.625     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.626     * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders627     * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.628     */629    function mkdir(630        path: PathLike,631        options?:632            | Mode633            | (MakeDirectoryOptions & {634                recursive?: false | undefined;635            })636            | null,637    ): Promise<void>;638    /**639     * Asynchronous mkdir(2) - create a directory.640     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.641     * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders642     * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.643     */644    function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise<string | undefined>;645    /**646     * Reads the contents of a directory.647     *648     * The optional `options` argument can be a string specifying an encoding, or an649     * object with an `encoding` property specifying the character encoding to use for650     * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned651     * will be passed as `Buffer` objects.652     *653     * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects.654     *655     * ```js656     * import { readdir } from 'node:fs/promises';657     *658     * try {659     *   const files = await readdir(path);660     *   for (const file of files)661     *     console.log(file);662     * } catch (err) {663     *   console.error(err);664     * }665     * ```666     * @since v10.0.0667     * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`.668     */669    function readdir(670        path: PathLike,671        options?:672            | (ObjectEncodingOptions & {673                withFileTypes?: false | undefined;674                recursive?: boolean | undefined;675            })676            | BufferEncoding677            | null,678    ): Promise<string[]>;679    /**680     * Asynchronous readdir(3) - read a directory.681     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.682     * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.683     */684    function readdir(685        path: PathLike,686        options:687            | {688                encoding: "buffer";689                withFileTypes?: false | undefined;690                recursive?: boolean | undefined;691            }692            | "buffer",693    ): Promise<Buffer[]>;694    /**695     * Asynchronous readdir(3) - read a directory.696     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.697     * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.698     */699    function readdir(700        path: PathLike,701        options?:702            | (ObjectEncodingOptions & {703                withFileTypes?: false | undefined;704                recursive?: boolean | undefined;705            })706            | BufferEncoding707            | null,708    ): Promise<string[] | Buffer[]>;709    /**710     * Asynchronous readdir(3) - read a directory.711     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.712     * @param options If called with `withFileTypes: true` the result data will be an array of Dirent.713     */714    function readdir(715        path: PathLike,716        options: ObjectEncodingOptions & {717            withFileTypes: true;718            recursive?: boolean | undefined;719        },720    ): Promise<Dirent[]>;721    /**722     * Asynchronous readdir(3) - read a directory.723     * @param path A path to a directory. If a URL is provided, it must use the `file:` protocol.724     * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`.725     */726    function readdir(727        path: PathLike,728        options: {729            encoding: "buffer";730            withFileTypes: true;731            recursive?: boolean | undefined;732        },733    ): Promise<Dirent<Buffer>[]>;734    /**735     * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is736     * fulfilled with the`linkString` upon success.737     *738     * The optional `options` argument can be a string specifying an encoding, or an739     * object with an `encoding` property specifying the character encoding to use for740     * the link path returned. If the `encoding` is set to `'buffer'`, the link path741     * returned will be passed as a `Buffer` object.742     * @since v10.0.0743     * @return Fulfills with the `linkString` upon success.744     */745    function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string>;746    /**747     * Asynchronous readlink(2) - read value of a symbolic link.748     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.749     * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.750     */751    function readlink(path: PathLike, options: BufferEncodingOption): Promise<Buffer>;752    /**753     * Asynchronous readlink(2) - read value of a symbolic link.754     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.755     * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.756     */757    function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise<string | Buffer>;758    /**759     * Creates a symbolic link.760     *761     * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will762     * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not763     * exist, `'file'` will be used. Windows junction points require the destination764     * path to be absolute. When using `'junction'`, the `target` argument will765     * automatically be normalized to absolute path. Junction points on NTFS volumes766     * can only point to directories.767     * @since v10.0.0768     * @param [type='null']769     * @return Fulfills with `undefined` upon success.770     */771    function symlink(target: PathLike, path: PathLike, type?: string | null): Promise<void>;772    /**773     * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link,774     * in which case the link itself is stat-ed, not the file that it refers to.775     * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail.776     * @since v10.0.0777     * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`.778     */779    function lstat(780        path: PathLike,781        opts?: StatOptions & {782            bigint?: false | undefined;783        },784    ): Promise<Stats>;785    function lstat(786        path: PathLike,787        opts: StatOptions & {788            bigint: true;789        },790    ): Promise<BigIntStats>;791    function lstat(path: PathLike, opts?: StatOptions): Promise<Stats | BigIntStats>;792    /**793     * @since v10.0.0794     * @return Fulfills with the {fs.Stats} object for the given `path`.795     */796    function stat(797        path: PathLike,798        opts?: StatOptions & {799            bigint?: false | undefined;800        },801    ): Promise<Stats>;802    function stat(803        path: PathLike,804        opts: StatOptions & {805            bigint: true;806        },807    ): Promise<BigIntStats>;808    function stat(path: PathLike, opts?: StatOptions): Promise<Stats | BigIntStats>;809    /**810     * @since v19.6.0, v18.15.0811     * @return Fulfills with the {fs.StatFs} object for the given `path`.812     */813    function statfs(814        path: PathLike,815        opts?: StatFsOptions & {816            bigint?: false | undefined;817        },818    ): Promise<StatsFs>;819    function statfs(820        path: PathLike,821        opts: StatFsOptions & {822            bigint: true;823        },824    ): Promise<BigIntStatsFs>;825    function statfs(path: PathLike, opts?: StatFsOptions): Promise<StatsFs | BigIntStatsFs>;826    /**827     * 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.828     * @since v10.0.0829     * @return Fulfills with `undefined` upon success.830     */831    function link(existingPath: PathLike, newPath: PathLike): Promise<void>;832    /**833     * If `path` refers to a symbolic link, then the link is removed without affecting834     * the file or directory to which that link refers. If the `path` refers to a file835     * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail.836     * @since v10.0.0837     * @return Fulfills with `undefined` upon success.838     */839    function unlink(path: PathLike): Promise<void>;840    /**841     * Changes the permissions of a file.842     * @since v10.0.0843     * @return Fulfills with `undefined` upon success.844     */845    function chmod(path: PathLike, mode: Mode): Promise<void>;846    /**847     * Changes the permissions on a symbolic link.848     *849     * This method is only implemented on macOS.850     * @deprecated Since v10.0.0851     * @return Fulfills with `undefined` upon success.852     */853    function lchmod(path: PathLike, mode: Mode): Promise<void>;854    /**855     * Changes the ownership on a symbolic link.856     * @since v10.0.0857     * @return Fulfills with `undefined` upon success.858     */859    function lchown(path: PathLike, uid: number, gid: number): Promise<void>;860    /**861     * 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 a862     * symbolic link, then the link is not dereferenced: instead, the timestamps of863     * the symbolic link itself are changed.864     * @since v14.5.0, v12.19.0865     * @return Fulfills with `undefined` upon success.866     */867    function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>;868    /**869     * Changes the ownership of a file.870     * @since v10.0.0871     * @return Fulfills with `undefined` upon success.872     */873    function chown(path: PathLike, uid: number, gid: number): Promise<void>;874    /**875     * Change the file system timestamps of the object referenced by `path`.876     *877     * The `atime` and `mtime` arguments follow these rules:878     *879     * * Values can be either numbers representing Unix epoch time, `Date`s, or a880     * numeric string like `'123456789.0'`.881     * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown.882     * @since v10.0.0883     * @return Fulfills with `undefined` upon success.884     */885    function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>;886    /**887     * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function.888     *889     * Only paths that can be converted to UTF8 strings are supported.890     *891     * The optional `options` argument can be a string specifying an encoding, or an892     * object with an `encoding` property specifying the character encoding to use for893     * the path. If the `encoding` is set to `'buffer'`, the path returned will be894     * passed as a `Buffer` object.895     *896     * On Linux, when Node.js is linked against musl libc, the procfs file system must897     * be mounted on `/proc` in order for this function to work. Glibc does not have898     * this restriction.899     * @since v10.0.0900     * @return Fulfills with the resolved path upon success.901     */902    function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string>;903    /**904     * Asynchronous realpath(3) - return the canonicalized absolute pathname.905     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.906     * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.907     */908    function realpath(path: PathLike, options: BufferEncodingOption): Promise<Buffer>;909    /**910     * Asynchronous realpath(3) - return the canonicalized absolute pathname.911     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.912     * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.913     */914    function realpath(915        path: PathLike,916        options?: ObjectEncodingOptions | BufferEncoding | null,917    ): Promise<string | Buffer>;918    /**919     * Creates a unique temporary directory. A unique directory name is generated by920     * appending six random characters to the end of the provided `prefix`. Due to921     * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some922     * platforms, notably the BSDs, can return more than six random characters, and923     * replace trailing `X` characters in `prefix` with random characters.924     *925     * The optional `options` argument can be a string specifying an encoding, or an926     * object with an `encoding` property specifying the character encoding to use.927     *928     * ```js929     * import { mkdtemp } from 'node:fs/promises';930     * import { join } from 'node:path';931     * import { tmpdir } from 'node:os';932     *933     * try {934     *   await mkdtemp(join(tmpdir(), 'foo-'));935     * } catch (err) {936     *   console.error(err);937     * }938     * ```939     *940     * The `fsPromises.mkdtemp()` method will append the six randomly selected941     * 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 trailing942     * platform-specific path separator943     * (`import { sep } from 'node:path'`).944     * @since v10.0.0945     * @return Fulfills with a string containing the file system path of the newly created temporary directory.946     */947    function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string>;948    /**949     * Asynchronously creates a unique temporary directory.950     * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory.951     * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.952     */953    function mkdtemp(prefix: string, options: BufferEncodingOption): Promise<Buffer>;954    /**955     * Asynchronously creates a unique temporary directory.956     * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory.957     * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.958     */959    function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string | Buffer>;960    /**961     * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an962     * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an963     * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object.964     *965     * The `encoding` option is ignored if `data` is a buffer.966     *967     * If `options` is a string, then it specifies the encoding.968     *969     * The `mode` option only affects the newly created file. See `fs.open()` for more details.970     *971     * Any specified `FileHandle` has to support writing.972     *973     * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file974     * without waiting for the promise to be settled.975     *976     * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience977     * method that performs multiple `write` calls internally to write the buffer978     * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`.979     *980     * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`.981     * Cancelation is "best effort", and some amount of data is likely still982     * to be written.983     *984     * ```js985     * import { writeFile } from 'node:fs/promises';986     * import { Buffer } from 'node:buffer';987     *988     * try {989     *   const controller = new AbortController();990     *   const { signal } = controller;991     *   const data = new Uint8Array(Buffer.from('Hello Node.js'));992     *   const promise = writeFile('message.txt', data, { signal });993     *994     *   // Abort the request before the promise settles.995     *   controller.abort();996     *997     *   await promise;998     * } catch (err) {999     *   // When a request is aborted - err is an AbortError1000     *   console.error(err);1001     * }1002     * ```1003     *1004     * Aborting an ongoing request does not abort individual operating1005     * system requests but rather the internal buffering `fs.writeFile` performs.1006     * @since v10.0.01007     * @param file filename or `FileHandle`1008     * @return Fulfills with `undefined` upon success.1009     */1010    function writeFile(1011        file: PathLike | FileHandle,1012        data:1013            | string1014            | NodeJS.ArrayBufferView1015            | Iterable<string | NodeJS.ArrayBufferView>1016            | AsyncIterable<string | NodeJS.ArrayBufferView>1017            | Stream,1018        options?:1019            | (ObjectEncodingOptions & {1020                mode?: Mode | undefined;1021                flag?: OpenMode | undefined;1022                /**1023                 * If all data is successfully written to the file, and `flush`1024                 * is `true`, `filehandle.sync()` is used to flush the data.1025                 * @default false1026                 */1027                flush?: boolean | undefined;1028            } & Abortable)1029            | BufferEncoding1030            | null,1031    ): Promise<void>;1032    /**1033     * Asynchronously append data to a file, creating the file if it does not yet1034     * exist. `data` can be a string or a `Buffer`.1035     *1036     * If `options` is a string, then it specifies the `encoding`.1037     *1038     * The `mode` option only affects the newly created file. See `fs.open()` for more details.1039     *1040     * The `path` may be specified as a `FileHandle` that has been opened1041     * for appending (using `fsPromises.open()`).1042     * @since v10.0.01043     * @param path filename or {FileHandle}1044     * @return Fulfills with `undefined` upon success.1045     */1046    function appendFile(1047        path: PathLike | FileHandle,1048        data: string | Uint8Array,1049        options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null,1050    ): Promise<void>;1051    /**1052     * Asynchronously reads the entire contents of a file.1053     *1054     * If no encoding is specified (using `options.encoding`), the data is returned1055     * as a `Buffer` object. Otherwise, the data will be a string.1056     *1057     * If `options` is a string, then it specifies the encoding.1058     *1059     * When the `path` is a directory, the behavior of `fsPromises.readFile()` is1060     * platform-specific. On macOS, Linux, and Windows, the promise will be rejected1061     * with an error. On FreeBSD, a representation of the directory's contents will be1062     * returned.1063     *1064     * An example of reading a `package.json` file located in the same directory of the1065     * running code:1066     *1067     * ```js1068     * import { readFile } from 'node:fs/promises';1069     * try {1070     *   const filePath = new URL('./package.json', import.meta.url);1071     *   const contents = await readFile(filePath, { encoding: 'utf8' });1072     *   console.log(contents);1073     * } catch (err) {1074     *   console.error(err.message);1075     * }1076     * ```1077     *1078     * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a1079     * request is aborted the promise returned is rejected with an `AbortError`:1080     *1081     * ```js1082     * import { readFile } from 'node:fs/promises';1083     *1084     * try {1085     *   const controller = new AbortController();1086     *   const { signal } = controller;1087     *   const promise = readFile(fileName, { signal });1088     *1089     *   // Abort the request before the promise settles.1090     *   controller.abort();1091     *1092     *   await promise;1093     * } catch (err) {1094     *   // When a request is aborted - err is an AbortError1095     *   console.error(err);1096     * }1097     * ```1098     *1099     * Aborting an ongoing request does not abort individual operating1100     * system requests but rather the internal buffering `fs.readFile` performs.1101     *1102     * Any specified `FileHandle` has to support reading.1103     * @since v10.0.01104     * @param path filename or `FileHandle`1105     * @return Fulfills with the contents of the file.1106     */1107    function readFile(1108        path: PathLike | FileHandle,1109        options?:1110            | ({1111                encoding?: null | undefined;1112                flag?: OpenMode | undefined;1113            } & Abortable)1114            | null,1115    ): Promise<Buffer>;1116    /**1117     * Asynchronously reads the entire contents of a file.1118     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.1119     * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically.1120     * @param options An object that may contain an optional flag.1121     * If a flag is not provided, it defaults to `'r'`.1122     */1123    function readFile(1124        path: PathLike | FileHandle,1125        options:1126            | ({1127                encoding: BufferEncoding;1128                flag?: OpenMode | undefined;1129            } & Abortable)1130            | BufferEncoding,1131    ): Promise<string>;1132    /**1133     * Asynchronously reads the entire contents of a file.1134     * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.1135     * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically.1136     * @param options An object that may contain an optional flag.1137     * If a flag is not provided, it defaults to `'r'`.1138     */1139    function readFile(1140        path: PathLike | FileHandle,1141        options?:1142            | (1143                & ObjectEncodingOptions1144                & Abortable1145                & {1146                    flag?: OpenMode | undefined;1147                }1148            )1149            | BufferEncoding1150            | null,1151    ): Promise<string | Buffer>;1152    /**1153     * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail.1154     *1155     * Creates an `fs.Dir`, which contains all further functions for reading from1156     * and cleaning up the directory.1157     *1158     * The `encoding` option sets the encoding for the `path` while opening the1159     * directory and subsequent read operations.1160     *1161     * Example using async iteration:1162     *1163     * ```js1164     * import { opendir } from 'node:fs/promises';1165     *1166     * try {1167     *   const dir = await opendir('./');1168     *   for await (const dirent of dir)1169     *     console.log(dirent.name);1170     * } catch (err) {1171     *   console.error(err);1172     * }1173     * ```1174     *1175     * When using the async iterator, the `fs.Dir` object will be automatically1176     * closed after the iterator exits.1177     * @since v12.12.01178     * @return Fulfills with an {fs.Dir}.1179     */1180    function opendir(path: PathLike, options?: OpenDirOptions): Promise<Dir>;1181    /**1182     * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory.1183     *1184     * ```js1185     * import { watch } from 'node:fs/promises';1186     *1187     * const ac = new AbortController();1188     * const { signal } = ac;1189     * setTimeout(() => ac.abort(), 10000);1190     *1191     * (async () => {1192     *   try {1193     *     const watcher = watch(__filename, { signal });1194     *     for await (const event of watcher)1195     *       console.log(event);1196     *   } catch (err) {1197     *     if (err.name === 'AbortError')1198     *       return;1199     *     throw err;1200     *   }

Showing the first 1,200 of 1281 lines. Download the file for the rest.