type
quic.StreamBody
Referenced types
class Blob
A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
Returns a promise that resolves to the contents of the blob as an ArrayBuffer
Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes) its the same as
new Uint8Array(await blob.arrayBuffer())Read the data from the blob as a FormData object.
This first decodes the data from UTF-8, then parses it as a
multipart/form-databody or aapplication/x-www-form-urlencodedbody.The
typeproperty of the blob is used to determine the format of the body.This is a non-standard addition to the
BlobAPI, to make it conform more closely to theBodyMixinAPI.Wrap this blob in a Bun.Image pipeline. Equivalent to
new Bun.Image(this, options)— the constructor is synchronous (the underlying read happens lazily when an Image terminal is awaited), so this works onBun.file(),Bun.s3(), fd-backed and in-memory blobs alike:await Bun.file("photo.jpg").image().resize(400).webp().write("thumb.webp");Read the data from the blob as a JSON object.
This first decodes the data from UTF-8, then parses it as JSON.
Returns a readable stream of the blob's contents
Returns a promise that resolves to the contents of the blob as a string
interface FileHandle
Calls
filehandle.close()and returns a promise that fulfills when the filehandle is closed.- data: string | ArrayBufferView<ArrayBufferLike> | Iterable<unknown, any, any> | AsyncIterable<unknown, any, any>,): 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 tofilehandle.writeFile().@returnsFulfills with
undefinedupon success. 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(); }@returnsFulfills with
undefinedupon success.Unlike the 16 KiB default
highWaterMarkfor astream.Readable, the stream returned by this method has a defaulthighWaterMarkof 64 KiB.optionscan includestartandendvalues to read a range of bytes from the file instead of the entire file. Bothstartandendare inclusive and start counting at 0, allowed values are in the [0,Number.MAX_SAFE_INTEGER] range. Ifstartis omitted orundefined,filehandle.createReadStream()reads sequentially from the current file position. Theencodingcan be any one of those accepted byBuffer.If the
FileHandlepoints 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 theemitCloseoption tofalseto 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
autoCloseis 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. IfautoCloseis 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 });optionsmay also include astartoption 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 theflagsopenoption to be set tor+rather than the defaultr. Theencodingcan be any one of those accepted byBuffer.If
autoCloseis set to true (default behavior) on'error'or'finish'the file descriptor will be closed automatically. IfautoCloseis 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 theemitCloseoption tofalseto change this behavior.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.syncthis method does not flush modified metadata.@returnsFulfills with
undefinedupon success.- pull(
Return the file contents as an async iterable using the
node:stream/iterpull model. Reads are performed inchunkSize-byte chunks (default 128 KB). If transforms are provided, they are applied viastream/iter pull().The file handle is locked while the iterable is being consumed and unlocked when iteration completes, an error occurs, or the consumer breaks.
This function is only available when the
--experimental-stream-iterflag is enabled.import { open } from 'node:fs/promises'; import { text } from 'node:stream/iter'; import { compressGzip } from 'node:zlib/iter'; const fh = await open('input.txt', 'r'); // Read as text console.log(await text(fh.pull({ autoClose: true }))); // Read 1 KB starting at byte 100 const fh2 = await open('input.txt', 'r'); console.log(await text(fh2.pull({ start: 100, limit: 1024, autoClose: true }))); // Read with compression const fh3 = await open('input.txt', 'r'); const compressed = fh3.pull(compressGzip(), { autoClose: true }); - buffer: T,offset?: null | number,length?: null | number,
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 bufferA buffer that will be filled with the file data read.
@param offsetThe location in the buffer at which to start filling.
@param lengthThe number of bytes to read.
@param positionThe 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. Ifpositionis an integer, the current file position will remain unchanged.@returnsFulfills upon success with an object with two properties:
buffer: T, - ): ReadableStream;
Returns a byte-oriented
ReadableStreamthat 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
FileHandleis 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
ReadableStreamwill read the file to completion, it will not close theFileHandleautomatically. User code must still call thefileHandle.close()method. - ): Promise<NonSharedBuffer>;
Asynchronously reads the entire contents of a file.
If
optionsis a string, then it specifies theencoding.The
FileHandlehas to support reading.If one or more
filehandle.read()calls are made on a file handle and then afilehandle.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.@returnsFulfills 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.): Promise<string | NonSharedBuffer>;Asynchronously reads the entire contents of a file. The underlying file will not be closed automatically. The
FileHandlemust have been opened for reading. Convenience method to create a
readlineinterface and stream over the file. Seefilehandle.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); }- @param position
The offset from the beginning of the file where the data should be read from. If
positionis not anumber, the data will be read from the current position.@returnsFulfills upon success an object containing two properties:
- @returns
Fulfills with an {fs.Stats} for the file.
- len?: number): Promise<void>;
Truncates the file.
If the file was larger than
lenbytes, only the firstlenbytes 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
lenbytes, it is extended, and the extended part is filled with null bytes ('\0'):If
lenis negative then0will be used.@returnsFulfills with
undefinedupon success. - buffer: TBuffer,offset?: null | number,length?: null | number,position?: null | number): Promise<{ buffer: TBuffer; bytesWritten: number }>;
Write
bufferto 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, usefilehandle.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 offsetThe start position from within
bufferwhere the data to write begins.@param lengthThe number of bytes from
bufferto write.@param positionThe offset from the beginning of the file where the data from
buffershould be written. Ifpositionis not anumber, the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail.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 | ArrayBufferView<ArrayBufferLike> | Iterable<unknown, any, any> | AsyncIterable<unknown, any, any>,): Promise<void>;
Asynchronously writes data to a file, replacing the file if it already exists.
datacan be a string, a buffer, an AsyncIterable, or an Iterable object. The promise is fulfilled with no arguments upon success.If
optionsis a string, then it specifies theencoding.The
FileHandlehas 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. Return a
node:stream/iterwriter backed by this file handle.The writer supports both
Symbol.asyncDisposeandSymbol.dispose:await using w = fh.writer()— if the writer is still open (noend()called),asyncDisposecallsfail(). Ifend()is pending, it waits for it to complete.using w = fh.writer()— callsfail()unconditionally.
The
writeSync()andwritevSync()methods enable the try-sync fast path used bystream/iter pipeTo(). When the reader's chunk size matches the writer'schunkSize, all writes in apipeTo()pipeline complete synchronously with zero promise overhead.This function is only available when the
--experimental-stream-iterflag is enabled.import { open } from 'node:fs/promises'; import { from, pipeTo } from 'node:stream/iter'; import { compressGzip } from 'node:zlib/iter'; // Async pipeline const fh = await open('output.gz', 'w'); await pipeTo(from('Hello!'), compressGzip(), fh.writer({ autoClose: true })); // Sync pipeline with limit const src = await open('input.txt', 'r'); const dst = await open('output.txt', 'w'); const w = dst.writer({ limit: 1024 * 1024 }); // Max 1 MB await pipeTo(src.pull({ autoClose: true }), w); await w.end(); await dst.close();- buffers: TBuffers,position?: number
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 positionThe offset from the beginning of the file where the data from
buffersshould be written. Ifpositionis not anumber, 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.
- @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 targetIf target is negative, it is treated as length+target where length is the length of the array.
@param startIf start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
@param endIf not specified, length of the this object is used as its default value.
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 predicateA 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 thisArgAn object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
- fill(value: number,start?: number,end?: number): this;
Changes all array elements from
starttoendindex to a staticvalueand returns the modified array@param valuevalue to fill array section with
@param startindex 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 endindex 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 predicateA function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
@param thisArgAn object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
- find(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 predicatefind 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 thisArgIf 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 predicatefind 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 thisArgIf 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) => 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 predicatefindLast 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 thisArgIf 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 predicatefindLastIndex 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 thisArgIf 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 callbackfnA function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
@param thisArgAn 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 searchElementThe element to search for.
@param fromIndexThe 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 searchElementThe value to locate in the array.
@param fromIndexThe array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
- join(separator?: string): string;
Adds all the elements of an array separated by the specified separator string.
@param separatorA 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.
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 searchElementThe value to locate in the array.
@param fromIndexThe array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
- map(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 callbackfnA function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param thisArgAn 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 callbackfnA 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;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 callbackfnA function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
@param initialValueIf 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 callbackfnA 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 callbackfnA function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
@param initialValueIf 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.
Reverses the elements in an Array.
- @param array
A typed or untyped array of values to set.
@param offsetThe 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 base64The base64 encoded string to decode into the array
@param offsetOptional 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 hexThe 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.
- @param start
The beginning of the specified portion of the array.
@param endThe end of the specified portion of the array. This is exclusive of the element at the index 'end'.
- some(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 predicateA 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 thisArgAn object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
- @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
Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements at begin, inclusive, up to end, exclusive.
@param beginThe index of the beginning of the array.
@param endThe index of the end of the array.
- options?: { alphabet: 'base64' | 'base64url'; omitPadding: boolean }): string;
Convert the Uint8Array to a base64 encoded string
@returnsThe base64 encoded string representation of the Uint8Array
Convert the Uint8Array to a hex encoded string
@returnsThe hex encoded string representation of the Uint8Array
Converts a number to a string by using the current locale.
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 compareFnFunction 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] Returns a string representation of an array.
Returns the primitive value of the specified object.
Returns an list of values in the array
- with(index: number,value: number
Copies the array and inserts the given number at the provided index.
@param indexThe index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
@param valueThe value to insert into the copied array.
@returnsA copy of the original array with the inserted value.