FileStreams
FileStreams handle binary data in Jazz applications - think documents, audio files, and other non-text content. They're essentially collaborative versions of Blobs that sync automatically across devices.
Use FileStreams when you need to:
- Distribute documents across devices
- Store audio or video files
- Sync any binary data between users
Note: For images specifically, Jazz provides the higher-level ImageDefinition abstraction which manages multiple image resolutions - see the ImageDefinition documentation for details.
FileStreams provide automatic chunking when using the createFromBlob method, track upload progress, and handle MIME types and metadata.
In your schema, reference FileStreams like any other CoValue:
// schema.ts import {import coco,import zz } from "jazz-tools"; constDocument =const Document: co.Map<{ title: z.z.ZodString; file: co.FileStream; }, unknown, Account | Group>import coco.map({map<{ title: z.z.ZodString; file: co.FileStream; }>(shape: { title: z.z.ZodString; file: co.FileStream; }): co.Map<{ title: z.z.ZodString; file: co.FileStream; }, unknown, Account | Group> export maptitle: z.z.ZodStringtitle:import zz.string(),function string(params?: string | z.z.core.$ZodStringParams): z.z.ZodString (+1 overload) export stringfile: co.FileStreamfile:import coco.fileStream(), // Store a document file });function fileStream(): co.FileStream export fileStream
Creating FileStreams
There are two main ways to create FileStreams: creating empty ones for manual data population or creating directly from existing files or blobs.
Creating from Blobs and Files
For files from input elements or drag-and-drop interfaces, use createFromBlob:
// From a file input constconst fileInput: HTMLInputElementfileInput =var document: Document[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)document.ParentNode.querySelector<HTMLInputElement>(selectors: string): HTMLInputElement | null (+4 overloads)Returns the first element that is a descendant of node that matches selectors. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/querySelector)querySelector('input[type="file"]') as HTMLInputElement;const fileInput: HTMLInputElementfileInput.HTMLInputElement.addEventListener<"change">(type: "change", listener: (this: HTMLInputElement, ev: Event) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)addEventListener('change', async () => { constconst file: File | undefinedfile =const fileInput: HTMLInputElementfileInput.HTMLInputElement.files: FileList | nullReturns a FileList object on a file type input object. [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/files)files?.[0]; if (!const file: File | undefinedfile) return; // Create FileStream from user-selected file constconst fileStream: FileStreamfileStream = awaitimport coco.fileStream().function fileStream(): co.FileStream export fileStreamcreateFromBlob(FileStreamSchema.createFromBlob(blob: Blob | File, options?: { owner?: Group; onProgress?: (progress: number) => void; } | Group): Promise<FileStream> (+1 overload)const file: Filefile, {owner?: Group | undefinedowner:const myGroup: GroupmyGroup }); // Or with progress tracking for better UX constconst fileWithProgress: FileStreamfileWithProgress = awaitimport coco.fileStream().function fileStream(): co.FileStream export fileStreamcreateFromBlob(FileStreamSchema.createFromBlob(blob: Blob | File, options?: { owner?: Group; onProgress?: (progress: number) => void; } | Group): Promise<FileStream> (+1 overload)const file: Filefile, {onProgress?: ((progress: number) => void) | undefinedonProgress: (progress: numberprogress) => { // progress is a value between 0 and 1 constconst percent: numberpercent =var Math: MathAn intrinsic object that provides basic mathematics functionality and constants.Math.Math.round(x: number): numberReturns a supplied numeric expression rounded to the nearest integer.round(progress: numberprogress * 100);var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Upload progress: ${const percent: numberpercent}%`);const progressBar: HTMLElementprogressBar.ElementCSSInlineStyle.style: CSSStyleDeclaration[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/style)style.CSSStyleDeclaration.width: string[MDN Reference](https://developer.mozilla.org/docs/Web/CSS/width)width = `${const percent: numberpercent}%`; },owner?: Group | undefinedowner:const myGroup: GroupmyGroup }); });
Creating Empty FileStreams
Create an empty FileStream when you want to manually add binary data in chunks:
// Create a new empty FileStream constconst fileStream: FileStreamfileStream =class FileStreamFileStreams are `CoFeed`s that contain binary data, collaborative versions of `Blob`s.FileStream.FileStream.create<FileStream>(this: CoValueClass<FileStream>, options?: { owner?: Account | Group; } | Account | Group): FileStreamCreate a new empty `FileStream` instance.create({owner?: Account | Group | undefinedowner:const myGroup: GroupmyGroup } );
Ownership
Like other CoValues, you can specify ownership when creating FileStreams.
// Create a team group constconst teamGroup: GroupteamGroup =class GroupGroup.create();Group.create<Group>(this: CoValueClass<Group>, options?: { owner: Account; } | Account): Groupconst teamGroup: GroupteamGroup.Group.addMember(member: Account, role: AccountRole): void (+3 overloads)addMember(colleagueAccount, "writer"); // Create a FileStream with shared ownership constconst colleagueAccount: Account | ({ readonly [x: string]: any; } & Account)const teamFileStream: FileStreamteamFileStream =class FileStreamFileStreams are `CoFeed`s that contain binary data, collaborative versions of `Blob`s.FileStream.FileStream.create<FileStream>(this: CoValueClass<FileStream>, options?: { owner?: Account | Group; } | Account | Group): FileStreamCreate a new empty `FileStream` instance.create({owner?: Group | Account | undefinedowner:const teamGroup: GroupteamGroup });
See Groups as permission scopes for more information on how to use groups to control access to FileStreams.
Reading from FileStreams
FileStreams provide several ways to access their binary content, from raw chunks to convenient Blob objects.
Getting Raw Data Chunks
To access the raw binary data and metadata:
// Get all chunks and metadata constfileData =const fileData: (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }) | undefinedconst fileStream: FileStreamfileStream.getChunks(); if (FileStream.getChunks(options?: { allowUnfinished?: boolean; }): (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }) | undefinedfileData) {const fileData: (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }) | undefinedvar console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`MIME type: ${fileData.const fileData: BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }mimeType: stringmimeType}`);var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Total size: ${fileData.const fileData: BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }totalSizeBytes?: number | undefinedtotalSizeBytes} bytes`);var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`File name: ${fileData.const fileData: BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }fileName?: string | undefinedfileName}`);var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Is complete: ${fileData.const fileData: BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }finished: booleanfinished}`); // Access raw binary chunks for (constconst chunk: Uint8Arraychunk offileData.const fileData: BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }chunks: Uint8Array[]chunks) { // Each chunk is a Uint8Arrayvar console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Chunk size: ${const chunk: Uint8Arraychunk.Uint8Array.length: numberThe length of the array.length} bytes`); } }
By default, getChunks() only returns data for completely synced FileStreams. To start using chunks from a FileStream that's currently still being synced use the allowUnfinished option:
// Get data even if the stream isn't complete constpartialData =const partialData: (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }) | undefinedconst fileStream: FileStreamfileStream.getChunks({FileStream.getChunks(options?: { allowUnfinished?: boolean; }): (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }) | undefinedallowUnfinished?: boolean | undefinedallowUnfinished: true });
Converting to Blobs
For easier integration with web APIs, convert to a Blob:
// Convert to a Blob constconst blob: Blob | undefinedblob =const fileStream: FileStreamfileStream.toBlob(); // Get the filename from the metadata constFileStream.toBlob(options?: { allowUnfinished?: boolean; }): Blob | undefinedconst filename: string | undefinedfilename =const fileStream: FileStreamfileStream.getChunks()?.FileStream.getChunks(options?: { allowUnfinished?: boolean; }): (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }) | undefinedfileName?: string | undefinedfileName; if (const blob: Blob | undefinedblob) { // Use with URL.createObjectURL constconst url: stringurl =var URL: { new (url: string | URL, base?: string | URL): URL; prototype: URL; canParse(url: string | URL, base?: string | URL): boolean; createObjectURL(obj: Blob | MediaSource): string; parse(url: string | URL, base?: string | URL): URL | null; revokeObjectURL(url: string): void; }The URL interface represents an object providing static methods used for creating object URLs. [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) `URL` class is a global reference for `import { URL } from 'node:url'` https://nodejs.org/api/url.html#the-whatwg-url-apiURL.function createObjectURL(obj: Blob | MediaSource): string[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static)createObjectURL(const blob: Blobblob); // Create a download link constconst link: HTMLAnchorElementlink =var document: Document[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)document.Document.createElement<"a">(tagName: "a", options?: ElementCreationOptions): HTMLAnchorElement (+2 overloads)Creates an instance of the element for the specified tag.createElement('a');const link: HTMLAnchorElementlink.HTMLHyperlinkElementUtils.href: stringReturns the hyperlink's URL. Can be set, to change the URL. [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/href)href =const url: stringurl;const link: HTMLAnchorElementlink.HTMLAnchorElement.download: string[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/download)download =const filename: string | undefinedfilename || 'document.pdf';const link: HTMLAnchorElementlink.HTMLElement.click(): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/click)click(); // Clean up when donevar URL: { new (url: string | URL, base?: string | URL): URL; prototype: URL; canParse(url: string | URL, base?: string | URL): boolean; createObjectURL(obj: Blob | MediaSource): string; parse(url: string | URL, base?: string | URL): URL | null; revokeObjectURL(url: string): void; }The URL interface represents an object providing static methods used for creating object URLs. [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) `URL` class is a global reference for `import { URL } from 'node:url'` https://nodejs.org/api/url.html#the-whatwg-url-apiURL.function revokeObjectURL(url: string): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static)revokeObjectURL(const url: stringurl); }
Loading FileStreams as Blobs
You can directly load a FileStream as a Blob when you only have its ID:
// Load directly as a Blob when you have an ID constconst blob: Blob | undefinedblob = awaitclass FileStreamFileStreams are `CoFeed`s that contain binary data, collaborative versions of `Blob`s.FileStream.FileStream.loadAsBlob(id: ID<FileStream>, options?: { allowUnfinished?: boolean; loadAs?: Account | AnonymousJazzAgent; }): Promise<Blob | undefined>Load a `FileStream` as a `Blob`loadAsBlob(const fileStreamId: stringfileStreamId); // By default, waits for complete uploads // For in-progress uploads: constconst partialBlob: Blob | undefinedpartialBlob = awaitclass FileStreamFileStreams are `CoFeed`s that contain binary data, collaborative versions of `Blob`s.FileStream.FileStream.loadAsBlob(id: ID<FileStream>, options?: { allowUnfinished?: boolean; loadAs?: Account | AnonymousJazzAgent; }): Promise<Blob | undefined>Load a `FileStream` as a `Blob`loadAsBlob(const fileStreamId: stringfileStreamId, {allowUnfinished?: boolean | undefinedallowUnfinished: true, });
Checking Completion Status
Check if a FileStream is fully synced:
if (const fileStream: FileStreamfileStream.FileStream.isBinaryStreamEnded(): booleanisBinaryStreamEnded()) {var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('File is completely synced'); } else {var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('File upload is still in progress'); }
Writing to FileStreams
When creating a FileStream manually (not using createFromBlob), you need to manage the upload process yourself. This gives you more control over chunking and progress tracking.
The Upload Lifecycle
FileStream uploads follow a three-stage process:
- Start - Initialize with metadata
- Push - Send one or more chunks of data
- End - Mark the stream as complete
Starting a FileStream
Begin by providing metadata about the file:
// Create an empty FileStream constconst fileStream: FileStreamfileStream =class FileStreamFileStreams are `CoFeed`s that contain binary data, collaborative versions of `Blob`s.FileStream.FileStream.create<FileStream>(this: CoValueClass<FileStream>, options?: { owner?: Account | Group; } | Account | Group): FileStreamCreate a new empty `FileStream` instance.create({owner?: Account | Group | undefinedowner:const myGroup: GroupmyGroup }); // Initialize with metadataconst fileStream: FileStreamfileStream.FileStream.start(options: BinaryStreamInfo): voidstart({mimeType: stringmimeType: 'application/pdf', // MIME type (required)totalSizeBytes?: number | undefinedtotalSizeBytes: 1024 * 1024 * 2, // Size in bytes (if known)fileName?: string | undefinedfileName: 'document.pdf' // Original filename (optional) });
Pushing Data
Add binary data in chunks - this helps with large files and progress tracking:
constconst data: Uint8Arraydata = newUint8Array(var Uint8Array: Uint8ArrayConstructor new (array: ArrayLike<number> | ArrayBufferLike) => Uint8Array (+4 overloads)const arrayBuffer: ArrayBufferLikearrayBuffer); // For large files, break into chunks (e.g., 100KB each) constconst chunkSize: numberchunkSize = 1024 * 100; for (letlet i: numberi = 0;let i: numberi <const data: Uint8Arraydata.Uint8Array.length: numberThe length of the array.length;let i: numberi +=const chunkSize: numberchunkSize) { // Create a slice of the data constconst chunk: Uint8Arraychunk =const data: Uint8Arraydata.Uint8Array.slice(start?: number, end?: number): Uint8ArrayReturns a section of an array.slice(let i: numberi,let i: numberi +const chunkSize: numberchunkSize); // Push chunk to the FileStreamconst fileStream: FileStreamfileStream.FileStream.push(data: Uint8Array): voidpush(const chunk: Uint8Arraychunk); // Track progress constconst progress: numberprogress =var Math: MathAn intrinsic object that provides basic mathematics functionality and constants.Math.Math.min(...values: number[]): numberReturns the smaller of a set of supplied numeric expressions.min(100,var Math: MathAn intrinsic object that provides basic mathematics functionality and constants.Math.Math.round(x: number): numberReturns a supplied numeric expression rounded to the nearest integer.round((let i: numberi +const chunk: Uint8Arraychunk.Uint8Array.length: numberThe length of the array.length) * 100 /const data: Uint8Arraydata.Uint8Array.length: numberThe length of the array.length));var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Upload progress: ${const progress: numberprogress}%`); }
Completing the Upload
Once all chunks are pushed, mark the FileStream as complete:
// Finalize the uploadconst fileStream: FileStreamfileStream.FileStream.end(): voidend();var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('Upload complete!');
Subscribing to FileStreams
Like other CoValues, you can subscribe to FileStreams to get notified of changes as they happen. This is especially useful for tracking upload progress when someone else is uploading a file.
Loading by ID
Load a FileStream when you have its ID:
// Load a FileStream by ID constconst fileStream: FileStream | nullfileStream = awaitclass FileStreamFileStreams are `CoFeed`s that contain binary data, collaborative versions of `Blob`s.FileStream.FileStream.load<FileStream>(this: CoValueClass<...>, id: ID<FileStream>, options?: { loadAs?: Account | AnonymousJazzAgent; allowUnfinished?: boolean; }): Promise<FileStream | null>Load a `FileStream`load(const fileStreamId: "co_z123"fileStreamId); if (const fileStream: FileStream | nullfileStream) {var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('FileStream loaded successfully'); // Check if it's complete if (const fileStream: FileStreamfileStream.FileStream.isBinaryStreamEnded(): booleanisBinaryStreamEnded()) { // Process the completed file constconst blob: Blob | undefinedblob =const fileStream: FileStreamfileStream.toBlob(); } }FileStream.toBlob(options?: { allowUnfinished?: boolean; }): Blob | undefined
Subscribing to Changes
Subscribe to a FileStream to be notified when chunks are added or when the upload is complete:
// Subscribe to a FileStream by ID constconst unsubscribe: () => voidunsubscribe =class FileStreamFileStreams are `CoFeed`s that contain binary data, collaborative versions of `Blob`s.FileStream.FileStream.subscribe<FileStream, RefsToResolve<FileStream>>(this: CoValueClass<...>, id: ID<FileStream>, listener: (value: FileStream, unsubscribe: () => void) => void): () => void (+1 overload)Subscribe to a `FileStream`, when you have an ID but don't have a `FileStream` instance yetsubscribe(const fileStreamId: "co_z123"fileStreamId, (fileStream: FileStreamfileStream:class FileStreamFileStreams are `CoFeed`s that contain binary data, collaborative versions of `Blob`s.FileStream) => { // Called whenever the FileStream changesvar console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('FileStream updated'); // Get current status constchunks =const chunks: (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }) | undefinedfileStream: FileStreamfileStream.getChunks({FileStream.getChunks(options?: { allowUnfinished?: boolean; }): (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }) | undefinedallowUnfinished?: boolean | undefinedallowUnfinished: true }); if (chunks) { constconst chunks: (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }) | undefinedconst uploadedBytes: numberuploadedBytes =chunks.const chunks: BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }chunks: Uint8Array[]chunks.Array<Uint8Array>.reduce<number>(callbackfn: (previousValue: number, currentValue: Uint8Array, currentIndex: number, array: Uint8Array[]) => number, initialValue: number): number (+2 overloads)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.reduce((sum: numbersum: number,chunk: Uint8Arraychunk: Uint8Array) =>sum: numbersum +chunk: Uint8Arraychunk.Uint8Array.length: numberThe length of the array.length, 0); constconst totalBytes: numbertotalBytes =chunks.const chunks: BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean; }totalSizeBytes?: number | undefinedtotalSizeBytes || 1; constconst progress: numberprogress =var Math: MathAn intrinsic object that provides basic mathematics functionality and constants.Math.Math.min(...values: number[]): numberReturns the smaller of a set of supplied numeric expressions.min(100,var Math: MathAn intrinsic object that provides basic mathematics functionality and constants.Math.Math.round(x: number): numberReturns a supplied numeric expression rounded to the nearest integer.round(const uploadedBytes: numberuploadedBytes * 100 /const totalBytes: numbertotalBytes));var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Upload progress: ${const progress: numberprogress}%`); if (fileStream: FileStreamfileStream.FileStream.isBinaryStreamEnded(): booleanisBinaryStreamEnded()) {var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('Upload complete!'); // Now safe to use the file constconst blob: Blob | undefinedblob =fileStream: FileStreamfileStream.toBlob(); // Clean up the subscription if we're doneFileStream.toBlob(options?: { allowUnfinished?: boolean; }): Blob | undefinedconst unsubscribe: () => voidunsubscribe(); } } });
Waiting for Upload Completion
If you need to wait for a FileStream to be fully synchronized across devices:
// Wait for the FileStream to be fully synced awaitconst fileStream: FileStreamfileStream.FileStream.$jazz: FileStreamJazzApi<FileStream>$jazz.FileStreamJazzApi<FileStream>.waitForSync(options?: { timeout?: number; }): Promise<unknown[]>Wait for the `FileStream` to be uploaded to the other peers.waitForSync({timeout?: number | undefinedtimeout: 5000 // Optional timeout in ms });var console: ConsoleThe `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('FileStream is now synced to all connected devices');
This is useful when you need to ensure that a file is available to other users before proceeding with an operation.