Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -1470,6 +1470,15 @@ added:

Enable exposition of [EventSource Web API][] on the global scope.

### `--experimental-fileapi`

<!-- YAML
added: REPLACEME
-->

Enable exposition of the [File API][] globals `FileReader`, `FileReaderSync`,
and `ProgressEvent` on the global scope.

### `--experimental-import-meta-resolve`

<!-- YAML
Expand Down Expand Up @@ -4317,6 +4326,7 @@ one is included in the list below.
* `--experimental-detect-module`
* `--experimental-dtls`
* `--experimental-eventsource`
* `--experimental-fileapi`
* `--experimental-import-meta-resolve`
* `--experimental-import-text`
* `--experimental-json-modules`
Expand Down Expand Up @@ -4932,6 +4942,7 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
[EventSource Web API]: https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
[ExperimentalWarning: `vm.measureMemory` is an experimental feature]: vm.md#vmmeasurememoryoptions
[FIPS mode]: crypto.md#fips-mode
[File API]: https://w3c.github.io/FileAPI/
[File System Permissions]: permissions.md#file-system-permissions
[Loading ECMAScript modules using `require()`]: modules.md#loading-ecmascript-modules-using-require
[Module resolution and loading]: packages.md#module-resolution-and-loading
Expand Down
114 changes: 112 additions & 2 deletions doc/api/globals.md
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,82 @@ added: v20.0.0

See {File}.

## Class: `FileReader`
Comment thread
jasnell marked this conversation as resolved.
Resolved

<!-- YAML
added: REPLACEME
-->

> Stability: 1.1 - Active development. Enable this API with the
> [`--experimental-fileapi`][] CLI flag.

An implementation of {FileReader} from the [File API][]. `readAsArrayBuffer()`,
`readAsBinaryString()`, `readAsText()`, and `readAsDataURL()` read a {Blob}
asynchronously and report the result through `loadstart`, `progress`, `load`,
`abort`, `error`, and `loadend` events. `readyState` is `FileReader.EMPTY`
(`0`), `FileReader.LOADING` (`1`), or `FileReader.DONE` (`2`).

`FileReader` and `FileReaderSync` are not integrated with [`node:fs`][] or
[`node:vfs`][]. They read {Blob} and {File} objects only, and do not accept
paths, file descriptors, or {FileHandle} objects. A {File} is not tied to a
file on disk. To read a file through these APIs, first create a file-backed
{Blob} with [`fs.openAsBlob()`][]. To read a file without them, use
[`fsPromises.readFile()`][].

```js
const { openAsBlob } = require('node:fs');

(async () => {
const blob = await openAsBlob(__filename);
const reader = new FileReader();
reader.onload = () => console.log(reader.result.length);
reader.readAsText(blob);
})();
```

`readAsDataURL()` produces a base64 `data:` URL. When the blob's type is the
empty string, the URL has no media type (`data:;base64,...`). Chrome and
Firefox use `application/octet-stream` in that case. `#`, `?`, `%`, `,`, and
whitespace in a media type are percent-encoded so the result stays one URL that
[`fetch()`][] reads back to the blob's bytes.

`readAsText()` follows {TextDecoder} for the chosen encoding, including its
ICU requirement. Labels that the Encoding Standard maps to the replacement
encoding, such as `'iso-2022-kr'`, decode to U+FFFD when the input is not
empty.

```js
const reader = new FileReader();
reader.addEventListener('load', () => {
console.log(reader.result); // Prints: hello
});
reader.readAsText(new Blob(['hello']));
```

## Class: `FileReaderSync`

<!-- YAML
added: REPLACEME
-->

> Stability: 1.1 - Active development. Enable this API with the
> [`--experimental-fileapi`][] CLI flag.

An implementation of {FileReaderSync} from the [File API][]. The File API
exposes it only in dedicated and shared workers. Node.js also exposes it on
the main thread and in [`node:worker_threads`][] when this flag is enabled.

`readAsArrayBuffer()`, `readAsBinaryString()`, `readAsText()`, and
`readAsDataURL()` read a {Blob} synchronously, including file-backed blobs
returned by [`fs.openAsBlob()`][]. If the underlying file has been removed,
the error is `NotFoundError`. If the file has changed since the blob was
created, the error is `NotReadableError`.

```js
const text = new FileReaderSync().readAsText(new Blob(['hello']));
console.log(text); // Prints: hello
```

## Class: `FormData`

<!-- YAML
Expand Down Expand Up @@ -942,6 +1018,33 @@ added: v0.1.7

The process object. See the [`process` object][] section.

## Class: `ProgressEvent`

<!-- YAML
added: REPLACEME
-->

> Stability: 1.1 - Active development. Enable this API with the
> [`--experimental-fileapi`][] CLI flag.

An implementation of {ProgressEvent} from the [XMLHttpRequest Standard][].
`FileReader`
dispatches `ProgressEvent`s for `loadstart`, `progress`, `load`, `abort`,
`error`, and `loadend`. Those events do not bubble and are not cancelable.
`lengthComputable`, `loaded`, and `total` return the values they were
initialized to (`false`, `0`, and `0` when omitted). The File API's
"fire a progress event" algorithm does not set those three fields, so events
fired by `FileReader` leave them at the defaults.

```js
const event = new ProgressEvent('progress', {
lengthComputable: true,
loaded: 50,
total: 100,
});
console.log(event.loaded / event.total); // Prints: 0.5
```

## `queueMicrotask(callback)`

<!-- YAML
Expand Down Expand Up @@ -1375,8 +1478,9 @@ accepted and how failures are reported:
* On the main thread, relative script URLs are resolved against the current
working directory, because there is no document base URL. Within a worker
they are resolved against the worker's own URL (as is done in the spec).
* For `blob:` URLs, the script must be held in memory, so blobs backed by a file,
such as those returned by [`fs.openAsBlob()`][], cannot be used.
* For `blob:` URLs backed by a file, such as those returned by
[`fs.openAsBlob()`][], the file is read synchronously when the script is
loaded.

[Type stripping][type stripping] only applies to module workers loaded from
`file:` URLs. The `type` option, not the file extension, decides how an entry is
Expand Down Expand Up @@ -1479,12 +1583,15 @@ A browser-compatible implementation of [`WritableStreamDefaultWriter`][].
[CommonJS module]: modules.md
[CommonJS modules]: modules.md
[ECMAScript module]: esm.md
[File API]: https://w3c.github.io/FileAPI/
[HTML Standard]: https://html.spec.whatwg.org/multipage/workers.html
[Navigator API]: https://html.spec.whatwg.org/multipage/system-state.html#the-navigator-object
[RFC 5646]: https://www.rfc-editor.org/rfc/rfc5646.txt
[Refable protocol]: process.md#processrefmayberefable
[Web Crypto API]: webcrypto.md
[XMLHttpRequest Standard]: https://xhr.spec.whatwg.org/#interface-progressevent
[`--experimental-eventsource`]: cli.md#--experimental-eventsource
[`--experimental-fileapi`]: cli.md#--experimental-fileapi
[`--localstorage-file`]: cli.md#--localstorage-filefile
[`--no-experimental-global-navigator`]: cli.md#--no-experimental-global-navigator
[`--no-experimental-web-worker`]: cli.md#--no-experimental-web-worker
Expand Down Expand Up @@ -1537,9 +1644,12 @@ A browser-compatible implementation of [`WritableStreamDefaultWriter`][].
[`exports`]: modules.md#exports
[`fetch()`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch
[`fs.openAsBlob()`]: fs.md#fsopenasblobpath-options
[`fsPromises.readFile()`]: fs.md#fspromisesreadfilepath-options
[`globalThis`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
[`localStorage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
[`module`]: modules.md#module
[`node:fs`]: fs.md
[`node:vfs`]: vfs.md
[`node:worker_threads`]: worker_threads.md
[`perf_hooks.performance`]: perf_hooks.md#perf_hooksperformance
[`process.nextTick()`]: process.md#processnexttickcallback-args
Expand Down
4 changes: 4 additions & 0 deletions doc/node-config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,10 @@
"type": "boolean",
"description": "experimental node:ffi module"
},
"experimental-fileapi": {
"type": "boolean",
"description": "experimental File API globals"
},
"experimental-global-navigator": {
"type": "boolean",
"description": "expose experimental Navigator API on the global scope"
Expand Down
6 changes: 6 additions & 0 deletions doc/node.1
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,10 @@ dtls documentation for details.
.It Fl -experimental-eventsource
Enable exposition of EventSource Web API on the global scope.
.
.It Fl -experimental-fileapi
Enable exposition of the File API globals \fBFileReader\fR, \fBFileReaderSync\fR,
and \fBProgressEvent\fR on the global scope.
.
.It Fl -experimental-import-meta-resolve
Enable experimental \fBimport.meta.resolve()\fR parent URL support, which allows
passing a second \fBparentURL\fR argument for contextual resolution.
Expand Down Expand Up @@ -2271,6 +2275,8 @@ one is included in the list below.
.It
\fB--experimental-eventsource\fR
.It
\fB--experimental-fileapi\fR
.It
\fB--experimental-import-meta-resolve\fR
.It
\fB--experimental-import-text\fR
Expand Down
3 changes: 3 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,13 @@ export default [
DisposableStack: 'readonly',
EventSource: 'readonly',
fetch: 'readonly',
FileReader: 'readonly',
FileReaderSync: 'readonly',
Float16Array: 'readonly',
FormData: 'readonly',
localStorage: 'readonly',
navigator: 'readonly',
ProgressEvent: 'readonly',
QuotaExceededError: 'readonly',
ReadableByteStreamController: 'readonly',
ReadableStream: 'readonly',
Expand Down
40 changes: 30 additions & 10 deletions lib/internal/blob.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ const {
} = require('internal/encoding');
const { URL } = require('internal/url');

const { UV_ENOENT } = internalBinding('uv');

const {
markTransferMode,
kClone,
Expand Down Expand Up @@ -473,6 +475,19 @@ function createBlobFromFilePath(path, options) {
return res;
}

function blobReadException(status) {
// File API error conditions: a missing resource is NotFoundError.
// Other read failures are NotReadableError.
if (status === UV_ENOENT) {
return lazyDOMException(
'The file could not be found.',
'NotFoundError');
}
return lazyDOMException(
'The blob could not be read',
'NotReadableError');
}

function arrayBuffer(blob) {
const { promise, resolve, reject } = PromiseWithResolvers();
const reader = blob[kHandle].getReader();
Expand All @@ -487,8 +502,8 @@ function arrayBuffer(blob) {
} else if (status < 0) {
// The read could fail for many different reasons when reading
// from a non-memory resident blob part (e.g. file-backed blob).
// The error details the system error code.
const error = lazyDOMException('The blob could not be read', 'NotReadableError');
// status is the libuv error code.
const error = blobReadException(status);
reject(error);
return;
}
Expand All @@ -502,17 +517,16 @@ function arrayBuffer(blob) {
}

/**
* Read a blob's data synchronously. This is only possible when every part
* of the blob is memory-resident, in which case the reader's pull callbacks
* are invoked synchronously; otherwise (e.g. for file-backed blobs)
* undefined is returned.
* Read a blob's data synchronously. Sources that cannot provide data
* synchronously return undefined.
* @param {Blob} blob
* @returns {ArrayBuffer|undefined}
*/
function getBlobDataSync(blob) {
const reader = blob[kHandle].getReader();
const buffers = [];
let result;
let failure;
let ended = false;
while (!ended) {
let sync = false;
Expand All @@ -524,17 +538,25 @@ function getBlobDataSync(blob) {
ended = true;
return;
} else if (status < 0) {
failure = status;
ended = true;
return;
} else if (status === 2) {
// STATUS_BLOCK: do not retry a source that cannot provide data now.
ended = true;
return;
}
if (buffer !== undefined)
ArrayPrototypePush(buffers, buffer);
});
}, true);
if (!sync) {
// The data is not available synchronously.
break;
}
}
if (failure !== undefined) {
throw blobReadException(failure);
}
return result;
}

Expand Down Expand Up @@ -595,9 +617,7 @@ function createBlobReaderStream(reader) {
// from a non-memory resident blob part (e.g. file-backed blob).
// The error details the system error code.
reader.setWakeup(undefined);
const error =
lazyDOMException('The blob could not be read',
'NotReadableError');
const error = blobReadException(status);
const pending = this.pendingPulls.shift();
c.error(error);
pending.reject(error);
Expand Down
9 changes: 9 additions & 0 deletions lib/internal/bootstrap/web/exposed-window-or-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ exposeLazyInterfaces(globalThis, 'internal/webworker', ['Worker']);
exposeLazyInterfaces(globalThis, 'internal/blob', ['Blob']);
// https://www.w3.org/TR/FileAPI/#dfn-file
exposeLazyInterfaces(globalThis, 'internal/file', ['File']);
// https://w3c.github.io/FileAPI/#APIASynch
// https://w3c.github.io/FileAPI/#FileReaderSync
// The File API exposes FileReaderSync only in dedicated and shared workers.
// Node.js exposes it in every realm that gets these globals.
exposeLazyInterfaces(globalThis, 'internal/filereader', [
'FileReader', 'FileReaderSync',
]);
// https://xhr.spec.whatwg.org/#interface-progressevent
exposeLazyInterfaces(globalThis, 'internal/progress_event', ['ProgressEvent']);
// https://www.w3.org/TR/hr-time-2/#the-performance-attribute
exposeLazyInterfaces(globalThis, 'perf_hooks', [
'Performance', 'PerformanceEntry', 'PerformanceMark', 'PerformanceMeasure',
Expand Down
1 change: 1 addition & 0 deletions lib/internal/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,5 @@ ObjectDefineProperties(File.prototype, {
module.exports = {
File,
TransferableFile,
isFile,
};
Loading
Loading