> For the complete documentation index, see [llms.txt](https://developer.vario-software.de/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.vario-software.de/documentation/scripting/local-link-transform-scripts.md).

# Local Link Transform Scripts

Convert, split or rename files in VARIO Local Link before a watch folder uploads them to the DMS.

A **transform script** is a Node.js module that VARIO Local Link runs on every file a watch folder picks up, before the file is uploaded to the DMS. Use it to fix an encoding, split one file into several, rename a file or convert a format the import cannot read.

Transform scripts are not VARIO Cloud scripts. They do not run on the server, have no `ctx` and no access to the VARIO Cloud services. For server-side processing after the upload, link the DMS document type to an automated import or script processing (see [Batch Processing](https://developer.vario-software.de/documentation/scripting/batch-processing.md)).

***

## Runtime

| Aspect            | Behaviour                                                                                                                                     |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| **Engine**        | The Node.js process of VARIO Local Link (Node 24), not the GraalJS engine of VARIO Cloud scripts                                              |
| **Module format** | CommonJS. `module.exports` must be a function.                                                                                                |
| **Rights**        | Those of the account the Local Link service runs under. The script can read and write files, start processes and open network connections.    |
| **Modules**       | Node built-ins (`fs`, `path`, `zlib`, …) and any package installed next to the script with `npm install`                                      |
| **Reloading**     | The script file is reloaded when its modification time changes. Helper modules loaded with `require()` stay cached until Local Link restarts. |

{% hint style="warning" %}
**Treat the script like a program on the server**

A transform script runs with the full rights of the Local Link service. Store it in a folder only administrators can write to.
{% endhint %}

***

## Setup

1. Save the script as a `.js` file on the machine running Local Link, e.g. `C:\VARIO\transform\csv-to-utf8.js`.
2. In Local Link, open **Datentransfer → Datenimporte → Ordner überwachen** and edit the watch folder.
3. Enter the absolute path of the file in **Transform-Skript (optional)** and save.

From now on, every file the watch folder picks up passes through the script. Watch folders without a script upload the file unchanged.

***

## Input

The function receives one object:

| Property   | Type          | Description                                                                  |
| ---------- | ------------- | ---------------------------------------------------------------------------- |
| `buffer`   | `Buffer`      | Content of the source file                                                   |
| `path`     | `string`      | Path of the copy in the Local Link queue, not the path in the watched folder |
| `filename` | `string`      | Original file name, e.g. `orders_2026-10-06.csv`                             |
| `signal`   | `AbortSignal` | Aborted when the upload is cancelled or Local Link shuts down                |

Use `path` to stream large files instead of working on `buffer`.

***

## Return Values

A script can return a single file, a list of files or stream files one by one.

| Form              | Return value                                                      | Use for                                                               |
| ----------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------- |
| **Single file**   | `{ buffer, filename, mimeType? }`                                 | Converting or renaming one file                                       |
| **Several files** | `{ files: [{ buffer, filename, mimeType? }, …] }`                 | Splitting a file into a few parts                                     |
| **Streaming**     | `async function*` that `yield`s `{ buffer, filename, mimeType? }` | Splitting very large files; only one part is held in memory at a time |

| Field      | Rule                                                                             |
| ---------- | -------------------------------------------------------------------------------- |
| `buffer`   | Must be a Node `Buffer`. Convert a `Uint8Array` with `Buffer.from(...)`.         |
| `filename` | Non-empty string. Becomes the file name and the description of the DMS document. |
| `mimeType` | Optional. Sent as the content type of the upload.                                |

At least one file must be returned.

***

## What Happens With the Result

* **Each returned file becomes its own DMS document.** DMS document type, tags and the link to an automated import are taken from the watch folder, so every part is processed like a file that was dropped into the folder on its own.
* **Fixed document (*****Fortlaufende Revision*****):** If the watch folder adds new revisions to one fixed DMS document, the script may return exactly one file. A second file fails with `transform_multi_output_not_compatible_with_fixed_dmsResource`.
* **Crash safety:** The parts are written to `<import directory>/sub-queue/<key>/` together with a `manifest.json` before the upload starts. If Local Link stops after the script has finished, the upload resumes with the stored parts and the script does not run again. If it stops while the script is still running, the parts are discarded and the script runs again.
* **Partial failure:** If some parts fail to upload, the source file is moved to **Fehlgeschlagen** with the error `partial_upload_failed: 2/5 files failed`. **Fehlgeschlagene Sub-Files wiederholen** uploads only the failed parts again, without running the script a second time.

***

## Errors

| Error                                                          | Cause                                                                         |
| -------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `transform_script_not_found: <path>`                           | No file at the configured path                                                |
| `transform_script_must_export_function`                        | `module.exports` is not a function                                            |
| `transform_script_invalid_result`                              | The script returned nothing, or a single file without a `Buffer` or file name |
| `transform_script_empty_files`                                 | `files` is empty or the generator yielded nothing                             |
| `transform_script_invalid_file_buffer_at_<i>`                  | Part number `<i>` (0-based) has no `Buffer`                                   |
| `transform_script_invalid_file_filename_at_<i>`                | Part number `<i>` has no file name                                            |
| `transform_multi_output_not_compatible_with_fixed_dmsResource` | More than one part for a watch folder with a fixed DMS document               |

Errors thrown by the script and the errors above are reported as `transform_script_failed: <message>`. The source file then appears under **Fehlgeschlagen** and can be retried there.

***

## Examples

### Convert a Latin-1 CSV to UTF-8

```javascript
module.exports = async ({ buffer, filename }) => ({
  buffer: Buffer.from(buffer.toString('latin1'), 'utf8'),
  filename: filename.replace(/\.csv$/i, '.utf8.csv'),
  mimeType: 'text/csv',
});
```

### Split a CSV into one file per order number

```javascript
module.exports = async ({ buffer, filename }) => {
  const [header, ...rows] = buffer.toString('utf8').split(/\r?\n/).filter(Boolean);
  const orderColumn = header.split(';').indexOf('order_number');
  const groups = new Map();

  for (const row of rows) {
    const key = row.split(';')[orderColumn];
    if (!groups.has(key)) groups.set(key, [header]);
    groups.get(key).push(row);
  }

  const base = filename.replace(/\.csv$/i, '');

  return {
    files: [...groups].map(([order, lines]) => ({
      buffer: Buffer.from(lines.join('\r\n') + '\r\n', 'utf8'),
      filename: `${base}_${order}.csv`,
      mimeType: 'text/csv',
    })),
  };
};
```

### Stream a large file in chunks

```javascript
const { createReadStream } = require('fs');
const readline = require('readline');

const CHUNK_SIZE = 10000;

module.exports = async function* ({ path, filename, signal }) {
  const lines = readline.createInterface({ input: createReadStream(path), crlfDelay: Infinity });
  const base = filename.replace(/\.csv$/i, '');
  let header;
  let chunk = [];
  let part = 0;

  for await (const line of lines) {
    if (signal?.aborted) return;
    if (header === undefined) { header = line; continue; }

    chunk.push(line);

    if (chunk.length === CHUNK_SIZE) {
      part += 1;
      yield { buffer: Buffer.from([header, ...chunk].join('\r\n') + '\r\n'), filename: `${base}_${part}.csv` };
      chunk = [];
    }
  }

  if (chunk.length) {
    part += 1;
    yield { buffer: Buffer.from([header, ...chunk].join('\r\n') + '\r\n'), filename: `${base}_${part}.csv` };
  }
};
```

### Split a PDF into single pages

Run `npm install pdf-lib` in the folder of the script first.

```javascript
const { PDFDocument } = require('pdf-lib');

module.exports = async function* ({ buffer, filename }) {
  const source = await PDFDocument.load(buffer);
  const base = filename.replace(/\.pdf$/i, '');

  for (let i = 0; i < source.getPageCount(); i += 1) {
    const page = await PDFDocument.create();
    const [copy] = await page.copyPages(source, [i]);
    page.addPage(copy);

    yield {
      buffer: Buffer.from(await page.save()),
      filename: `${base}_page_${i + 1}.pdf`,
      mimeType: 'application/pdf',
    };
  }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developer.vario-software.de/documentation/scripting/local-link-transform-scripts.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
