Skip to content

Build your personal knowledge base with Trilium Notes

fix(server): keep removing temp files after a failure

Elian Doran944c381ea7c0
diff --git a/apps/server/src/routes/api/files.spec.ts b/apps/server/src/routes/api/files.spec.ts
index bcddc11032..96d9792fee 100644
--- a/apps/server/src/routes/api/files.spec.ts
+++ b/apps/server/src/routes/api/files.spec.ts
@@ -3,7 +3,7 @@ import { becca, cls, note_service as noteService, ValidationError } from "@trili
import type { Request } from "express";
import fs from "fs";
import path from "path";
-import { beforeAll, describe, expect, it } from "vitest";
+import { beforeAll, describe, expect, it, vi } from "vitest";
import dataDirs from "../../services/data_dir.js";
import filesRoute from "./files.js";
@@ -91,5 +91,26 @@ describe("Files API", () => {
cleanup?.(0);
expect(fs.existsSync(tmpFilePath)).toBe(false);
});
+
+ it("removes the other temp files when one cannot be removed", () => {
+ const locked = cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId }))).tmpFilePath;
+ const other = cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId }))).tmpFilePath;
+ const rmSync = fs.rmSync;
+ const spy = vi.spyOn(fs, "rmSync").mockImplementation((filePath, options) => {
+ if (filePath === locked) {
+ throw new Error("EBUSY: resource busy or locked");
+ }
+ rmSync(filePath, options);
+ });
+ const cleanup = process.listeners("exit").find((listener) => listener.name === "removeTemporaryFiles");
+
+ try {
+ expect(() => cleanup?.(0)).not.toThrow();
+ expect(fs.existsSync(other)).toBe(false);
+ } finally {
+ spy.mockRestore();
+ fs.rmSync(locked, { force: true });
+ }
+ });
});
});
diff --git a/apps/server/src/routes/api/files.ts b/apps/server/src/routes/api/files.ts
index ba5ec4ff49..8ecfcffefc 100644
--- a/apps/server/src/routes/api/files.ts
+++ b/apps/server/src/routes/api/files.ts
@@ -61,7 +61,11 @@ function saveToTmpDir(fileName: string, content: string | Uint8Array, entityType
function removeTemporaryFiles() {
for (const filePath of createdTemporaryFiles) {
- fs.rmSync(filePath, { force: true });
+ try {
+ fs.rmSync(filePath, { force: true });
+ } catch {
+ // On Windows, an editor that still holds the file open makes `rmSync()` throw.
+ }
}
}