FappendFile
Bun

function

fs.promises.appendFile

function appendFile(
data: string | Uint8Array<ArrayBufferLike>,
options?: null | BufferEncoding | ObjectEncodingOptions & FlagAndOpenMode & { flush: boolean }
): Promise<void>;

Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.

If options is a string, then it specifies the encoding.

The mode option only affects the newly created file. See fs.open() for more details.

The path may be specified as a FileHandle that has been opened for appending (using fsPromises.open()).

@param path

filename or {FileHandle}

@returns

Fulfills with undefined upon success.

Referenced types

type PathLike = string | Buffer | URL

Valid types for path values in "fs".

interface FileHandle

  • readonly fd: number

    The numeric file descriptor managed by the {FileHandle} object.

  • [Symbol.asyncDispose](): Promise<void>;

    Calls filehandle.close() and returns a promise that fulfills when the filehandle is closed.

  • data: string | Uint8Array<ArrayBufferLike>,
    options?: null | BufferEncoding | ObjectEncodingOptions & Abortable
    ): Promise<void>;

    Alias of filehandle.writeFile().

    When operating on file handles, the mode cannot be changed from what it was set to with fsPromises.open(). Therefore, this is equivalent to filehandle.writeFile().

    @returns

    Fulfills with undefined upon success.

  • mode: Mode
    ): Promise<void>;

    Modifies the permissions on the file. See chmod(2).

    @param mode

    the file mode bit mask.

    @returns

    Fulfills with undefined upon success.

  • uid: number,
    gid: number
    ): Promise<void>;

    Changes the ownership of the file. A wrapper for chown(2).

    @param uid

    The file's new owner's user id.

    @param gid

    The file's new group's group id.

    @returns

    Fulfills with undefined upon success.

  • close(): Promise<void>;

    Closes the file handle after waiting for any pending operation on the handle to complete.

    import { open } from 'node:fs/promises';
    
    let filehandle;
    try {
      filehandle = await open('thefile.txt', 'r');
    } finally {
      await filehandle?.close();
    }
    
    @returns

    Fulfills with undefined upon success.

  • Unlike the 16 KiB default highWaterMark for a stream.Readable, the stream returned by this method has a default highWaterMark of 64 KiB.

    options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start counting at 0, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. If start is omitted or undefined, filehandle.createReadStream() reads sequentially from the current file position. The encoding can be any one of those accepted by Buffer.

    If the FileHandle points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.

    By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.

    import { open } from 'node:fs/promises';
    
    const fd = await open('/dev/input/event0');
    // Create a stream from some character device.
    const stream = fd.createReadStream();
    setTimeout(() => {
      stream.close(); // This may not close the stream.
      // Artificially marking end-of-stream, as if the underlying resource had
      // indicated end-of-file by itself, allows the stream to close.
      // This does not cancel pending read operations, and if there is such an
      // operation, the process may still not be able to exit successfully
      // until it finishes.
      stream.push(null);
      stream.read(0);
    }, 100);
    

    If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on 'error' or 'end' the file descriptor will be closed automatically.

    An example to read the last 10 bytes of a file which is 100 bytes long:

    import { open } from 'node:fs/promises';
    
    const fd = await open('sample.txt');
    fd.createReadStream({ start: 90, end: 99 });
    
  • options may also include a start option to allow writing data at some position past the beginning of the file, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than replacing it may require the flags open option to be set to r+ rather than the default r. The encoding can be any one of those accepted by Buffer.

    If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.

    By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.

  • datasync(): Promise<void>;

    Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details.

    Unlike filehandle.sync this method does not flush modified metadata.

    @returns

    Fulfills with undefined upon success.

  • read<T extends ArrayBufferView<ArrayBufferLike>>(
    buffer: T,
    offset?: null | number,
    length?: null | number,
    position?: null | ReadPosition
    ): Promise<FileReadResult<T>>;

    Reads data from the file and stores that in the given buffer.

    If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.

    @param buffer

    A buffer that will be filled with the file data read.

    @param offset

    The location in the buffer at which to start filling.

    @param length

    The number of bytes to read.

    @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 integer, the current file position will remain unchanged.

    @returns

    Fulfills upon success with an object with two properties:

    read<T extends ArrayBufferView<ArrayBufferLike>>(
    buffer: T,
    options?: ReadOptions
    ): Promise<FileReadResult<T>>;
    read<T extends ArrayBufferView<ArrayBufferLike> = NonSharedBuffer>(
    ): Promise<FileReadResult<T>>;
  • Returns a byte-oriented ReadableStream that may be used to read the file's contents.

    An error will be thrown if this method is called more than once or is called after the FileHandle is closed or closing.

    import {
      open,
    } from 'node:fs/promises';
    
    const file = await open('./some/file/to/read');
    
    for await (const chunk of file.readableWebStream())
      console.log(chunk);
    
    await file.close();
    

    While the ReadableStream will read the file to completion, it will not close the FileHandle automatically. User code must still call thefileHandle.close() method.

  • options?: null | { encoding: null } & Abortable
    ): Promise<NonSharedBuffer>;

    Asynchronously reads the entire contents of a file.

    If options is a string, then it specifies the encoding.

    The FileHandle has to support reading.

    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 position till the end of the file. It doesn't always read from the beginning of the file.

    @returns

    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 data will be a string.

    options: BufferEncoding | { encoding: BufferEncoding } & Abortable
    ): Promise<string>;

    Asynchronously reads the entire contents of a file. The underlying file will not be closed automatically. The FileHandle must have been opened for reading.

    options?: null | BufferEncoding | ObjectEncodingOptions & Abortable
    ): Promise<string | NonSharedBuffer>;

    Asynchronously reads the entire contents of a file. The underlying file will not be closed automatically. The FileHandle must have been opened for reading.

  • Convenience method to create a readline interface and stream over the file. See filehandle.createReadStream() for the options.

    import { open } from 'node:fs/promises';
    
    const file = await open('./some/file/to/read');
    
    for await (const line of file.readLines()) {
      console.log(line);
    }
    
  • readv<TBuffers extends readonly ArrayBufferView<ArrayBufferLike>[]>(
    buffers: TBuffers,
    position?: number
    ): Promise<ReadVResult<TBuffers>>;
    @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.

    @returns

    Fulfills upon success an object containing two properties:

  • opts?: StatOptions & { bigint: false }
    ): Promise<Stats>;
    @returns

    Fulfills with an {fs.Stats} for the file.

    opts: StatOptions & { bigint: true }
    ): Promise<BigIntStats>;
    ): Promise<Stats | BigIntStats>;
  • sync(): Promise<void>;

    Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail.

    @returns

    Fulfills with undefined upon success.

  • len?: number
    ): Promise<void>;

    Truncates the file.

    If the file was larger than len bytes, only the first len bytes will be retained in the file.

    The following example retains only the first four bytes of the file:

    import { open } from 'node:fs/promises';
    
    let filehandle = null;
    try {
      filehandle = await open('temp.txt', 'r+');
      await filehandle.truncate(4);
    } finally {
      await filehandle?.close();
    }
    

    If the file previously was shorter than len bytes, it is extended, and the extended part is filled with null bytes ('\0'):

    If len is negative then 0 will be used.

    @returns

    Fulfills with undefined upon success.

  • atime: TimeLike,
    mtime: TimeLike
    ): Promise<void>;

    Change the file system timestamps of the object referenced by the FileHandle then fulfills the promise with no arguments upon success.

  • write<TBuffer extends ArrayBufferView<ArrayBufferLike>>(
    buffer: TBuffer,
    offset?: null | number,
    length?: null | number,
    position?: null | number
    ): Promise<{ buffer: TBuffer; bytesWritten: number }>;

    Write buffer to the file.

    The promise is fulfilled with an object containing two properties:

    It is unsafe to use filehandle.write() multiple times on the same file without waiting for the promise to be fulfilled (or rejected). For this scenario, use filehandle.createWriteStream().

    On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

    @param offset

    The start position from within buffer where the data to write begins.

    @param length

    The number of bytes from buffer to write.

    @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. See the POSIX pwrite(2) documentation for more detail.

    write<TBuffer extends Uint8Array<ArrayBufferLike>>(
    buffer: TBuffer,
    options?: { length: number; offset: number; position: number }
    ): Promise<{ buffer: TBuffer; bytesWritten: number }>;
    data: string,
    position?: null | number,
    encoding?: null | BufferEncoding
    ): Promise<{ buffer: string; bytesWritten: number }>;
  • data: string | Uint8Array<ArrayBufferLike>,
    options?: null | BufferEncoding | ObjectEncodingOptions & Abortable
    ): Promise<void>;

    Asynchronously writes data to a file, replacing the file if it already exists. data can be a string, a buffer, an AsyncIterable, or an Iterable object. The promise is fulfilled with no arguments upon success.

    If options is a string, then it specifies the encoding.

    The FileHandle has to support writing.

    It is unsafe to use filehandle.writeFile() multiple times on the same file without waiting for the promise to be fulfilled (or rejected).

    If one or more filehandle.write() calls are made on a file handle and then afilehandle.writeFile() call is made, the data will be written from the current position till the end of the file. It doesn't always write from the beginning of the file.

  • writev<TBuffers extends readonly ArrayBufferView<ArrayBufferLike>[]>(
    buffers: TBuffers,
    position?: number
    ): Promise<WriteVResult<TBuffers>>;

    Write an array of ArrayBufferView s to the file.

    The promise is fulfilled with an object containing a two properties:

    It is unsafe to call writev() multiple times on the same file without waiting for the promise to be fulfilled (or rejected).

    On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

    @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 position.

class Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

  • readonly [Symbol.toStringTag]: 'Uint8Array'
  • readonly buffer: TArrayBuffer

    The ArrayBuffer instance referenced by the array.

  • readonly byteLength: number

    The length in bytes of the array.

  • readonly byteOffset: number

    The offset in bytes of the array.

  • readonly BYTES_PER_ELEMENT: number

    The size in bytes of each element in the array.

  • readonly length: number

    The length of the array.

  • [Symbol.iterator](): ArrayIterator<number>;
  • index: number
    ): undefined | number;

    Returns the item located at the specified index.

    @param index

    The zero-based index of the desired code unit. A negative index will count back from the last item.

  • target: number,
    start: number,
    end?: number
    ): this;

    Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

    @param target

    If target is negative, it is treated as length+target where length is the length of the array.

    @param start

    If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.

    @param end

    If not specified, length of the this object is used as its default value.

  • entries(): ArrayIterator<[number, number]>;

    Returns an array of key, value pairs for every entry in the array

  • predicate: (value: number, index: number, array: this) => unknown,
    thisArg?: any
    ): boolean;

    Determines whether all the members of an array satisfy the specified test.

    @param predicate

    A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.

    @param thisArg

    An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

  • value: number,
    start?: number,
    end?: number
    ): this;

    Changes all array elements from start to end index to a static value and returns the modified array

    @param value

    value to fill array section with

    @param start

    index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.

    @param end

    index to stop filling the array at. If end is negative, it is treated as length+end.

  • predicate: (value: number, index: number, array: this) => any,
    thisArg?: any

    Returns the elements of an array that meet the condition specified in a callback function.

    @param predicate

    A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.

    @param thisArg

    An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

  • predicate: (value: number, index: number, obj: this) => boolean,
    thisArg?: any
    ): undefined | number;

    Returns the value of the first element in the array where predicate is true, and undefined otherwise.

    @param predicate

    find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.

    @param thisArg

    If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

  • predicate: (value: number, index: number, obj: this) => boolean,
    thisArg?: any
    ): number;

    Returns the index of the first element in the array where predicate is true, and -1 otherwise.

    @param predicate

    find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.

    @param thisArg

    If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

  • findLast<S extends number>(
    predicate: (value: number, index: number, array: this) => value is S,
    thisArg?: any
    ): undefined | S;

    Returns the value of the last element in the array where predicate is true, and undefined otherwise.

    @param predicate

    findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.

    @param thisArg

    If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

    predicate: (value: number, index: number, array: this) => unknown,
    thisArg?: any
    ): undefined | number;
  • predicate: (value: number, index: number, array: this) => unknown,
    thisArg?: any
    ): number;

    Returns the index of the last element in the array where predicate is true, and -1 otherwise.

    @param predicate

    findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.

    @param thisArg

    If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

  • callbackfn: (value: number, index: number, array: this) => void,
    thisArg?: any
    ): void;

    Performs the specified action for each element in an array.

    @param callbackfn

    A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.

    @param thisArg

    An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

  • searchElement: number,
    fromIndex?: number
    ): boolean;

    Determines whether an array includes a certain element, returning true or false as appropriate.

    @param searchElement

    The element to search for.

    @param fromIndex

    The position in this array at which to begin searching for searchElement.

  • searchElement: number,
    fromIndex?: number
    ): number;

    Returns the index of the first occurrence of a value in an array.

    @param searchElement

    The value to locate in the array.

    @param fromIndex

    The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

  • separator?: string
    ): string;

    Adds all the elements of an array separated by the specified separator string.

    @param separator

    A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.

  • keys(): ArrayIterator<number>;

    Returns an list of keys in the array

  • searchElement: number,
    fromIndex?: number
    ): number;

    Returns the index of the last occurrence of a value in an array.

    @param searchElement

    The value to locate in the array.

    @param fromIndex

    The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

  • callbackfn: (value: number, index: number, array: this) => number,
    thisArg?: any

    Calls a defined callback function on each element of an array, and returns an array that contains the results.

    @param callbackfn

    A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

    @param thisArg

    An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

  • callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number
    ): number;

    Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

    @param callbackfn

    A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.

    callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,
    initialValue: number
    ): number;
    reduce<U>(
    callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U,
    initialValue: U
    ): U;

    Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

    @param callbackfn

    A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.

    @param initialValue

    If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

  • callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number
    ): number;

    Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

    @param callbackfn

    A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.

    callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,
    initialValue: number
    ): number;
    callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U,
    initialValue: U
    ): U;

    Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

    @param callbackfn

    A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.

    @param initialValue

    If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

  • reverse(): this;

    Reverses the elements in an Array.

  • array: ArrayLike<number>,
    offset?: number
    ): void;

    Sets a value or an array of values.

    @param array

    A typed or untyped array of values to set.

    @param offset

    The index in the current array at which the values are to be written.

  • base64: string,
    offset?: number
    ): { read: number; written: number };

    Set the contents of the Uint8Array from a base64 encoded string

    @param base64

    The base64 encoded string to decode into the array

    @param offset

    Optional starting index to begin setting the decoded bytes (default: 0)

  • hex: string
    ): { read: number; written: number };

    Set the contents of the Uint8Array from a hex encoded string

    @param hex

    The hex encoded string to decode into the array. The string must have an even number of characters, be valid hexadecimal characters and contain no whitespace.

  • start?: number,
    end?: number

    Returns a section of an array.

    @param start

    The beginning of the specified portion of the array.

    @param end

    The end of the specified portion of the array. This is exclusive of the element at the index 'end'.

  • predicate: (value: number, index: number, array: this) => unknown,
    thisArg?: any
    ): boolean;

    Determines whether the specified callback function returns true for any element of an array.

    @param predicate

    A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.

    @param thisArg

    An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

  • compareFn?: (a: number, b: number) => number
    ): this;

    Sorts an array.

    @param compareFn

    Function used to determine the order of the elements. It is expected to return a negative value if first argument is less than second argument, zero if they're equal and a positive value otherwise. If omitted, the elements are sorted in ascending order.

    [11,2,22,1].sort((a, b) => a - b)
    
  • begin?: number,
    end?: number
    ): Uint8Array<TArrayBuffer>;

    Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements at begin, inclusive, up to end, exclusive.

    @param begin

    The index of the beginning of the array.

    @param end

    The index of the end of the array.

  • options?: { alphabet: 'base64' | 'base64url'; omitPadding: boolean }
    ): string;

    Convert the Uint8Array to a base64 encoded string

    @returns

    The base64 encoded string representation of the Uint8Array

  • toHex(): string;

    Convert the Uint8Array to a hex encoded string

    @returns

    The hex encoded string representation of the Uint8Array

  • toLocaleString(): string;

    Converts a number to a string by using the current locale.

    locales: string | string[],
    options?: NumberFormatOptions
    ): string;
  • Copies the array and returns the copy with the elements in reverse order.

  • compareFn?: (a: number, b: number) => number

    Copies and sorts the array.

    @param compareFn

    Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending order.

    const myNums = Uint8Array.from([11, 2, 22, 1]);
    myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]
    
  • toString(): string;

    Returns a string representation of an array.

  • valueOf(): this;

    Returns the primitive value of the specified object.

  • values(): ArrayIterator<number>;

    Returns an list of values in the array

  • index: number,
    value: number

    Copies the array and inserts the given number at the provided index.

    @param index

    The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.

    @param value

    The value to insert into the copied array.

    @returns

    A copy of the original array with the inserted value.

interface ObjectEncodingOptions