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