@tauri-apps/plugin-fs 2.0.0-alpha.3 → 2.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,700 @@
1
+ export { BaseDirectory } from '@tauri-apps/api/path';
2
+ import { Resource, invoke, Channel } from '@tauri-apps/api/core';
3
+
4
+ // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
5
+ // SPDX-License-Identifier: Apache-2.0
6
+ // SPDX-License-Identifier: MIT
7
+ /**
8
+ * Access the file system.
9
+ *
10
+ * ## Security
11
+ *
12
+ * This module prevents path traversal, not allowing absolute paths or parent dir components
13
+ * (i.e. "/usr/path/to/file" or "../path/to/file" paths are not allowed).
14
+ * Paths accessed with this API must be relative to one of the {@link BaseDirectory | base directories}
15
+ * so if you need access to arbitrary filesystem paths, you must write such logic on the core layer instead.
16
+ *
17
+ * The API has a scope configuration that forces you to restrict the paths that can be accessed using glob patterns.
18
+ *
19
+ * The scope configuration is an array of glob patterns describing folder paths that are allowed.
20
+ * For instance, this scope configuration only allows accessing files on the
21
+ * *databases* folder of the {@link https://beta.tauri.app/2/reference/js/core/namespacepath/#appdatadir | `$APPDATA` directory}:
22
+ * ```json
23
+ * {
24
+ * "plugins": {
25
+ * "fs": {
26
+ * "scope": ["$APPDATA/databases/*"]
27
+ * }
28
+ * }
29
+ * }
30
+ * ```
31
+ *
32
+ * Notice the use of the `$APPDATA` variable. The value is injected at runtime, resolving to the {@link https://beta.tauri.app/2/reference/js/core/namespacepath/#appdatadir | app data directory}.
33
+ *
34
+ * The available variables are:
35
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#appconfigdir | $APPCONFIG},
36
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#appdatadir | $APPDATA},
37
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#appLocaldatadir | $APPLOCALDATA},
38
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#appcachedir | $APPCACHE},
39
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#applogdir | $APPLOG},
40
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#audiodir | $AUDIO},
41
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#cachedir | $CACHE},
42
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#configdir | $CONFIG},
43
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#datadir | $DATA},
44
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#localdatadir | $LOCALDATA},
45
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#desktopdir | $DESKTOP},
46
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#documentdir | $DOCUMENT},
47
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#downloaddir | $DOWNLOAD},
48
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#executabledir | $EXE},
49
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#fontdir | $FONT},
50
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#homedir | $HOME},
51
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#picturedir | $PICTURE},
52
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#publicdir | $PUBLIC},
53
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#runtimedir | $RUNTIME},
54
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#templatedir | $TEMPLATE},
55
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#videodir | $VIDEO},
56
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#resourcedir | $RESOURCE},
57
+ * {@linkcode https://beta.tauri.app/2/reference/js/core/namespacepath/#tempdir | $TEMP}.
58
+ *
59
+ * Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
60
+ *
61
+ * Note that this scope applies to **all** APIs on this module.
62
+ *
63
+ * @module
64
+ */
65
+ var SeekMode;
66
+ (function (SeekMode) {
67
+ SeekMode[SeekMode["Start"] = 0] = "Start";
68
+ SeekMode[SeekMode["Current"] = 1] = "Current";
69
+ SeekMode[SeekMode["End"] = 2] = "End";
70
+ })(SeekMode || (SeekMode = {}));
71
+ function parseFileInfo(r) {
72
+ return {
73
+ isFile: r.isFile,
74
+ isDirectory: r.isDirectory,
75
+ isSymlink: r.isSymlink,
76
+ size: r.size,
77
+ mtime: r.mtime != null ? new Date(r.mtime) : null,
78
+ atime: r.atime != null ? new Date(r.atime) : null,
79
+ birthtime: r.birthtime != null ? new Date(r.birthtime) : null,
80
+ readonly: r.readonly,
81
+ fileAttributes: r.fileAttributes,
82
+ dev: r.dev,
83
+ ino: r.ino,
84
+ mode: r.mode,
85
+ nlink: r.nlink,
86
+ uid: r.uid,
87
+ gid: r.gid,
88
+ rdev: r.rdev,
89
+ blksize: r.blksize,
90
+ blocks: r.blocks,
91
+ };
92
+ }
93
+ /**
94
+ * The Tauri abstraction for reading and writing files.
95
+ *
96
+ * @since 2.0.0
97
+ */
98
+ class FileHandle extends Resource {
99
+ constructor(rid) {
100
+ super(rid);
101
+ }
102
+ /**
103
+ * Reads up to `p.byteLength` bytes into `p`. It resolves to the number of
104
+ * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error
105
+ * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may
106
+ * use all of `p` as scratch space during the call. If some data is
107
+ * available but not `p.byteLength` bytes, `read()` conventionally resolves
108
+ * to what is available instead of waiting for more.
109
+ *
110
+ * When `read()` encounters end-of-file condition, it resolves to EOF
111
+ * (`null`).
112
+ *
113
+ * When `read()` encounters an error, it rejects with an error.
114
+ *
115
+ * Callers should always process the `n` > `0` bytes returned before
116
+ * considering the EOF (`null`). Doing so correctly handles I/O errors that
117
+ * happen after reading some bytes and also both of the allowed EOF
118
+ * behaviors.
119
+ *
120
+ * @example
121
+ * ```typescript
122
+ * import { open, read, close, BaseDirectory } from "@tauri-apps/plugin-fs"
123
+ * // if "$APP/foo/bar.txt" contains the text "hello world":
124
+ * const file = await open("foo/bar.txt", { dir: BaseDirectory.App });
125
+ * const buf = new Uint8Array(100);
126
+ * const numberOfBytesRead = await file.read(buf); // 11 bytes
127
+ * const text = new TextDecoder().decode(buf); // "hello world"
128
+ * await close(file.rid);
129
+ * ```
130
+ *
131
+ * @since 2.0.0
132
+ */
133
+ async read(buffer) {
134
+ if (buffer.byteLength === 0) {
135
+ return 0;
136
+ }
137
+ const [data, nread] = await invoke("plugin:fs|read", {
138
+ rid: this.rid,
139
+ len: buffer.byteLength,
140
+ });
141
+ buffer.set(data);
142
+ return nread === 0 ? null : nread;
143
+ }
144
+ /**
145
+ * Seek sets the offset for the next `read()` or `write()` to offset,
146
+ * interpreted according to `whence`: `Start` means relative to the
147
+ * start of the file, `Current` means relative to the current offset,
148
+ * and `End` means relative to the end. Seek resolves to the new offset
149
+ * relative to the start of the file.
150
+ *
151
+ * Seeking to an offset before the start of the file is an error. Seeking to
152
+ * any positive offset is legal, but the behavior of subsequent I/O
153
+ * operations on the underlying object is implementation-dependent.
154
+ * It returns the number of cursor position.
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * import { open, seek, write, SeekMode, BaseDirectory } from '@tauri-apps/plugin-fs';
159
+ *
160
+ * // Given hello.txt pointing to file with "Hello world", which is 11 bytes long:
161
+ * const file = await open('hello.txt', { read: true, write: true, truncate: true, create: true, dir: BaseDirectory.App });
162
+ * await file.write(new TextEncoder().encode("Hello world"), { dir: BaseDirectory.App });
163
+ *
164
+ * // Seek 6 bytes from the start of the file
165
+ * console.log(await file.seek(6, SeekMode.Start)); // "6"
166
+ * // Seek 2 more bytes from the current position
167
+ * console.log(await file.seek(2, SeekMode.Current)); // "8"
168
+ * // Seek backwards 2 bytes from the end of the file
169
+ * console.log(await file.seek(-2, SeekMode.End)); // "9" (e.g. 11-2)
170
+ * ```
171
+ *
172
+ * @since 2.0.0
173
+ */
174
+ async seek(offset, whence) {
175
+ return invoke("plugin:fs|seek", {
176
+ rid: this.rid,
177
+ offset,
178
+ whence,
179
+ });
180
+ }
181
+ /**
182
+ * Returns a {@linkcode FileInfo } for this file.
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * import { open, fstat, BaseDirectory } from '@tauri-apps/plugin-fs';
187
+ * const file = await open("file.txt", { read: true, dir: BaseDirectory.App });
188
+ * const fileInfo = await fstat(file.rid);
189
+ * console.log(fileInfo.isFile); // true
190
+ * ```
191
+ *
192
+ * @since 2.0.0
193
+ */
194
+ async stat() {
195
+ const res = await invoke("plugin:fs|fstat", {
196
+ rid: this.rid,
197
+ });
198
+ return parseFileInfo(res);
199
+ }
200
+ /**
201
+ * Truncates or extends this file, to reach the specified `len`.
202
+ * If `len` is not specified then the entire file contents are truncated.
203
+ *
204
+ * @example
205
+ * ```typescript
206
+ * import { ftruncate, open, write, read, BaseDirectory } from '@tauri-apps/plugin-fs';
207
+ *
208
+ * // truncate the entire file
209
+ * const file = await open("my_file.txt", { read: true, write: true, create: true, dir: BaseDirectory.App });
210
+ * await ftruncate(file.rid);
211
+ *
212
+ * // truncate part of the file
213
+ * const file = await open("my_file.txt", { read: true, write: true, create: true, dir: BaseDirectory.App });
214
+ * await write(file.rid, new TextEncoder().encode("Hello World"));
215
+ * await ftruncate(file.rid, 7);
216
+ * const data = new Uint8Array(32);
217
+ * await read(file.rid, data);
218
+ * console.log(new TextDecoder().decode(data)); // Hello W
219
+ * ```
220
+ *
221
+ * @since 2.0.0
222
+ */
223
+ async truncate(len) {
224
+ return invoke("plugin:fs|ftruncate", {
225
+ rid: this.rid,
226
+ len,
227
+ });
228
+ }
229
+ /**
230
+ * Writes `p.byteLength` bytes from `p` to the underlying data stream. It
231
+ * resolves to the number of bytes written from `p` (`0` <= `n` <=
232
+ * `p.byteLength`) or reject with the error encountered that caused the
233
+ * write to stop early. `write()` must reject with a non-null error if
234
+ * would resolve to `n` < `p.byteLength`. `write()` must not modify the
235
+ * slice data, even temporarily.
236
+ *
237
+ * @example
238
+ * ```typescript
239
+ * import { open, write, close, BaseDirectory } from '@tauri-apps/plugin-fs';
240
+ * const encoder = new TextEncoder();
241
+ * const data = encoder.encode("Hello world");
242
+ * const file = await open("bar.txt", { write: true, dir: BaseDirectory.App });
243
+ * const bytesWritten = await write(file.rid, data); // 11
244
+ * await close(file.rid);
245
+ * ```
246
+ *
247
+ * @since 2.0.0
248
+ */
249
+ async write(data) {
250
+ return invoke("plugin:fs|write", {
251
+ rid: this.rid,
252
+ data: Array.from(data),
253
+ });
254
+ }
255
+ }
256
+ /**
257
+ * Creates a file if none exists or truncates an existing file and resolves to
258
+ * an instance of {@linkcode FileHandle }.
259
+ *
260
+ * @example
261
+ * ```typescript
262
+ * import { create, BaseDirectory } from "@tauri-apps/plugin-fs"
263
+ * const file = await create("foo/bar.txt", { dir: BaseDirectory.App });
264
+ * ```
265
+ *
266
+ * @since 2.0.0
267
+ */
268
+ async function create(path, options) {
269
+ if (path instanceof URL && path.protocol !== "file:") {
270
+ throw new TypeError("Must be a file URL.");
271
+ }
272
+ const rid = await invoke("plugin:fs|create", {
273
+ path: path instanceof URL ? path.toString() : path,
274
+ options,
275
+ });
276
+ return new FileHandle(rid);
277
+ }
278
+ /**
279
+ * Open a file and resolve to an instance of {@linkcode FileHandle}. The
280
+ * file does not need to previously exist if using the `create` or `createNew`
281
+ * open options. It is the callers responsibility to close the file when finished
282
+ * with it.
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * import { open, BaseDirectory } from "@tauri-apps/plugin-fs"
287
+ * const file = await open("foo/bar.txt", { read: true, write: true, dir: BaseDirectory.App });
288
+ * // Do work with file
289
+ * await close(file.rid);
290
+ * ```
291
+ *
292
+ * @since 2.0.0
293
+ */
294
+ async function open(path, options) {
295
+ if (path instanceof URL && path.protocol !== "file:") {
296
+ throw new TypeError("Must be a file URL.");
297
+ }
298
+ const rid = await invoke("plugin:fs|open", {
299
+ path: path instanceof URL ? path.toString() : path,
300
+ options,
301
+ });
302
+ return new FileHandle(rid);
303
+ }
304
+ /**
305
+ * Copies the contents and permissions of one file to another specified path, by default creating a new file if needed, else overwriting.
306
+ * @example
307
+ * ```typescript
308
+ * import { copyFile, BaseDirectory } from '@tauri-apps/plugin-fs';
309
+ * await copyFile('app.conf', 'app.conf.bk', { dir: BaseDirectory.App });
310
+ * ```
311
+ *
312
+ * @since 2.0.0
313
+ */
314
+ async function copyFile(fromPath, toPath, options) {
315
+ if ((fromPath instanceof URL && fromPath.protocol !== "file:") ||
316
+ (toPath instanceof URL && toPath.protocol !== "file:")) {
317
+ throw new TypeError("Must be a file URL.");
318
+ }
319
+ return invoke("plugin:fs|copy_file", {
320
+ fromPath: fromPath instanceof URL ? fromPath.toString() : fromPath,
321
+ toPath: toPath instanceof URL ? toPath.toString() : toPath,
322
+ options,
323
+ });
324
+ }
325
+ /**
326
+ * Creates a new directory with the specified path.
327
+ * @example
328
+ * ```typescript
329
+ * import { mkdir, BaseDirectory } from '@tauri-apps/plugin-fs';
330
+ * await mkdir('users', { dir: BaseDirectory.App });
331
+ * ```
332
+ *
333
+ * @since 2.0.0
334
+ */
335
+ async function mkdir(path, options) {
336
+ if (path instanceof URL && path.protocol !== "file:") {
337
+ throw new TypeError("Must be a file URL.");
338
+ }
339
+ return invoke("plugin:fs|mkdir", {
340
+ path: path instanceof URL ? path.toString() : path,
341
+ options,
342
+ });
343
+ }
344
+ /**
345
+ * Reads the directory given by path and returns an array of `DirEntry`.
346
+ * @example
347
+ * ```typescript
348
+ * import { readDir, BaseDirectory } from '@tauri-apps/plugin-fs';
349
+ * const dir = "users"
350
+ * const entries = await readDir('users', { dir: BaseDirectory.App });
351
+ * processEntriesRecursive(dir, entries);
352
+ * async function processEntriesRecursive(parent, entries) {
353
+ * for (const entry of entries) {
354
+ * console.log(`Entry: ${entry.name}`);
355
+ * if (entry.isDirectory) {
356
+ * const dir = parent + entry.name;
357
+ * processEntriesRecursive(dir, await readDir(dir, { dir: BaseDirectory.App }))
358
+ * }
359
+ * }
360
+ * }
361
+ * ```
362
+ *
363
+ * @since 2.0.0
364
+ */
365
+ async function readDir(path, options) {
366
+ if (path instanceof URL && path.protocol !== "file:") {
367
+ throw new TypeError("Must be a file URL.");
368
+ }
369
+ return invoke("plugin:fs|read_dir", {
370
+ path: path instanceof URL ? path.toString() : path,
371
+ options,
372
+ });
373
+ }
374
+ /**
375
+ * Reads and resolves to the entire contents of a file as an array of bytes.
376
+ * TextDecoder can be used to transform the bytes to string if required.
377
+ * @example
378
+ * ```typescript
379
+ * import { readFile, BaseDirectory } from '@tauri-apps/plugin-fs';
380
+ * const contents = await readFile('avatar.png', { dir: BaseDirectory.Resource });
381
+ * ```
382
+ *
383
+ * @since 2.0.0
384
+ */
385
+ async function readFile(path, options) {
386
+ if (path instanceof URL && path.protocol !== "file:") {
387
+ throw new TypeError("Must be a file URL.");
388
+ }
389
+ const arr = await invoke("plugin:fs|read_file", {
390
+ path: path instanceof URL ? path.toString() : path,
391
+ options,
392
+ });
393
+ return Uint8Array.from(arr);
394
+ }
395
+ /**
396
+ * Reads and returns the entire contents of a file as UTF-8 string.
397
+ * @example
398
+ * ```typescript
399
+ * import { readTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';
400
+ * const contents = await readTextFile('app.conf', { dir: BaseDirectory.App });
401
+ * ```
402
+ *
403
+ * @since 2.0.0
404
+ */
405
+ async function readTextFile(path, options) {
406
+ if (path instanceof URL && path.protocol !== "file:") {
407
+ throw new TypeError("Must be a file URL.");
408
+ }
409
+ return invoke("plugin:fs|read_text_file", {
410
+ path: path instanceof URL ? path.toString() : path,
411
+ options,
412
+ });
413
+ }
414
+ /**
415
+ * Returns an async {@linkcode AsyncIterableIterator} over the lines of a file as UTF-8 string.
416
+ * @example
417
+ * ```typescript
418
+ * import { readTextFileLines, BaseDirectory } from '@tauri-apps/plugin-fs';
419
+ * const lines = await readTextFileLines('app.conf', { dir: BaseDirectory.App });
420
+ * for await (const line of lines) {
421
+ * console.log(line);
422
+ * }
423
+ * ```
424
+ * You could also call {@linkcode AsyncIterableIterator.next} to advance the
425
+ * iterator so you can lazily read the next line whenever you want.
426
+ *
427
+ * @since 2.0.0
428
+ */
429
+ async function readTextFileLines(path, options) {
430
+ if (path instanceof URL && path.protocol !== "file:") {
431
+ throw new TypeError("Must be a file URL.");
432
+ }
433
+ const pathStr = path instanceof URL ? path.toString() : path;
434
+ return Promise.resolve({
435
+ path: pathStr,
436
+ rid: null,
437
+ async next() {
438
+ if (!this.rid) {
439
+ this.rid = await invoke("plugin:fs|read_text_file_lines", {
440
+ path: pathStr,
441
+ options,
442
+ });
443
+ }
444
+ const [line, done] = await invoke("plugin:fs|read_text_file_lines_next", { rid: this.rid });
445
+ // an iteration is over, reset rid for next iteration
446
+ if (done)
447
+ this.rid = null;
448
+ return {
449
+ value: done ? "" : line,
450
+ done,
451
+ };
452
+ },
453
+ [Symbol.asyncIterator]() {
454
+ return this;
455
+ },
456
+ });
457
+ }
458
+ /**
459
+ * Removes the named file or directory.
460
+ * If the directory is not empty and the `recursive` option isn't set to true, the promise will be rejected.
461
+ * @example
462
+ * ```typescript
463
+ * import { remove, BaseDirectory } from '@tauri-apps/plugin-fs';
464
+ * await remove('users/file.txt', { dir: BaseDirectory.App });
465
+ * await remove('users', { dir: BaseDirectory.App });
466
+ * ```
467
+ *
468
+ * @since 2.0.0
469
+ */
470
+ async function remove(path, options) {
471
+ if (path instanceof URL && path.protocol !== "file:") {
472
+ throw new TypeError("Must be a file URL.");
473
+ }
474
+ return invoke("plugin:fs|remove", {
475
+ path: path instanceof URL ? path.toString() : path,
476
+ options,
477
+ });
478
+ }
479
+ /**
480
+ * Renames (moves) oldpath to newpath. Paths may be files or directories.
481
+ * If newpath already exists and is not a directory, rename() replaces it.
482
+ * OS-specific restrictions may apply when oldpath and newpath are in different directories.
483
+ *
484
+ * On Unix, this operation does not follow symlinks at either path.
485
+ *
486
+ * @example
487
+ * ```typescript
488
+ * import { rename, BaseDirectory } from '@tauri-apps/plugin-fs';
489
+ * await rename('avatar.png', 'deleted.png', { dir: BaseDirectory.App });
490
+ * ```
491
+ *
492
+ * @since 2.0.0
493
+ */
494
+ async function rename(oldPath, newPath, options) {
495
+ if ((oldPath instanceof URL && oldPath.protocol !== "file:") ||
496
+ (newPath instanceof URL && newPath.protocol !== "file:")) {
497
+ throw new TypeError("Must be a file URL.");
498
+ }
499
+ return invoke("plugin:fs|rename", {
500
+ oldPath: oldPath instanceof URL ? oldPath.toString() : oldPath,
501
+ newPath: newPath instanceof URL ? newPath.toString() : newPath,
502
+ options,
503
+ });
504
+ }
505
+ /**
506
+ * Resolves to a {@linkcode FileInfo} for the specified `path`. Will always
507
+ * follow symlinks but will reject if the symlink points to a path outside of the scope.
508
+ *
509
+ * @example
510
+ * ```typescript
511
+ * import { stat, BaseDirectory } from '@tauri-apps/plugin-fs';
512
+ * const fileInfo = await stat("hello.txt", { dir: BaseDirectory.App });
513
+ * console.log(fileInfo.isFile); // true
514
+ * ```
515
+ *
516
+ * @since 2.0.0
517
+ */
518
+ async function stat(path, options) {
519
+ const res = await invoke("plugin:fs|stat", {
520
+ path: path instanceof URL ? path.toString() : path,
521
+ options,
522
+ });
523
+ return parseFileInfo(res);
524
+ }
525
+ /**
526
+ * Resolves to a {@linkcode FileInfo} for the specified `path`. If `path` is a
527
+ * symlink, information for the symlink will be returned instead of what it
528
+ * points to.
529
+ *
530
+ * @example
531
+ * ```typescript
532
+ * import { lstat, BaseDirectory } from '@tauri-apps/plugin-fs';
533
+ * const fileInfo = await lstat("hello.txt", { dir: BaseDirectory.App });
534
+ * console.log(fileInfo.isFile); // true
535
+ * ```
536
+ *
537
+ * @since 2.0.0
538
+ */
539
+ async function lstat(path, options) {
540
+ const res = await invoke("plugin:fs|lstat", {
541
+ path: path instanceof URL ? path.toString() : path,
542
+ options,
543
+ });
544
+ return parseFileInfo(res);
545
+ }
546
+ /**
547
+ * Truncates or extends the specified file, to reach the specified `len`.
548
+ * If `len` is `0` or not specified, then the entire file contents are truncated.
549
+ *
550
+ * @example
551
+ * ```typescript
552
+ * import { truncate, readFile, writeFile, BaseDirectory } from '@tauri-apps/plugin-fs';
553
+ * // truncate the entire file
554
+ * await truncate("my_file.txt", 0, { dir: BaseDirectory.App });
555
+ *
556
+ * // truncate part of the file
557
+ * let file = "file.txt";
558
+ * await writeFile(file, new TextEncoder().encode("Hello World"), { dir: BaseDirectory.App });
559
+ * await truncate(file, 7);
560
+ * const data = await readFile(file, { dir: BaseDirectory.App });
561
+ * console.log(new TextDecoder().decode(data)); // "Hello W"
562
+ * ```
563
+ *
564
+ * @since 2.0.0
565
+ */
566
+ async function truncate(path, len, options) {
567
+ if (path instanceof URL && path.protocol !== "file:") {
568
+ throw new TypeError("Must be a file URL.");
569
+ }
570
+ return invoke("plugin:fs|truncate", {
571
+ path: path instanceof URL ? path.toString() : path,
572
+ len,
573
+ options,
574
+ });
575
+ }
576
+ /**
577
+ * Write `data` to the given `path`, by default creating a new file if needed, else overwriting.
578
+ * @example
579
+ * ```typescript
580
+ * import { writeFile, BaseDirectory } from '@tauri-apps/plugin-fs';
581
+ *
582
+ * let encoder = new TextEncoder();
583
+ * let data = encoder.encode("Hello World");
584
+ * await writeFile('file.txt', data, { dir: BaseDirectory.App });
585
+ * ```
586
+ *
587
+ * @since 2.0.0
588
+ */
589
+ async function writeFile(path, data, options) {
590
+ if (path instanceof URL && path.protocol !== "file:") {
591
+ throw new TypeError("Must be a file URL.");
592
+ }
593
+ return invoke("plugin:fs|write_file", {
594
+ path: path instanceof URL ? path.toString() : path,
595
+ data: Array.from(data),
596
+ options,
597
+ });
598
+ }
599
+ /**
600
+ * Writes UTF-8 string `data` to the given `path`, by default creating a new file if needed, else overwriting.
601
+ @example
602
+ * ```typescript
603
+ * import { writeTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';
604
+ *
605
+ * await writeTextFile('file.txt', "Hello world", { dir: BaseDirectory.App });
606
+ * ```
607
+ *
608
+ * @since 2.0.0
609
+ */
610
+ async function writeTextFile(path, data, options) {
611
+ if (path instanceof URL && path.protocol !== "file:") {
612
+ throw new TypeError("Must be a file URL.");
613
+ }
614
+ return invoke("plugin:fs|write_text_file", {
615
+ path: path instanceof URL ? path.toString() : path,
616
+ data,
617
+ options,
618
+ });
619
+ }
620
+ /**
621
+ * Check if a path exists.
622
+ * @example
623
+ * ```typescript
624
+ * import { exists, BaseDirectory } from '@tauri-apps/plugin-fs';
625
+ * // Check if the `$APPDATA/avatar.png` file exists
626
+ * await exists('avatar.png', { dir: BaseDirectory.AppData });
627
+ * ```
628
+ *
629
+ * @since 2.0.0
630
+ */
631
+ async function exists(path, options) {
632
+ if (path instanceof URL && path.protocol !== "file:") {
633
+ throw new TypeError("Must be a file URL.");
634
+ }
635
+ return invoke("plugin:fs|exists", {
636
+ path: path instanceof URL ? path.toString() : path,
637
+ options,
638
+ });
639
+ }
640
+ async function unwatch(id) {
641
+ await invoke("plugin:fs|unwatch", { id });
642
+ }
643
+ /**
644
+ * Watch changes (after a delay) on files or directories.
645
+ *
646
+ * @since 2.0.0
647
+ */
648
+ async function watch(paths, cb, options) {
649
+ const opts = {
650
+ recursive: false,
651
+ delayMs: 2000,
652
+ ...options,
653
+ };
654
+ const watchPaths = Array.isArray(paths) ? paths : [paths];
655
+ for (const path of watchPaths) {
656
+ if (path instanceof URL && path.protocol !== "file:") {
657
+ throw new TypeError("Must be a file URL.");
658
+ }
659
+ }
660
+ const onEvent = new Channel();
661
+ onEvent.onmessage = cb;
662
+ const rid = await invoke("plugin:fs|watch", {
663
+ paths: watchPaths.map((p) => (p instanceof URL ? p.toString() : p)),
664
+ options: opts,
665
+ onEvent,
666
+ });
667
+ return () => {
668
+ void unwatch(rid);
669
+ };
670
+ }
671
+ /**
672
+ * Watch changes on files or directories.
673
+ *
674
+ * @since 2.0.0
675
+ */
676
+ async function watchImmediate(paths, cb, options) {
677
+ const opts = {
678
+ recursive: false,
679
+ ...options,
680
+ delayMs: null,
681
+ };
682
+ const watchPaths = Array.isArray(paths) ? paths : [paths];
683
+ for (const path of watchPaths) {
684
+ if (path instanceof URL && path.protocol !== "file:") {
685
+ throw new TypeError("Must be a file URL.");
686
+ }
687
+ }
688
+ const onEvent = new Channel();
689
+ onEvent.onmessage = cb;
690
+ const rid = await invoke("plugin:fs|watch", {
691
+ paths: watchPaths.map((p) => (p instanceof URL ? p.toString() : p)),
692
+ options: opts,
693
+ onEvent,
694
+ });
695
+ return () => {
696
+ void unwatch(rid);
697
+ };
698
+ }
699
+
700
+ export { FileHandle, SeekMode, copyFile, create, exists, lstat, mkdir, open, readDir, readFile, readTextFile, readTextFileLines, remove, rename, stat, truncate, watch, watchImmediate, writeFile, writeTextFile };