UNPKG

50.7 kBTypeScriptView Raw
1/**
2 * The `fs/promises` API provides asynchronous file system methods that return
3 * promises.
4 *
5 * The promise APIs use the underlying Node.js threadpool to perform file
6 * system operations off the event loop thread. These operations are not
7 * synchronized or threadsafe. Care must be taken when performing multiple
8 * concurrent modifications on the same file or data corruption may occur.
9 * @since v10.0.0
10 */
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 Stats,
17 BigIntStats,
18 StatOptions,
19 WriteVResult,
20 ReadVResult,
21 PathLike,
22 RmDirOptions,
23 RmOptions,
24 MakeDirectoryOptions,
25 Dirent,
26 OpenDirOptions,
27 Dir,
28 ObjectEncodingOptions,
29 BufferEncodingOption,
30 OpenMode,
31 Mode,
32 WatchOptions,
33 WatchEventType,
34 CopyOptions,
35 ReadStream,
36 WriteStream,
37 } from 'node:fs';
38 interface FileChangeInfo<T extends string | Buffer> {
39 eventType: WatchEventType;
40 filename: T;
41 }
42 interface FlagAndOpenMode {
43 mode?: Mode | undefined;
44 flag?: OpenMode | undefined;
45 }
46 interface FileReadResult<T extends NodeJS.ArrayBufferView> {
47 bytesRead: number;
48 buffer: T;
49 }
50 interface FileReadOptions<T extends NodeJS.ArrayBufferView = Buffer> {
51 /**
52 * @default `Buffer.alloc(0xffff)`
53 */
54 buffer?: T;
55 /**
56 * @default 0
57 */
58 offset?: number | null;
59 /**
60 * @default `buffer.byteLength`
61 */
62 length?: number | null;
63 position?: number | null;
64 }
65 interface CreateReadStreamOptions {
66 encoding?: BufferEncoding | null | undefined;
67 autoClose?: boolean | undefined;
68 emitClose?: boolean | undefined;
69 start?: number | undefined;
70 end?: number | undefined;
71 highWaterMark?: number | undefined;
72 }
73 interface CreateWriteStreamOptions {
74 encoding?: BufferEncoding | null | undefined;
75 autoClose?: boolean | undefined;
76 emitClose?: boolean | undefined;
77 start?: number | undefined;
78 }
79 // TODO: Add `EventEmitter` close
80 interface FileHandle {
81 /**
82 * The numeric file descriptor managed by the {FileHandle} object.
83 * @since v10.0.0
84 */
85 readonly fd: number;
86 /**
87 * Alias of `filehandle.writeFile()`.
88 *
89 * When operating on file handles, the mode cannot be changed from what it was set
90 * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`.
91 * @since v10.0.0
92 * @return Fulfills with `undefined` upon success.
93 */
94 appendFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise<void>;
95 /**
96 * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html).
97 * @since v10.0.0
98 * @param uid The file's new owner's user id.
99 * @param gid The file's new group's group id.
100 * @return Fulfills with `undefined` upon success.
101 */
102 chown(uid: number, gid: number): Promise<void>;
103 /**
104 * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html).
105 * @since v10.0.0
106 * @param mode the file mode bit mask.
107 * @return Fulfills with `undefined` upon success.
108 */
109 chmod(mode: Mode): Promise<void>;
110 /**
111 * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream
112 * returned by this method has a default `highWaterMark` of 64 kb.
113 *
114 * `options` can include `start` and `end` values to read a range of bytes from
115 * the file instead of the entire file. Both `start` and `end` are inclusive and
116 * start counting at 0, allowed values are in the
117 * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is
118 * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from
119 * the current file position. The `encoding` can be any one of those accepted by `Buffer`.
120 *
121 * If the `FileHandle` points to a character device that only supports blocking
122 * reads (such as keyboard or sound card), read operations do not finish until data
123 * is available. This can prevent the process from exiting and the stream from
124 * closing naturally.
125 *
126 * By default, the stream will emit a `'close'` event after it has been
127 * destroyed. Set the `emitClose` option to `false` to change this behavior.
128 *
129 * ```js
130 * import { open } from 'fs/promises';
131 *
132 * const fd = await open('/dev/input/event0');
133 * // Create a stream from some character device.
134 * const stream = fd.createReadStream();
135 * setTimeout(() => {
136 * stream.close(); // This may not close the stream.
137 * // Artificially marking end-of-stream, as if the underlying resource had
138 * // indicated end-of-file by itself, allows the stream to close.
139 * // This does not cancel pending read operations, and if there is such an
140 * // operation, the process may still not be able to exit successfully
141 * // until it finishes.
142 * stream.push(null);
143 * stream.read(0);
144 * }, 100);
145 * ```
146 *
147 * If `autoClose` is false, then the file descriptor won't be closed, even if
148 * there's an error. It is the application's responsibility to close it and make
149 * sure there's no file descriptor leak. If `autoClose` is set to true (default
150 * behavior), on `'error'` or `'end'` the file descriptor will be closed
151 * automatically.
152 *
153 * An example to read the last 10 bytes of a file which is 100 bytes long:
154 *
155 * ```js
156 * import { open } from 'fs/promises';
157 *
158 * const fd = await open('sample.txt');
159 * fd.createReadStream({ start: 90, end: 99 });
160 * ```
161 * @since v16.11.0
162 */
163 createReadStream(options?: CreateReadStreamOptions): ReadStream;
164 /**
165 * `options` may also include a `start` option to allow writing data at some
166 * position past the beginning of the file, allowed values are in the
167 * \[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
168 * it may require the `flags` `open` option to be set to `r+` rather than the
169 * default `r`. The `encoding` can be any one of those accepted by `Buffer`.
170 *
171 * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false,
172 * then the file descriptor won't be closed, even if there's an error.
173 * It is the application's responsibility to close it and make sure there's no
174 * file descriptor leak.
175 *
176 * By default, the stream will emit a `'close'` event after it has been
177 * destroyed. Set the `emitClose` option to `false` to change this behavior.
178 * @since v16.11.0
179 */
180 createWriteStream(options?: CreateWriteStreamOptions): WriteStream;
181 /**
182 * Forces all currently queued I/O operations associated with the file to the
183 * 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.
184 *
185 * Unlike `filehandle.sync` this method does not flush modified metadata.
186 * @since v10.0.0
187 * @return Fulfills with `undefined` upon success.
188 */
189 datasync(): Promise<void>;
190 /**
191 * Request that all data for the open file descriptor is flushed to the storage
192 * device. The specific implementation is operating system and device specific.
193 * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail.
194 * @since v10.0.0
195 * @return Fufills with `undefined` upon success.
196 */
197 sync(): Promise<void>;
198 /**
199 * Reads data from the file and stores that in the given buffer.
200 *
201 * If the file is not modified concurrently, the end-of-file is reached when the
202 * number of bytes read is zero.
203 * @since v10.0.0
204 * @param buffer A buffer that will be filled with the file data read.
205 * @param offset The location in the buffer at which to start filling.
206 * @param length The number of bytes to read.
207 * @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 an
208 * integer, the current file position will remain unchanged.
209 * @return Fulfills upon success with an object with two properties:
210 */
211 read<T extends NodeJS.ArrayBufferView>(buffer: T, offset?: number | null, length?: number | null, position?: number | null): Promise<FileReadResult<T>>;
212 read<T extends NodeJS.ArrayBufferView = Buffer>(options?: FileReadOptions<T>): Promise<FileReadResult<T>>;
213 /**
214 * Returns a `ReadableStream` that may be used to read the files data.
215 *
216 * An error will be thrown if this method is called more than once or is called after the `FileHandle` is closed
217 * or closing.
218 *
219 * ```js
220 * import { open } from 'node:fs/promises';
221 *
222 * const file = await open('./some/file/to/read');
223 *
224 * for await (const chunk of file.readableWebStream())
225 * console.log(chunk);
226 *
227 * await file.close();
228 * ```
229 *
230 * While the `ReadableStream` will read the file to completion, it will not close the `FileHandle` automatically. User code must still call the `fileHandle.close()` method.
231 *
232 * @since v17.0.0
233 * @experimental
234 */
235 readableWebStream(): ReadableStream;
236 /**
237 * Asynchronously reads the entire contents of a file.
238 *
239 * If `options` is a string, then it specifies the `encoding`.
240 *
241 * The `FileHandle` has to support reading.
242 *
243 * 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 current
244 * position till the end of the file. It doesn't always read from the beginning
245 * of the file.
246 * @since v10.0.0
247 * @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, the
248 * data will be a string.
249 */
250 readFile(
251 options?: {
252 encoding?: null | undefined;
253 flag?: OpenMode | undefined;
254 } | null
255 ): Promise<Buffer>;
256 /**
257 * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically.
258 * The `FileHandle` must have been opened for reading.
259 * @param options An object that may contain an optional flag.
260 * If a flag is not provided, it defaults to `'r'`.
261 */
262 readFile(
263 options:
264 | {
265 encoding: BufferEncoding;
266 flag?: OpenMode | undefined;
267 }
268 | BufferEncoding
269 ): Promise<string>;
270 /**
271 * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically.
272 * The `FileHandle` must have been opened for reading.
273 * @param options An object that may contain an optional flag.
274 * If a flag is not provided, it defaults to `'r'`.
275 */
276 readFile(
277 options?:
278 | (ObjectEncodingOptions & {
279 flag?: OpenMode | undefined;
280 })
281 | BufferEncoding
282 | null
283 ): Promise<string | Buffer>;
284 /**
285 * @since v10.0.0
286 * @return Fulfills with an {fs.Stats} for the file.
287 */
288 stat(
289 opts?: StatOptions & {
290 bigint?: false | undefined;
291 }
292 ): Promise<Stats>;
293 stat(
294 opts: StatOptions & {
295 bigint: true;
296 }
297 ): Promise<BigIntStats>;
298 stat(opts?: StatOptions): Promise<Stats | BigIntStats>;
299 /**
300 * Truncates the file.
301 *
302 * If the file was larger than `len` bytes, only the first `len` bytes will be
303 * retained in the file.
304 *
305 * The following example retains only the first four bytes of the file:
306 *
307 * ```js
308 * import { open } from 'fs/promises';
309 *
310 * let filehandle = null;
311 * try {
312 * filehandle = await open('temp.txt', 'r+');
313 * await filehandle.truncate(4);
314 * } finally {
315 * await filehandle?.close();
316 * }
317 * ```
318 *
319 * If the file previously was shorter than `len` bytes, it is extended, and the
320 * extended part is filled with null bytes (`'\0'`):
321 *
322 * If `len` is negative then `0` will be used.
323 * @since v10.0.0
324 * @param [len=0]
325 * @return Fulfills with `undefined` upon success.
326 */
327 truncate(len?: number): Promise<void>;
328 /**
329 * Change the file system timestamps of the object referenced by the `FileHandle` then resolves the promise with no arguments upon success.
330 * @since v10.0.0
331 */
332 utimes(atime: string | number | Date, mtime: string | number | Date): Promise<void>;
333 /**
334 * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an
335 * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or
336 * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object, or an
337 * object with an own `toString` function
338 * property. The promise is resolved with no arguments upon success.
339 *
340 * If `options` is a string, then it specifies the `encoding`.
341 *
342 * The `FileHandle` has to support writing.
343 *
344 * It is unsafe to use `filehandle.writeFile()` multiple times on the same file
345 * without waiting for the promise to be resolved (or rejected).
346 *
347 * 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 the
348 * current position till the end of the file. It doesn't always write from the
349 * beginning of the file.
350 * @since v10.0.0
351 */
352 writeFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode & Abortable) | BufferEncoding | null): Promise<void>;
353 /**
354 * Write `buffer` to the file.
355 *
356 * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property.
357 *
358 * The promise is resolved with an object containing two properties:
359 *
360 * It is unsafe to use `filehandle.write()` multiple times on the same file
361 * without waiting for the promise to be resolved (or rejected). For this
362 * scenario, use `fs.createWriteStream()`.
363 *
364 * On Linux, positional writes do not work when the file is opened in append mode.
365 * The kernel ignores the position argument and always appends the data to
366 * the end of the file.
367 * @since v10.0.0
368 * @param [offset=0] The start position from within `buffer` where the data to write begins.
369 * @param [length=buffer.byteLength] The number of bytes from `buffer` to write.
370 * @param position 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 current position.
371 * See the POSIX pwrite(2) documentation for more detail.
372 */
373 write<TBuffer extends Uint8Array>(
374 buffer: TBuffer,
375 offset?: number | null,
376 length?: number | null,
377 position?: number | null
378 ): Promise<{
379 bytesWritten: number;
380 buffer: TBuffer;
381 }>;
382 write(
383 data: string,
384 position?: number | null,
385 encoding?: BufferEncoding | null
386 ): Promise<{
387 bytesWritten: number;
388 buffer: string;
389 }>;
390 /**
391 * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file.
392 *
393 * The promise is resolved with an object containing a two properties:
394 *
395 * It is unsafe to call `writev()` multiple times on the same file without waiting
396 * for the promise to be resolved (or rejected).
397 *
398 * On Linux, positional writes don't work when the file is opened in append mode.
399 * The kernel ignores the position argument and always appends the data to
400 * the end of the file.
401 * @since v12.9.0
402 * @param position 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 current
403 * position.
404 */
405 writev(buffers: ReadonlyArray<NodeJS.ArrayBufferView>, position?: number): Promise<WriteVResult>;
406 /**
407 * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s
408 * @since v13.13.0, v12.17.0
409 * @param position 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.
410 * @return Fulfills upon success an object containing two properties:
411 */
412 readv(buffers: ReadonlyArray<NodeJS.ArrayBufferView>, position?: number): Promise<ReadVResult>;
413 /**
414 * Closes the file handle after waiting for any pending operation on the handle to
415 * complete.
416 *
417 * ```js
418 * import { open } from 'fs/promises';
419 *
420 * let filehandle;
421 * try {
422 * filehandle = await open('thefile.txt', 'r');
423 * } finally {
424 * await filehandle?.close();
425 * }
426 * ```
427 * @since v10.0.0
428 * @return Fulfills with `undefined` upon success.
429 */
430 close(): Promise<void>;
431 }
432 /**
433 * Tests a user's permissions for the file or directory specified by `path`.
434 * The `mode` argument is an optional integer that specifies the accessibility
435 * checks to be performed. Check `File access constants` for possible values
436 * of `mode`. It is possible to create a mask consisting of the bitwise OR of
437 * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
438 *
439 * If the accessibility check is successful, the promise is resolved with no
440 * value. If any of the accessibility checks fail, the promise is rejected
441 * 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 and
442 * written by the current process.
443 *
444 * ```js
445 * import { access } from 'fs/promises';
446 * import { constants } from 'fs';
447 *
448 * try {
449 * await access('/etc/passwd', constants.R_OK | constants.W_OK);
450 * console.log('can access');
451 * } catch {
452 * console.error('cannot access');
453 * }
454 * ```
455 *
456 * Using `fsPromises.access()` to check for the accessibility of a file before
457 * calling `fsPromises.open()` is not recommended. Doing so introduces a race
458 * condition, since other processes may change the file's state between the two
459 * calls. Instead, user code should open/read/write the file directly and handle
460 * the error raised if the file is not accessible.
461 * @since v10.0.0
462 * @param [mode=fs.constants.F_OK]
463 * @return Fulfills with `undefined` upon success.
464 */
465 function access(path: PathLike, mode?: number): Promise<void>;
466 /**
467 * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
468 * already exists.
469 *
470 * No guarantees are made about the atomicity of the copy operation. If an
471 * error occurs after the destination file has been opened for writing, an attempt
472 * will be made to remove the destination.
473 *
474 * ```js
475 * import { constants } from 'fs';
476 * import { copyFile } from 'fs/promises';
477 *
478 * try {
479 * await copyFile('source.txt', 'destination.txt');
480 * console.log('source.txt was copied to destination.txt');
481 * } catch {
482 * console.log('The file could not be copied');
483 * }
484 *
485 * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
486 * try {
487 * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
488 * console.log('source.txt was copied to destination.txt');
489 * } catch {
490 * console.log('The file could not be copied');
491 * }
492 * ```
493 * @since v10.0.0
494 * @param src source filename to copy
495 * @param dest destination filename of the copy operation
496 * @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.
497 * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`)
498 * @return Fulfills with `undefined` upon success.
499 */
500 function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise<void>;
501 /**
502 * Opens a `FileHandle`.
503 *
504 * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail.
505 *
506 * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
507 * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains
508 * 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).
509 * @since v10.0.0
510 * @param [flags='r'] See `support of file system `flags``.
511 * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created.
512 * @return Fulfills with a {FileHandle} object.
513 */
514 function open(path: PathLike, flags?: string | number, mode?: Mode): Promise<FileHandle>;
515 /**
516 * Renames `oldPath` to `newPath`.
517 * @since v10.0.0
518 * @return Fulfills with `undefined` upon success.
519 */
520 function rename(oldPath: PathLike, newPath: PathLike): Promise<void>;
521 /**
522 * Truncates (shortens or extends the length) of the content at `path` to `len`bytes.
523 * @since v10.0.0
524 * @param [len=0]
525 * @return Fulfills with `undefined` upon success.
526 */
527 function truncate(path: PathLike, len?: number): Promise<void>;
528 /**
529 * Removes the directory identified by `path`.
530 *
531 * Using `fsPromises.rmdir()` on a file (not a directory) results in the
532 * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX.
533 *
534 * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`.
535 * @since v10.0.0
536 * @return Fulfills with `undefined` upon success.
537 */
538 function rmdir(path: PathLike, options?: RmDirOptions): Promise<void>;
539 /**
540 * Removes files and directories (modeled on the standard POSIX `rm` utility).
541 * @since v14.14.0
542 * @return Fulfills with `undefined` upon success.
543 */
544 function rm(path: PathLike, options?: RmOptions): Promise<void>;
545 /**
546 * Asynchronously creates a directory.
547 *
548 * The optional `options` argument can be an integer specifying `mode` (permission
549 * 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 directory
550 * that exists results in a
551 * rejection only when `recursive` is false.
552 * @since v10.0.0
553 * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`.
554 */
555 function mkdir(
556 path: PathLike,
557 options: MakeDirectoryOptions & {
558 recursive: true;
559 }
560 ): Promise<string | undefined>;
561 /**
562 * Asynchronous mkdir(2) - create a directory.
563 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
564 * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
565 * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
566 */
567 function mkdir(
568 path: PathLike,
569 options?:
570 | Mode
571 | (MakeDirectoryOptions & {
572 recursive?: false | undefined;
573 })
574 | null
575 ): Promise<void>;
576 /**
577 * Asynchronous mkdir(2) - create a directory.
578 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
579 * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
580 * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
581 */
582 function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise<string | undefined>;
583 /**
584 * Reads the contents of a directory.
585 *
586 * The optional `options` argument can be a string specifying an encoding, or an
587 * object with an `encoding` property specifying the character encoding to use for
588 * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned
589 * will be passed as `Buffer` objects.
590 *
591 * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects.
592 *
593 * ```js
594 * import { readdir } from 'fs/promises';
595 *
596 * try {
597 * const files = await readdir(path);
598 * for (const file of files)
599 * console.log(file);
600 * } catch (err) {
601 * console.error(err);
602 * }
603 * ```
604 * @since v10.0.0
605 * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`.
606 */
607 function readdir(
608 path: PathLike,
609 options?:
610 | (ObjectEncodingOptions & {
611 withFileTypes?: false | undefined;
612 })
613 | BufferEncoding
614 | null
615 ): Promise<string[]>;
616 /**
617 * Asynchronous readdir(3) - read a directory.
618 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
619 * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
620 */
621 function readdir(
622 path: PathLike,
623 options:
624 | {
625 encoding: 'buffer';
626 withFileTypes?: false | undefined;
627 }
628 | 'buffer'
629 ): Promise<Buffer[]>;
630 /**
631 * Asynchronous readdir(3) - read a directory.
632 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
633 * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
634 */
635 function readdir(
636 path: PathLike,
637 options?:
638 | (ObjectEncodingOptions & {
639 withFileTypes?: false | undefined;
640 })
641 | BufferEncoding
642 | null
643 ): Promise<string[] | Buffer[]>;
644 /**
645 * Asynchronous readdir(3) - read a directory.
646 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
647 * @param options If called with `withFileTypes: true` the result data will be an array of Dirent.
648 */
649 function readdir(
650 path: PathLike,
651 options: ObjectEncodingOptions & {
652 withFileTypes: true;
653 }
654 ): Promise<Dirent[]>;
655 /**
656 * 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 is
657 * resolved with the`linkString` upon success.
658 *
659 * The optional `options` argument can be a string specifying an encoding, or an
660 * object with an `encoding` property specifying the character encoding to use for
661 * the link path returned. If the `encoding` is set to `'buffer'`, the link path
662 * returned will be passed as a `Buffer` object.
663 * @since v10.0.0
664 * @return Fulfills with the `linkString` upon success.
665 */
666 function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string>;
667 /**
668 * Asynchronous readlink(2) - read value of a symbolic link.
669 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
670 * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
671 */
672 function readlink(path: PathLike, options: BufferEncodingOption): Promise<Buffer>;
673 /**
674 * Asynchronous readlink(2) - read value of a symbolic link.
675 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
676 * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
677 */
678 function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise<string | Buffer>;
679 /**
680 * Creates a symbolic link.
681 *
682 * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path
683 * to be absolute. When using `'junction'`, the `target` argument will
684 * automatically be normalized to absolute path.
685 * @since v10.0.0
686 * @param [type='file']
687 * @return Fulfills with `undefined` upon success.
688 */
689 function symlink(target: PathLike, path: PathLike, type?: string | null): Promise<void>;
690 /**
691 * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link,
692 * in which case the link itself is stat-ed, not the file that it refers to.
693 * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail.
694 * @since v10.0.0
695 * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`.
696 */
697 function lstat(
698 path: PathLike,
699 opts?: StatOptions & {
700 bigint?: false | undefined;
701 }
702 ): Promise<Stats>;
703 function lstat(
704 path: PathLike,
705 opts: StatOptions & {
706 bigint: true;
707 }
708 ): Promise<BigIntStats>;
709 function lstat(path: PathLike, opts?: StatOptions): Promise<Stats | BigIntStats>;
710 /**
711 * @since v10.0.0
712 * @return Fulfills with the {fs.Stats} object for the given `path`.
713 */
714 function stat(
715 path: PathLike,
716 opts?: StatOptions & {
717 bigint?: false | undefined;
718 }
719 ): Promise<Stats>;
720 function stat(
721 path: PathLike,
722 opts: StatOptions & {
723 bigint: true;
724 }
725 ): Promise<BigIntStats>;
726 function stat(path: PathLike, opts?: StatOptions): Promise<Stats | BigIntStats>;
727 /**
728 * 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.
729 * @since v10.0.0
730 * @return Fulfills with `undefined` upon success.
731 */
732 function link(existingPath: PathLike, newPath: PathLike): Promise<void>;
733 /**
734 * If `path` refers to a symbolic link, then the link is removed without affecting
735 * the file or directory to which that link refers. If the `path` refers to a file
736 * 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.
737 * @since v10.0.0
738 * @return Fulfills with `undefined` upon success.
739 */
740 function unlink(path: PathLike): Promise<void>;
741 /**
742 * Changes the permissions of a file.
743 * @since v10.0.0
744 * @return Fulfills with `undefined` upon success.
745 */
746 function chmod(path: PathLike, mode: Mode): Promise<void>;
747 /**
748 * Changes the permissions on a symbolic link.
749 *
750 * This method is only implemented on macOS.
751 * @deprecated Since v10.0.0
752 * @return Fulfills with `undefined` upon success.
753 */
754 function lchmod(path: PathLike, mode: Mode): Promise<void>;
755 /**
756 * Changes the ownership on a symbolic link.
757 * @since v10.0.0
758 * @return Fulfills with `undefined` upon success.
759 */
760 function lchown(path: PathLike, uid: number, gid: number): Promise<void>;
761 /**
762 * 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
763 * symbolic link, then the link is not dereferenced: instead, the timestamps of
764 * the symbolic link itself are changed.
765 * @since v14.5.0, v12.19.0
766 * @return Fulfills with `undefined` upon success.
767 */
768 function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise<void>;
769 /**
770 * Changes the ownership of a file.
771 * @since v10.0.0
772 * @return Fulfills with `undefined` upon success.
773 */
774 function chown(path: PathLike, uid: number, gid: number): Promise<void>;
775 /**
776 * Change the file system timestamps of the object referenced by `path`.
777 *
778 * The `atime` and `mtime` arguments follow these rules:
779 *
780 * * Values can be either numbers representing Unix epoch time, `Date`s, or a
781 * numeric string like `'123456789.0'`.
782 * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown.
783 * @since v10.0.0
784 * @return Fulfills with `undefined` upon success.
785 */
786 function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise<void>;
787 /**
788 * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function.
789 *
790 * Only paths that can be converted to UTF8 strings are supported.
791 *
792 * The optional `options` argument can be a string specifying an encoding, or an
793 * object with an `encoding` property specifying the character encoding to use for
794 * the path. If the `encoding` is set to `'buffer'`, the path returned will be
795 * passed as a `Buffer` object.
796 *
797 * On Linux, when Node.js is linked against musl libc, the procfs file system must
798 * be mounted on `/proc` in order for this function to work. Glibc does not have
799 * this restriction.
800 * @since v10.0.0
801 * @return Fulfills with the resolved path upon success.
802 */
803 function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string>;
804 /**
805 * Asynchronous realpath(3) - return the canonicalized absolute pathname.
806 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
807 * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
808 */
809 function realpath(path: PathLike, options: BufferEncodingOption): Promise<Buffer>;
810 /**
811 * Asynchronous realpath(3) - return the canonicalized absolute pathname.
812 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
813 * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
814 */
815 function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string | Buffer>;
816 /**
817 * Creates a unique temporary directory. A unique directory name is generated by
818 * appending six random characters to the end of the provided `prefix`. Due to
819 * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some
820 * platforms, notably the BSDs, can return more than six random characters, and
821 * replace trailing `X` characters in `prefix` with random characters.
822 *
823 * The optional `options` argument can be a string specifying an encoding, or an
824 * object with an `encoding` property specifying the character encoding to use.
825 *
826 * ```js
827 * import { mkdtemp } from 'fs/promises';
828 *
829 * try {
830 * await mkdtemp(path.join(os.tmpdir(), 'foo-'));
831 * } catch (err) {
832 * console.error(err);
833 * }
834 * ```
835 *
836 * The `fsPromises.mkdtemp()` method will append the six randomly selected
837 * 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
838 * platform-specific path separator
839 * (`require('path').sep`).
840 * @since v10.0.0
841 * @return Fulfills with a string containing the filesystem path of the newly created temporary directory.
842 */
843 function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string>;
844 /**
845 * Asynchronously creates a unique temporary directory.
846 * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory.
847 * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
848 */
849 function mkdtemp(prefix: string, options: BufferEncodingOption): Promise<Buffer>;
850 /**
851 * Asynchronously creates a unique temporary directory.
852 * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory.
853 * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
854 */
855 function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string | Buffer>;
856 /**
857 * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a `Buffer`, or, an object with an own (not inherited)`toString` function property.
858 *
859 * The `encoding` option is ignored if `data` is a buffer.
860 *
861 * If `options` is a string, then it specifies the encoding.
862 *
863 * The `mode` option only affects the newly created file. See `fs.open()` for more details.
864 *
865 * Any specified `FileHandle` has to support writing.
866 *
867 * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file
868 * without waiting for the promise to be settled.
869 *
870 * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience
871 * method that performs multiple `write` calls internally to write the buffer
872 * passed to it. For performance sensitive code consider using `fs.createWriteStream()`.
873 *
874 * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`.
875 * Cancelation is "best effort", and some amount of data is likely still
876 * to be written.
877 *
878 * ```js
879 * import { writeFile } from 'fs/promises';
880 * import { Buffer } from 'buffer';
881 *
882 * try {
883 * const controller = new AbortController();
884 * const { signal } = controller;
885 * const data = new Uint8Array(Buffer.from('Hello Node.js'));
886 * const promise = writeFile('message.txt', data, { signal });
887 *
888 * // Abort the request before the promise settles.
889 * controller.abort();
890 *
891 * await promise;
892 * } catch (err) {
893 * // When a request is aborted - err is an AbortError
894 * console.error(err);
895 * }
896 * ```
897 *
898 * Aborting an ongoing request does not abort individual operating
899 * system requests but rather the internal buffering `fs.writeFile` performs.
900 * @since v10.0.0
901 * @param file filename or `FileHandle`
902 * @return Fulfills with `undefined` upon success.
903 */
904 function writeFile(
905 file: PathLike | FileHandle,
906 data: string | NodeJS.ArrayBufferView | Iterable<string | NodeJS.ArrayBufferView> | AsyncIterable<string | NodeJS.ArrayBufferView> | Stream,
907 options?:
908 | (ObjectEncodingOptions & {
909 mode?: Mode | undefined;
910 flag?: OpenMode | undefined;
911 } & Abortable)
912 | BufferEncoding
913 | null
914 ): Promise<void>;
915 /**
916 * Asynchronously append data to a file, creating the file if it does not yet
917 * exist. `data` can be a string or a `Buffer`.
918 *
919 * If `options` is a string, then it specifies the `encoding`.
920 *
921 * The `mode` option only affects the newly created file. See `fs.open()` for more details.
922 *
923 * The `path` may be specified as a `FileHandle` that has been opened
924 * for appending (using `fsPromises.open()`).
925 * @since v10.0.0
926 * @param path filename or {FileHandle}
927 * @return Fulfills with `undefined` upon success.
928 */
929 function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise<void>;
930 /**
931 * Asynchronously reads the entire contents of a file.
932 *
933 * If no encoding is specified (using `options.encoding`), the data is returned
934 * as a `Buffer` object. Otherwise, the data will be a string.
935 *
936 * If `options` is a string, then it specifies the encoding.
937 *
938 * When the `path` is a directory, the behavior of `fsPromises.readFile()` is
939 * platform-specific. On macOS, Linux, and Windows, the promise will be rejected
940 * with an error. On FreeBSD, a representation of the directory's contents will be
941 * returned.
942 *
943 * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a
944 * request is aborted the promise returned is rejected with an `AbortError`:
945 *
946 * ```js
947 * import { readFile } from 'fs/promises';
948 *
949 * try {
950 * const controller = new AbortController();
951 * const { signal } = controller;
952 * const promise = readFile(fileName, { signal });
953 *
954 * // Abort the request before the promise settles.
955 * controller.abort();
956 *
957 * await promise;
958 * } catch (err) {
959 * // When a request is aborted - err is an AbortError
960 * console.error(err);
961 * }
962 * ```
963 *
964 * Aborting an ongoing request does not abort individual operating
965 * system requests but rather the internal buffering `fs.readFile` performs.
966 *
967 * Any specified `FileHandle` has to support reading.
968 * @since v10.0.0
969 * @param path filename or `FileHandle`
970 * @return Fulfills with the contents of the file.
971 */
972 function readFile(
973 path: PathLike | FileHandle,
974 options?:
975 | ({
976 encoding?: null | undefined;
977 flag?: OpenMode | undefined;
978 } & Abortable)
979 | null
980 ): Promise<Buffer>;
981 /**
982 * Asynchronously reads the entire contents of a file.
983 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
984 * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically.
985 * @param options An object that may contain an optional flag.
986 * If a flag is not provided, it defaults to `'r'`.
987 */
988 function readFile(
989 path: PathLike | FileHandle,
990 options:
991 | ({
992 encoding: BufferEncoding;
993 flag?: OpenMode | undefined;
994 } & Abortable)
995 | BufferEncoding
996 ): Promise<string>;
997 /**
998 * Asynchronously reads the entire contents of a file.
999 * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
1000 * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically.
1001 * @param options An object that may contain an optional flag.
1002 * If a flag is not provided, it defaults to `'r'`.
1003 */
1004 function readFile(
1005 path: PathLike | FileHandle,
1006 options?:
1007 | (ObjectEncodingOptions &
1008 Abortable & {
1009 flag?: OpenMode | undefined;
1010 })
1011 | BufferEncoding
1012 | null
1013 ): Promise<string | Buffer>;
1014 /**
1015 * 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.
1016 *
1017 * Creates an `fs.Dir`, which contains all further functions for reading from
1018 * and cleaning up the directory.
1019 *
1020 * The `encoding` option sets the encoding for the `path` while opening the
1021 * directory and subsequent read operations.
1022 *
1023 * Example using async iteration:
1024 *
1025 * ```js
1026 * import { opendir } from 'fs/promises';
1027 *
1028 * try {
1029 * const dir = await opendir('./');
1030 * for await (const dirent of dir)
1031 * console.log(dirent.name);
1032 * } catch (err) {
1033 * console.error(err);
1034 * }
1035 * ```
1036 *
1037 * When using the async iterator, the `fs.Dir` object will be automatically
1038 * closed after the iterator exits.
1039 * @since v12.12.0
1040 * @return Fulfills with an {fs.Dir}.
1041 */
1042 function opendir(path: PathLike, options?: OpenDirOptions): Promise<Dir>;
1043 /**
1044 * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory.
1045 *
1046 * ```js
1047 * const { watch } = require('fs/promises');
1048 *
1049 * const ac = new AbortController();
1050 * const { signal } = ac;
1051 * setTimeout(() => ac.abort(), 10000);
1052 *
1053 * (async () => {
1054 * try {
1055 * const watcher = watch(__filename, { signal });
1056 * for await (const event of watcher)
1057 * console.log(event);
1058 * } catch (err) {
1059 * if (err.name === 'AbortError')
1060 * return;
1061 * throw err;
1062 * }
1063 * })();
1064 * ```
1065 *
1066 * On most platforms, `'rename'` is emitted whenever a filename appears or
1067 * disappears in the directory.
1068 *
1069 * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`.
1070 * @since v15.9.0, v14.18.0
1071 * @return of objects with the properties:
1072 */
1073 function watch(
1074 filename: PathLike,
1075 options:
1076 | (WatchOptions & {
1077 encoding: 'buffer';
1078 })
1079 | 'buffer'
1080 ): AsyncIterable<FileChangeInfo<Buffer>>;
1081 /**
1082 * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
1083 * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
1084 * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
1085 * If `encoding` is not supplied, the default of `'utf8'` is used.
1086 * If `persistent` is not supplied, the default of `true` is used.
1087 * If `recursive` is not supplied, the default of `false` is used.
1088 */
1089 function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable<FileChangeInfo<string>>;
1090 /**
1091 * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
1092 * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
1093 * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
1094 * If `encoding` is not supplied, the default of `'utf8'` is used.
1095 * If `persistent` is not supplied, the default of `true` is used.
1096 * If `recursive` is not supplied, the default of `false` is used.
1097 */
1098 function watch(filename: PathLike, options: WatchOptions | string): AsyncIterable<FileChangeInfo<string>> | AsyncIterable<FileChangeInfo<Buffer>>;
1099 /**
1100 * Asynchronously copies the entire directory structure from `src` to `dest`,
1101 * including subdirectories and files.
1102 *
1103 * When copying a directory to another directory, globs are not supported and
1104 * behavior is similar to `cp dir1/ dir2/`.
1105 * @since v16.7.0
1106 * @experimental
1107 * @param src source path to copy.
1108 * @param dest destination path to copy to.
1109 * @return Fulfills with `undefined` upon success.
1110 */
1111 function cp(source: string, destination: string, opts?: CopyOptions): Promise<void>;
1112}
1113declare module 'node:fs/promises' {
1114 export * from 'fs/promises';
1115}