UNPKG

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