> For the complete documentation index, see [llms.txt](https://docs.sacruda.nl/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sacruda.nl/developers/sacruda-apis/the-filesystem.md).

# The filesystem

For reading and writing files, Sacruda has the **Filesystem** kernel module. This module is accessible globally (defined as the `fs` constant) or as a property in every process (`Process.fs`). You can use this module to perform various filesystem operations on any mounted drive.

### Dispatches

As discussed on the [Built-in utilities](https://docs.sacruda.nl/developers/sacruda-apis/built-in-utilities.md) (namely `util.onFileChange` and `util.onFolderChange`), the Sacruda filesystem dispatches changes to the filesystem across the operating system for other applications to listen to.

Sacruda does this internally in various different ways, but what you need to know is that **any** `dispatch` argument in the Filesystem kernel module defaults to `true`. Set it to `false` to prevent Sacruda from informing the rest of the operating system of the operation. This is handy if you want to perform a bunch of filesystem operations without updating everything else at the same time.&#x20;

If you want to perform a bunch of filesystem operations sequentially, disable dispatch on all of them, and then manually dispatch the changes you've made using:

```javascript
dispatch.dispatch("fs-flush-folder", path); // for folders
dispatch.dispatch("fs-flush-file", path); // for files
```

### Reading a file into RAM

To read a file, call `fs.readFile` , passing in the path to the file you want to read:

```javascript
const contents = await fs.readFile("T:/test.txt");
```

{% hint style="info" %}
This method is asynchronous: it has to be awaited.
{% endhint %}

`readFile` returns an `ArrayBuffer` or undefined, depending on whether or not the file exists. You can then use `convert.arrayToText` to convert this array buffer to a string. For more information, visit the [Data conversion](https://docs.sacruda.nl/developers/sacruda-apis/data-conversion.md) page.

### Writing a file

Similar to `readFile`, `writeFile` takes a path and some content to write to it. Here's the type for the `writeFile` method:

```typescript
writeFile(path: string, data: Blob, onProgress?: FilesystemProgressCallback, dispatch?: boolean): Promise<boolean>;
```

{% hint style="info" %}
This method is asynchronous: it has to be awaited.
{% endhint %}

The onProgress argument is the same across all filesystem operations. See [Filesystem progress](#filesystem-progress) for more information.

### Creating a directory

To create a directory, call `fs.createDirectory`, passing in the path you want to create. Recursive creations aren't supported, though might work depending on the drive. The function returns `true` if the folder was created, or `false` if it wasn't.

```typescript
createDirectory(path: string, dispatch?: boolean): Promise<boolean>;
```

{% hint style="info" %}
This method is asynchronous: it has to be awaited.
{% endhint %}

### Moving and copying items

{% hint style="danger" %}
The `moveItem` and `copyItem` functions are very limited at this time. They take **one** source and **one** destination. The source can either be a file or a folder, and the destination indicates the directory the source will be copied to. You also cannot copy or move items across drives. This functionality will be implemented in the future.
{% endhint %}

To move an item, call `fs.moveItem`:

```typescript
moveItem(source: string, destination: string, dispatch?: boolean): Promise<boolean>;
```

{% hint style="info" %}
This method is asynchronous: it has to be awaited.
{% endhint %}

***

To copy an item, call `fs.copyItem`:

```typescript
copyItem(source: string, destination: string, dispatch?: boolean): Promise<boolean>;
```

{% hint style="info" %}
This method is asynchronous: it has to be awaited.
{% endhint %}

### Direct file access

If you need a link to a file that you can use directly in an HTML element like an image or an audio fragment, call `fs.direct`:

```typescript
direct(path: string): Promise<string | undefined>;
```

{% hint style="info" %}
This method is asynchronous: it has to be awaited.
{% endhint %}

This will return an accessor link generated by the backend. File accessors are stored in the database, linked to your user. Accessor links expire after 24 hours. If you call `fs.direct` on the same link, the same accessor will be returned instead of a new one. Here's an example of a direct file access:

<pre class="language-javascript"><code class="lang-javascript">const image = document.createElement("img");

img.src = await fs.direct(util.join(<a data-footnote-ref href="#user-content-fn-1">workingDirectory</a>, "minesweeper.png"));

this.<a data-footnote-ref href="#user-content-fn-2">getBody</a>()?.append(img);
</code></pre>

### Filesystem progress

When performing a large file operation, like uploading a file or mounting a drive, you're advised to keep the user informed using the `FilesystemProgressCallback`. Before you start the operation, creata an FsProgress instance, and then stop it when it's done. Take this example from the **Writer** app:

```javascript
const prog = await daemon.files.FileProgress({
  type: "size",
  caption: `Reading file`,
  subtitle: path,
  icon: TextMimeIcon,
}, this.pid);

const contents = await fs.readFile(path, (progress) => {
  prog.setWait(false);
  prog.setWork(true);
  prog.show();
  prog.setMax(progress.max);
  prog.setDone(progress.value);
});

prog.stop();
```

Do note that this snippet includes variables that aren't accessible, like `path` and `TextMimeIcon`. As you can see I'm calling several properties of the `prog` variable. These are functions you can call to change the file progress. The properties are [here](#properties-of-a-fileprogress).

{% hint style="danger" %}
The `FileProgress` method is asynchronous: it has to be awaited to prevent conflicts in the proces stack.
{% endhint %}

{% hint style="warning" %}
You might have to make the total value one value higher than the completed value to prevent the file progress from automatically closing if there are multiple file operations you want to display using one file progress. Keep that in mind.
{% endhint %}

{% hint style="info" %}
When you spawn a file progress, it'll be *primed*: it won't display immediately. You have to first call the `show`  function before the progress dialog actually spawns and is displayed to the user.
{% endhint %}

#### Properties of a FileProgress

<table><thead><tr><th width="169">Parameter</th><th>Type</th><th>input type?</th><th>Description</th></tr></thead><tbody><tr><td><code>progress</code></td><td>Svelte Store</td><td>-</td><td>Returns the current state of the file progress</td></tr><tr><td><code>mutateMax</code></td><td>Function</td><td><code>number</code></td><td>Adds or subtracts from the total value</td></tr><tr><td><code>mutDone</code></td><td>Function</td><td><code>number</code></td><td>Adds or subtracts from the completed value</td></tr><tr><td><code>updateCaption</code></td><td>Function</td><td><code>string</code></td><td>Changes the file progress' caption.</td></tr><tr><td><code>updSub</code></td><td>Function</td><td><code>string</code></td><td>Changes the subtitle below the caption</td></tr><tr><td><code>setMax</code></td><td>Function</td><td><code>number</code></td><td>Sets the total value</td></tr><tr><td><code>setDone</code></td><td>Function</td><td><code>number</code></td><td>Sets the completed value</td></tr><tr><td><code>setWait</code></td><td>Function</td><td><code>boolean</code></td><td>Turns on or off the "wait" indicator</td></tr><tr><td><code>setWork</code></td><td>Function</td><td><code>boolean</code></td><td>Turns on or off the <code>working</code> indicator</td></tr><tr><td><code>mutErr</code></td><td>Function</td><td><code>string</code></td><td>Appends an error to the list of errors</td></tr><tr><td><code>stop</code></td><td>Function</td><td>-</td><td>Stops the file progress</td></tr><tr><td><code>show</code> </td><td>Function</td><td>-</td><td>Shows the file progress (it's hidden initially)</td></tr><tr><td><code>setCancel</code></td><td>Function</td><td>function or undefined</td><td>Gives the <code>cancel</code> button an action, or disables it</td></tr><tr><td><code>setType</code></td><td>Function</td><td><code>"none" | "quantity" | "size"</code></td><td>Sets the type of file progress you're displaying.</td></tr></tbody></table>

### Uploading files

For uploading files, Sacruda has yet another method in the Filesystem kernel module you can access, named `uploadFiles`, which is basically just a glorified wrapper for an `input[type="file"]`. Here's the syntax for it:

<pre class="language-typescript"><code class="lang-typescript"><strong>uploadFiles(
</strong>  target: string,
  accept?: string,
  multiple?: boolean,
  onProgress?: FilesystemProgressCallback
): Promise&#x3C;UploadReturn>;
</code></pre>

`target` specifies the directory you want to upload to, `accept` is the same as the DOM's [accept](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/accept) attribute, `multiple` specifies if the host operating system's file picker should allow a single file or multiple files for uploading. Finally, theres `onProgress`, which is the same as any other progress callback in this kernel module. Learn more about filesystem progress [here](#filesystem-progress).

{% hint style="info" %}
`uploadFiles` is forced to wait 100 milliseconds between file operations to prevent overloading the server. This doesn't mean that the server is weak, just that it could get stressed out if e.g. 50 people are each uploading 50 files at the same time. This delay is just some breathing room.
{% endhint %}

[^1]: `workingDirectory` is a global that indicates the installation directory of the app

[^2]: `getBody` is part of the `AppProcess` class and can be used to get the HTML body of your app
