Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): stream server zip imports from the uploaded temp file

Elian Dorand6775f7d6db6
diff --git a/apps/server/src/routes/route_api.spec.ts b/apps/server/src/routes/route_api.spec.ts
index da24c45a22..c94ef02c72 100644
--- a/apps/server/src/routes/route_api.spec.ts
+++ b/apps/server/src/routes/route_api.spec.ts
@@ -12,25 +12,62 @@ function buildApp() {
const file = req.file;
res.json({
hasFile: !!file,
+ // Present only for the buffered (non-streamed) path; undefined when streamed from a path.
content: file?.buffer?.toString("utf-8"),
originalname: file?.originalname,
- // The unlink is awaited before the handler runs, so by now the temp file is already gone.
- tempStillExists: file?.path ? existsSync(file.path) : null
+ hasPath: !!file?.path,
+ // Whether the temp file is still on disk while the handler runs.
+ tempPresent: file?.path ? existsSync(file.path) : null
});
});
return app;
}
describe("importMiddlewareWithErrorHandling (disk storage)", () => {
- it("streams the upload to disk, exposes it as file.buffer, and removes the temp file", async () => {
+ it("streams a generic .zip from its temp path: no buffer, temp kept for the importer", async () => {
const res = await request(buildApp())
.post("/import")
- .attach("upload", Buffer.from("zip-bytes-here"), "vault.zip");
+ .attach("upload", Buffer.from("PK-zip-bytes"), "backup.zip");
expect(res.status).toBe(200);
- expect(res.body.content).toBe("zip-bytes-here");
- expect(res.body.originalname).toBe("vault.zip");
- expect(res.body.tempStillExists).toBe(false);
+ // Not buffered — the importer reads it in place via file.path.
+ expect(res.body.content).toBeUndefined();
+ expect(res.body.hasPath).toBe(true);
+ // The temp file is still present during the import (cleaned up after the response).
+ expect(res.body.tempPresent).toBe(true);
+ });
+
+ it("buffers a non-zip upload and removes the temp file before the handler", async () => {
+ const res = await request(buildApp())
+ .post("/import")
+ .attach("upload", Buffer.from("<en-export/>"), "notes.enex");
+
+ expect(res.status).toBe(200);
+ expect(res.body.content).toBe("<en-export/>");
+ expect(res.body.tempPresent).toBe(false);
+ });
+
+ it("buffers a .zip when a provider format tags it (e.g. notion), rather than streaming", async () => {
+ const res = await request(buildApp())
+ .post("/import")
+ .field("format", "notion")
+ .attach("upload", Buffer.from("notion-zip"), "export.zip");
+
+ expect(res.status).toBe(200);
+ // Tagged providers go through their buffer-based importer, so it's materialized + cleaned up.
+ expect(res.body.content).toBe("notion-zip");
+ expect(res.body.tempPresent).toBe(false);
+ });
+
+ it("buffers a .zip when explodeArchives is disabled (imported as a single file)", async () => {
+ const res = await request(buildApp())
+ .post("/import")
+ .field("explodeArchives", "false")
+ .attach("upload", Buffer.from("opaque-zip"), "thing.zip");
+
+ expect(res.status).toBe(200);
+ expect(res.body.content).toBe("opaque-zip");
+ expect(res.body.tempPresent).toBe(false);
});
it("proceeds to the handler when no file is uploaded", async () => {
diff --git a/apps/server/src/routes/route_api.ts b/apps/server/src/routes/route_api.ts
index 26c734e31a..cac34ee1be 100644
--- a/apps/server/src/routes/route_api.ts
+++ b/apps/server/src/routes/route_api.ts
@@ -225,15 +225,44 @@ export const importMiddlewareWithErrorHandling = function (req: express.Request,
next(err);
return;
}
- void materializeUploadedImport(req.file, next);
+
+ const file = req.file;
+ if (file?.path && isStreamableZipUpload(req)) {
+ // Generic `.zip` import: hand the importer the temp file's path so the archive is read in
+ // place per entry (the route prefers `file.path`), never buffered. Keep the temp file alive
+ // through the import and delete it once the response is done (or the connection drops).
+ const tempPath = file.path;
+ res.on("close", () => void rm(tempPath, { force: true }).catch(() => {}));
+ next();
+ return;
+ }
+
+ void materializeUploadedImport(file, next);
});
};
/**
- * diskStorage gives us `file.path` rather than `file.buffer`. The shared core import handlers still consume
- * `file.buffer`, so read the temp file back into it and delete the temp file before handing off — the unlink
- * is awaited so nothing is left behind even if the handler later throws. (Step 2 will stream importers
- * straight from the path instead of re-buffering here.)
+ * Whether this upload is a plain `.zip` the generic zip importer will read — the case worth streaming from
+ * disk. Tagged provider uploads (notion/keep/anytype/obsidian) and non-zip files go through buffer-based
+ * importers, so they take the {@link materializeUploadedImport} path instead. Kept in sync with the
+ * generic-zip branch in the core import route (routes/api/import.ts).
+ */
+function isStreamableZipUpload(req: express.Request): boolean {
+ const body = req.body as Record<string, string> | undefined;
+ if (body?.format) {
+ return false;
+ }
+ if (body?.explodeArchives === "false") {
+ return false;
+ }
+ return req.file?.originalname?.toLowerCase().endsWith(".zip") ?? false;
+}
+
+/**
+ * For uploads that aren't streamed from a path (tagged providers, non-zip files, the browser): diskStorage
+ * gives us `file.path` rather than `file.buffer`, but those importers consume `file.buffer`, so read the
+ * temp file back into it and delete the temp file before handing off — the unlink is awaited so nothing is
+ * left behind even if the handler later throws.
*/
async function materializeUploadedImport(file: Express.Multer.File | undefined, next: express.NextFunction) {
if (!file?.path) {
diff --git a/packages/trilium-core/src/routes/api/import.ts b/packages/trilium-core/src/routes/api/import.ts
index 2f158f7ad6..0e56a8e0d7 100644
--- a/packages/trilium-core/src/routes/api/import.ts
+++ b/packages/trilium-core/src/routes/api/import.ts
@@ -76,7 +76,11 @@ async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>)
// Trilium export by extension alone; the Obsidian import dialog tags the upload to route it here.
note = await obsidianImportService.importObsidian(taskContext, file.buffer, parentNote, file.originalname);
} else if (extension === ".zip" && options.explodeArchives && typeof file.buffer !== "string") {
- note = await zipImportService.importZip(taskContext, file.buffer, parentNote);
+ // Prefer reading the archive straight from the uploaded temp file (server disk storage) so a
+ // multi-GB zip is streamed per entry — never held in one buffer, and free of fs.readFile's
+ // ~2 GiB ceiling. Falls back to the buffer when there's no path (the browser/WASM upload).
+ const zipSource = file.path ? { path: file.path } : file.buffer;
+ note = await zipImportService.importZip(taskContext, zipSource, parentNote);
} else if (extension === ".opml" && options.explodeArchives) {
const importResult = await opmlImportService.importOpml(taskContext, file.buffer, parentNote);
if (!Array.isArray(importResult)) {
diff --git a/packages/trilium-core/src/services/import/common.ts b/packages/trilium-core/src/services/import/common.ts
index 114f529458..2d37ef6ae0 100644
--- a/packages/trilium-core/src/services/import/common.ts
+++ b/packages/trilium-core/src/services/import/common.ts
@@ -2,4 +2,10 @@ export interface File {
originalname: string;
mimetype: string;
buffer: string | Buffer | Uint8Array;
+ /**
+ * Filesystem path of the uploaded file when it was streamed to disk (server multer disk storage).
+ * Lets a zip be read in place instead of buffering it; absent for the browser/WASM upload, which
+ * only has `buffer`.
+ */
+ path?: string;
}