Bug 1787269 [wpt PR 35624] - Further refine STP download regexs, a=testonly
[gecko.git] / dom / docs / ioutils_migration.md
blob246731a3d7c12b2a9f3eb1d1a39b447802b1ab90
1 # IOUtils Migration Guide
3 **Improving performance through a new file API**
5 ---
7 ## What is IOUtils?
9 `IOUtils` is a privileged JavaScript API for performing file I/O in the Firefox frontend.
10 It was developed as a replacement for `OS.File`, addressing
11 [bug 1231711](https://bugzilla.mozilla.org/show_bug.cgi?id=1231711).
12 It is *not to be confused* with the unprivileged
13 [DOM File API](https://developer.mozilla.org/en-US/docs/Web/API/File).
15 `IOUtils` provides a minimal API surface to perform common
16 I/O tasks via a collection of static methods inspired from `OS.File`.
17 It is implemented in C++, and exposed to JavaScript via WebIDL bindings.
19 The most up-to-date API can always be found in
20 [IOUtils.webidl](https://searchfox.org/mozilla-central/source/dom/chrome-webidl/IOUtils.webidl).
22 ## Differences from `OS.File`
24 `IOUtils` has a similar API to `OS.File`, but one should keep in mind some key differences.
26 ### No `File` instances (except `SyncReadFile` in workers)
28 Most of the `IOUtils` methods only operate on absolute path strings, and don't expose a file handle to the caller.
29 The exception to this rule is the `openFileForSyncReading` API, which is only available in workers.
31 Furthermore, `OS.File` was exposing platform-specific file descriptors through the
32 [`fd`](https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/OSFile.jsm/OS.File_for_workers#Attributes)
33 attribute. `IOUtils` does not expose file descriptors.
35 ### WebIDL has no `Date` type
37 `IOUtils` is written in C++ and exposed to JavaScript through WebIDL.
38 Many uses of `OS.File` concern themselves with obtaining or manipulating file metadata,
39 like the last modified time, however the `Date` type does not exist in WebIDL.
40 Using `IOUtils`,
41 these values are returned to the caller as the number of milliseconds since
42 `1970-01-01T00:00:00Z`.
43 `Date`s can be safely constructed from these values if needed.
45 For example, to obtain the last modification time of a file and update it to the current time:
47 ```js
48 let { lastModified } = await IOUtils.stat(path);
50 let lastModifiedDate = new Date(lastModified);
52 let now = new Date();
54 await IOUtils.touch(path, now.valueOf());
55 ```
57 ### Some methods are not implemented
59 For various reasons
60 (complexity, safety, availability of underlying system calls, usefulness, etc.)
61 the following `OS.File` methods have no analogue in IOUtils.
62 They also will **not** be implemented.
64 -   void unixSymlink(in string targetPath, in string createPath)
65 -   string getCurrentDirectory(void)
66 -   void setCurrentDirectory(in string path)
67 -   object open(in string path)
68 -   object openUnique(in string path)
70 ### Errors are reported as `DOMException`s
72 When an `OS.File` method runs into an error,
73 it will throw/reject with a custom
74 [`OS.File.Error`](https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/OSFile.jsm/OS.File.Error).
75 These objects have custom attributes that can be checked for common error cases.
77 `IOUtils` has similar behaviour, however its methods consistently reject with a
78 [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException)
79 whose name depends on the failure:
81 | Exception Name | Reason for exception |
82 | -------------- | -------------------- |
83 | `NotFoundError` | A file at the specified path could not be found on disk. |
84 | `NotAllowedError` | Access to a file at the specified path was denied by the operating system. |
85 | `NotReadableError` | A file at the specified path could not be read for some reason. It may have been too big to read, or it was corrupt, or some other reason. The exception message should have more details. |
86 | `ReadOnlyError` | A file at the specified path is read only and could not be modified. |
87 | `NoModificationAllowedError` | A file already exists at the specified path and could not be overwritten according to the specified options. The exception message should have more details. |
88 | `OperationError` | Something went wrong during the I/O operation. E.g. failed to allocate a buffer. The exception message should have more details. |
89 | `UnknownError` | An unknown error occurred in the implementation. An nsresult error code should be included in the exception message to assist with debugging and improving `IOUtils` internal error handling. |
91 ### `IOUtils` is mostly async-only
93 `OS.File` provided an asynchronous front-end for main-thread consumers,
94 and a synchronous front-end for workers.
95 `IOUtils` only provides an asynchronous API for the vast majority of its API surface.
96 These asynchronous methods can be called from both the main thread and from chrome-privileged worker threads.
98 The one exception to this rule is `openFileForSyncReading`, which allows synchronous file reading in workers.
100 ## `OS.File` vs `IOUtils`
102 Some methods and options of `OS.File` keep the same name and underlying behaviour in `IOUtils`,
103 but others have been renamed.
104 The following is a detailed comparison with examples of the methods and options in each API.
106 ### Reading a file
108 `IOUtils` provides the following methods to read data from a file. Like
109 `OS.File`, they accept an `options` dictionary.
111 Note: The maximum file size that can be read is `UINT32_MAX` bytes. Attempting
112 to read a file larger will result in a `NotReadableError`.
114 ```idl
115 Promise<Uint8Array> read(DOMString path, ...);
117 Promise<DOMString> readUTF8(DOMString path, ...);
119 Promise<any> readJSON(DOMString path, ...);
121 // Workers only:
122 SyncReadFile openFileForSyncReading(DOMString path);
125 #### Options
127 | `OS.File` option   | `IOUtils` option             | Description                                                                                                               |
128 | ------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
129 | bytes: number?     | maxBytes: number?            | If specified, read only up to this number of bytes. Otherwise, read the entire file. Default is null.                         |
130 | compression: 'lz4' | decompress: boolean          | If true, read the file and return the decompressed LZ4 stream. Otherwise, just read the file byte-for-byte. Default is false. |
131 | encoding: 'utf-8'  | N/A; use `readUTF8` instead. | Interprets the file as UTF-8 encoded text, and returns a string to the caller.                                                |
133 #### Examples
135 ##### Read raw (unsigned) byte values
137 **`OS.File`**
138 ```js
139 let bytes = await OS.File.read(path); // Uint8Array
141 **`IOUtils`**
142 ```js
143 let bytes = await IOUtils.read(path); // Uint8Array
146 ##### Read UTF-8 encoded text
148 **`OS.File`**
149 ```js
150 let utf8 = await OS.File.read(path, { encoding: 'utf-8' }); // string
152 **`IOUtils`**
153 ```js
154 let utf8 = await IOUtils.readUTF8(path); // string
157 ##### Read JSON file
159 **`IOUtils`**
160 ```js
161 let obj = await IOUtils.readJSON(path); // object
164 ##### Read LZ4 compressed file contents
166 **`OS.File`**
167 ```js
168 // Uint8Array
169 let bytes = await OS.File.read(path, { compression: 'lz4' });
170 // string
171 let utf8 = await OS.File.read(path, {
172     encoding: 'utf-8',
173     compression: 'lz4',
176 **`IOUtils`**
177 ```js
178 let bytes = await IOUtils.read(path, { decompress: true }); // Uint8Array
179 let utf8 = await IOUtils.readUTF8(path, { decompress: true }); // string
182 ##### Synchronously read a fragment of a file into a buffer, from a worker
184 **`OS.File`**
185 ```js
186 // Read 64 bytes at offset 128, workers only:
187 let file = OS.File.open(path, { read: true });
188 file.setPosition(128);
189 let bytes = file.read({ bytes: 64 }); // Uint8Array
190 file.close();
192 **`IOUtils`**
193 ```js
194 // Read 64 bytes at offset 128, workers only:
195 let file = IOUtils.openFileForSyncReading(path);
196 let bytes = new Uint8Array(64);
197 file.readBytesInto(bytes, 128);
198 file.close();
201 ### Writing to a file
203 IOUtils provides the following methods to write data to a file. Like
204 OS.File, they accept an options dictionary.
206 ```idl
207 Promise<unsigned long long> write(DOMString path, Uint8Array data, ...);
209 Promise<unsigned long long> writeUTF8(DOMString path, DOMString string, ...);
211 Promise<unsigned long long> writeJSON(DOMString path, any value, ...);
214 #### Options
216 | `OS.File` option     | `IOUtils` option              | Description                                                                                                                                                               |
217 | -------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
218 | backupTo: string?    | backupFile: string?           | Identifies the path to backup the target file to before performing the write operation. If unspecified, no backup will be performed. Default is null.                     |
219 | tmpPath: string?     | tmpPath: string?              | Identifies a path to write to first, before performing a move to overwrite the target file. If unspecified, the target file will be written to directly. Default is null. |
220 | noOverwrite: boolean | noOverwrite: boolean          | If true, fail if the destination already exists. Default is false.                                                                                                        |
221 | flush: boolean       | flush: boolean                | If true, force the OS to flush its internal buffers to disk. Default is false.                                                                                            |
222 | encoding: 'utf-8'    | N/A; use `writeUTF8` instead. | Allows the caller to supply a string to be encoded as utf-8 text on disk.                                                                                                 |
224 #### Examples
225 ##### Write raw (unsigned) byte values
227 **`OS.File`**
228 ```js
229 let bytes = new Uint8Array();
230 await OS.File.writeAtomic(path, bytes);
233 **`IOUtils`**
234 ```js
235 let bytes = new Uint8Array();
236 await IOUtils.write(path, bytes);
239 ##### Write UTF-8 encoded text
241 **`OS.File`**
242 ```js
243 let str = "";
244 await OS.File.writeAtomic(path, str, { encoding: 'utf-8' });
247 **`IOUtils`**
248 ```js
249 let str = "";
250 await IOUtils.writeUTF8(path, str);
253 ##### Write A JSON object
255 **`IOUtils`**
256 ```js
257 let obj = {};
258 await IOUtils.writeJSON(path, obj);
261 ##### Write with LZ4 compression
263 **`OS.File`**
264 ```js
265 let bytes = new Uint8Array();
266 await OS.File.writeAtomic(path, bytes, { compression: 'lz4' });
267 let str = "";
268 await OS.File.writeAtomic(path, str, {
269     compression: 'lz4',
273 **`IOUtils`**
274 ```js
275 let bytes = new Uint8Array();
276 await IOUtils.write(path, bytes, { compress: true });
277 let str = "";
278 await IOUtils.writeUTF8(path, str, { compress: true });
281 ### Move a file
283 `IOUtils` provides the following method to move files on disk.
284 Like `OS.File`, it accepts an options dictionary.
286 ```idl
287 Promise<void> move(DOMString sourcePath, DOMString destPath, ...);
290 #### Options
292 | `OS.File` option     | `IOUtils` option                    | Description                                                                                                                                                               |
293 | -------------------- | ----------------------------------- | ---------------------------------------------------------------------------- |
294 | noOverwrite: boolean | noOverwrite: boolean                | If true, fail if the destination already exists. Default is false.           |
295 | noCopy: boolean      | N/A; will not be implemented        | This option is not implemented in `IOUtils`, and will be ignored if provided |
297 #### Example
299 **`OS.File`**
300 ```js
301 await OS.File.move(srcPath, destPath);
304 **`IOUtils`**
305 ```js
306 await IOUtils.move(srcPath, destPath);
309 ### Remove a file
311 `IOUtils` provides *one* method to remove files from disk.
312 `OS.File` provides several methods.
314 ```idl
315 Promise<void> remove(DOMString path, ...);
318 #### Options
320 | `OS.File` option                                           | `IOUtils` option      | Description                                                                                                      |
321 | ---------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------- |
322 | ignoreAbsent: boolean                                      | ignoreAbsent: boolean | If true, and the destination does not exist, then do not raise an error. Default is true.                        |
323 | N/A; `OS.File` has dedicated methods for directory removal | recursive: boolean    | If true, and the target is a directory, recursively remove the directory and all its children. Default is false. |
325 #### Examples
327 ##### Remove a file
329 **`OS.File`**
330 ```js
331 await OS.File.remove(path, { ignoreAbsent: true });
334 **`IOUtils`**
335 ```js
336 await IOUtils.remove(path);
339 ##### Remove a directory and all its contents
341 **`OS.File`**
342 ```js
343 await OS.File.removeDir(path, { ignoreAbsent: true });
346 **`IOUtils`**
347 ```js
348 await IOUtils.remove(path, { recursive: true });
351 ##### Remove an empty directory
353 **`OS.File`**
354 ```js
355 await OS.File.removeEmptyDir(path); // Will throw an exception if `path` is not empty.
358 **`IOUtils`**
359 ```js
360 await IOUtils.remove(path); // Will throw an exception if `path` is not empty.
363 ### Make a directory
365 `IOUtils` provides the following method to create directories on disk.
366 Like `OS.File`, it accepts an options dictionary.
368 ```idl
369 Promise<void> makeDirectory(DOMString path, ...);
372 #### Options
374 | `OS.File` option        | `IOUtils` option         | Description                                                                                                                                                                                                     |
375 | ----------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
376 | ignoreExisting: boolean | ignoreExisting: boolean  | If true, succeed even if the target directory already exists. Default is true.                                                                                                                                  |
377 | from: string            | createAncestors: boolean | If true, `IOUtils` will create all missing ancestors in a path. Default is true. This option differs from `OS.File`, which requires the caller to specify a root path from which to create missing directories. |
378 | unixMode                | N/A                      | `IOUtils` does not support setting a custom directory mode on unix.                                                                                                                                             |
379 | winSecurity             | N/A                      | `IOUtils` does not support setting custom directory security settings on Windows.                                                                                                                               |
381 #### Example
383 **`OS.File`**
384 ```js
385 await OS.File.makeDir(srcPath, destPath);
387 **`IOUtils`**
388 ```js
389 await IOUtils.makeDirectory(srcPath, destPath);
392 ### Update a file's modification time
394 `IOUtils` provides the following method to update a file's modification time.
396 ```idl
397 Promise<void> setModificationTime(DOMString path, optional long long modification);
400 #### Example
402 **`OS.File`**
403 ```js
404 await OS.File.setDates(path, new Date(), new Date());
407 **`IOUtils`**
408 ```js
409 await IOUtils.setModificationTime(path, new Date().valueOf());
412 ### Get file metadata
414 `IOUtils` provides the following method to query file metadata.
416 ```idl
417 Promise<void> stat(DOMString path);
420 #### Example
422 **`OS.File`**
423 ```js
424 let fileInfo = await OS.File.stat(path);
427 **`IOUtils`**
428 ```js
429 let fileInfo = await IOUtils.stat(path);
432 ### Copy a file
434 `IOUtils` provides the following method to copy a file on disk.
435 Like `OS.File`, it accepts an options dictionary.
437 ```idl
438 Promise<void> copy(DOMString path, ...);
441 #### Options
443 | `OS.File` option                                                    | `IOUtils` option     | Description                                                    |
444 | ------------------------------------------------------------------- | -------------------- | -------------------------------------------------------------------|
445 | noOverwrite: boolean                                                | noOverwrite: boolean | If true, fail if the destination already exists. Default is false. |
446 | N/A; `OS.File` does not appear to support recursively copying files | recursive: boolean   | If true, copy the source recursively.                              |
448 #### Examples
450 ##### Copy a file
452 **`OS.File`**
453 ```js
454 await OS.File.copy(srcPath, destPath);
457 **`IOUtils`**
458 ```js
459 await IOUtils.copy(srcPath, destPath);
462 ##### Copy a directory recursively
464 **`OS.File`**
465 ```js
466 // Not easy to do.
469 **`IOUtils`**
470 ```js
471 await IOUtils.copy(srcPath, destPath, { recursive: true });
474 ### Iterate a directory
476 At the moment, `IOUtils` does not have a way to expose an iterator for directories.
477 This is blocked by
478 [bug 1577383](https://bugzilla.mozilla.org/show_bug.cgi?id=1577383).
479 As a stop-gap for this functionality,
480 one can get all the children of a directory and iterate through the returned path array using the following method.
482 ```idl
483 Promise<sequence<DOMString>> getChildren(DOMString path);
486 #### Example
488 **`OS.File`**
489 ```js
490 for await (const { path } of new OS.FileDirectoryIterator(dirName)) {</p>
491   ...
495 **`IOUtils`**
496 ```js
497 for (const path of await IOUtils.getChildren(dirName)) {
498   ...
502 ### Check if a file exists
504 `IOUtils` provides the following method analogous to the `OS.File` method of the same name.
506 ```idl
507 Promise<boolean> exists(DOMString path);
510 #### Example
512 **`OS.File`**
513 ```js
514 if (await OS.File.exists(path)) {
515   ...
519 **`IOUtils`**
520 ```js
521 if (await IOUtils.exists(path)) {
522   ...
526 ### Set the permissions of a file
528 `IOUtils` provides the following method analogous to the `OS.File` method of the same name.
530 ```idl
531 Promise<void> setPermissions(DOMString path, unsigned long permissions, optional boolean honorUmask = true);
534 #### Options
536 | `OS.File` option        | `IOUtils` option           | Description                                                                                                                          |
537 | ----------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
538 | unixMode: number        | permissions: unsigned long | The UNIX file mode representing the permissions. Required in IOUtils.                                                                |
539 | unixHonorUmask: boolean | honorUmask: boolean        | If omitted or true, any UNIX file mode is modified by the permissions. Otherwise the exact value of the permissions will be applied. |
541 #### Example
543 **`OS.File`**
544 ```js
545 await OS.File.setPermissions(path, { unixMode: 0o600 });
548 **`IOUtils`**
549 ```js
550 await IOUtils.setPermissions(path, 0o600);
553 ## FAQs
555 **Why should I use `IOUtils` instead of `OS.File`?**
557 [Bug 1231711](https://bugzilla.mozilla.org/show_bug.cgi?id=1231711)
558 provides some good context, but some reasons include:
559 * reduced cache-contention,
560 * faster startup, and
561 * less memory usage.
563 Additionally, `IOUtils` benefits from a native implementation,
564 which assists in performance-related work for
565 [Project Fission](https://hacks.mozilla.org/2021/05/introducing-firefox-new-site-isolation-security-architecture/).
567 We are actively working to migrate old code usages of `OS.File`
568 to analogous `IOUtils` calls, so new usages of `OS.File`
569 should not be introduced at this time.
571 **Do I need to import anything to use this API?**
573 Nope! It's available via the `IOUtils` global in JavaScript (`ChromeOnly` context).
575 **Can I use this API from C++ or Rust?**
577 Currently usage is geared exclusively towards JavaScript callers,
578 and all C++ methods are private except for the Web IDL bindings.
579 However given sufficient interest,
580 it should be easy to expose ergonomic public methods for C++ and/or Rust.
582 **Why isn't `IOUtils` written in Rust?**
584 At the time of writing,
585 support for Web IDL bindings was more mature for C++ oriented tooling than it was for Rust.
587 **Is `IOUtils` feature complete? When will it be available?**
589 `IOUtils` is considered feature complete as of Firefox 83.