Skip to content

Build your personal knowledge base with Trilium Notes

client/setup/backup data: improve UI

Adorian Dorane82e72b587da
diff --git a/apps/client/src/setup_existing.css b/apps/client/src/setup_existing.css
index f7199d9d2a..152ee6718a 100644
--- a/apps/client/src/setup_existing.css
+++ b/apps/client/src/setup_existing.css
@@ -5,6 +5,10 @@
}
}
+.page.existing-data .existing-data-choices .tn-card-section {
+ padding-block: 12px;
+}
+
/* The wait while a backup is written, centred under the icon like the restore's own steps. */
.page.existing-data-backing-up .existing-data-progress {
display: flex;
@@ -39,24 +43,20 @@
}
}
-.page.existing-data-backed-up .existing-data-facts {
- display: grid;
- grid-template-columns: auto 1fr;
- gap: 8px 16px;
- margin: 0;
-
- dt {
- color: var(--muted-text-color);
- font-weight: normal;
+.page.existing-data-backed-up {
+ /* A name and a path have no spaces to break at, and both are shown in full: they may not be
+ readable anywhere else once the database holding the custom backup location is gone. */
+ .existing-data-file-name,
+ .existing-data-path {
+ overflow-wrap: anywhere;
+ text-align: right;
}
- dd {
- margin: 0;
+ .existing-data-path-link {
+ cursor: pointer;
}
- /* A path has no spaces to break at and is shown in full, since it may not be readable anywhere
- else once the database holding the custom backup directory is gone. */
- .existing-data-path {
- overflow-wrap: anywhere;
+ .existing-data-actions {
+ justify-content: center;
}
}
diff --git a/apps/client/src/setup_existing.spec.tsx b/apps/client/src/setup_existing.spec.tsx
index 4522454e06..b214457f97 100644
--- a/apps/client/src/setup_existing.spec.tsx
+++ b/apps/client/src/setup_existing.spec.tsx
@@ -13,11 +13,24 @@ const serverMock = vi.hoisted(() => ({
}));
vi.mock("./services/server", () => ({ default: serverMock }));
+const openMock = vi.hoisted(() => ({
+ download: vi.fn(),
+ getUrlForDownload: vi.fn((url: string) => `/${url}`)
+}));
+vi.mock("./services/open", () => ({ default: openMock }));
+
+const electronMock = vi.hoisted(() => ({ isElectron: vi.fn(() => false), openPath: vi.fn() }));
+vi.mock("./services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./services/utils")>()),
+ isElectron: () => electronMock.isElectron()
+}));
+
import ExistingData from "./setup_existing";
const BACKUP = {
fileName: "Backup 2026-08-07 10-32-21.tnbackup",
filePath: "/mnt/usb/trilium/Backup 2026-08-07 10-32-21.tnbackup",
+ directoryPath: "/mnt/usb/trilium",
fileSize: 209715200,
encrypted: false
};
@@ -55,6 +68,10 @@ beforeEach(() => {
serverMock.post.mockReset().mockResolvedValue(undefined);
serverMock.postWithTimeout.mockReset().mockResolvedValue(undefined);
serverMock.get.mockClear();
+ openMock.download.mockClear();
+ electronMock.isElectron.mockReset().mockReturnValue(false);
+ electronMock.openPath.mockClear();
+ window.electronApi = undefined;
});
afterEach(() => {
@@ -75,6 +92,24 @@ describe("choosing what happens to the existing knowledge base", () => {
expect(button("setup.continue")?.disabled).toBe(false);
});
+ it("gives each answer a segment of its own, and keeps them exclusive", async () => {
+ renderScreens();
+ await settle();
+
+ expect(container.querySelectorAll(".existing-data-choices .tn-card-section")).toHaveLength(2);
+
+ choose("back-up");
+ await settle();
+ choose("delete");
+ await settle();
+
+ const checked = [ ...container.querySelectorAll<HTMLInputElement>("input[type=radio]") ]
+ .filter((radio) => radio.checked)
+ .map((radio) => radio.value);
+ // Two groups as far as the browser is concerned, one answer as far as the screen is.
+ expect(checked).toEqual([ "delete" ]);
+ });
+
it("warns about erasure only once erasure is what was chosen", async () => {
renderScreens();
await settle();
@@ -134,7 +169,9 @@ describe("backing it up first", () => {
// The path in full: the option holding a custom backup directory is in the database that is
// about to go, so this may be the last chance to read it.
expect(container.textContent).toContain(BACKUP.fileName);
- expect(container.textContent).toContain(BACKUP.filePath);
+ // The folder, not the whole path: the file name is on the line above it.
+ expect(container.textContent).toContain(BACKUP.directoryPath);
+ expect(container.textContent).not.toContain(BACKUP.filePath);
expect(container.textContent).toContain("200 MiB");
expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
@@ -158,13 +195,38 @@ describe("backing it up first", () => {
button("setup.continue")?.click();
await settle();
+ // Nothing to show yet, so the spinner stands in for the bar.
+ expect(container.querySelector(".spinner-border")).not.toBeNull();
+
await vi.advanceTimersByTimeAsync(1000);
expect(container.querySelector("progress")?.value).toBeCloseTo(0.42);
expect(container.textContent).toContain("42%");
+ // ...and steps aside once there is one, rather than the two competing.
+ expect(container.querySelector(".spinner-border")).toBeNull();
resolveBackup(BACKUP);
});
+ it("saves a copy wherever the user says, and opens the folder on the desktop", async () => {
+ electronMock.isElectron.mockReturnValue(true);
+ window.electronApi = { shell: { openPath: electronMock.openPath } } as never;
+ serverMock.postWithTimeout.mockResolvedValue(BACKUP);
+ renderScreens();
+ await settle();
+
+ choose("back-up");
+ await settle();
+ button("setup.continue")?.click();
+ await settle();
+
+ container.querySelector<HTMLAnchorElement>(".existing-data-path-link")?.click();
+ expect(electronMock.openPath).toHaveBeenCalledWith(BACKUP.directoryPath);
+
+ button("setup.existing-data-save-as")?.click();
+ expect(openMock.download).toHaveBeenCalledWith(
+ expect.stringContaining(encodeURIComponent(BACKUP.filePath)));
+ });
+
it("says to keep the backup password where the backup needs one", async () => {
serverMock.postWithTimeout.mockResolvedValue({ ...BACKUP, encrypted: true });
renderScreens();
diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsx
index a6c9d2e92c..1348575a35 100644
--- a/apps/client/src/setup_existing.tsx
+++ b/apps/client/src/setup_existing.tsx
@@ -3,12 +3,13 @@ import "./setup_existing.css";
import type { SetupExistingBackup } from "@triliumnext/commons";
import { useEffect, useState } from "preact/hooks";
-import { formatSize } from "./services/utils";
import { t } from "./services/i18n";
+import open from "./services/open";
import server from "./services/server";
+import { formatSize, isElectron } from "./services/utils";
import Admonition from "./widgets/react/Admonition";
import Button from "./widgets/react/Button";
-import { Card, CardSection } from "./widgets/react/Card";
+import { Card, CardOption, CardSection } from "./widgets/react/Card";
import FormRadioGroup from "./widgets/react/FormRadioGroup";
import Icon from "./widgets/react/Icon";
import SetupPage from "./widgets/react/SetupPage";
@@ -31,6 +32,11 @@ import SlidePages from "./widgets/react/SlidePages";
/** What the user decided to do with the database that is already here. */
type Choice = "back-up" | "delete";
+const CHOICES: { value: Choice; label: string }[] = [
+ { value: "back-up", label: "setup.existing-data-back-up" },
+ { value: "delete", label: "setup.existing-data-delete" }
+];
+
/** The three screens, in the order they can be reached, which is also the order they slide in. */
type Step = "choice" | "backing-up" | "backed-up";
const STEP_ORDER: Step[] = [ "choice", "backing-up", "backed-up" ];
@@ -185,18 +191,20 @@ export function ExistingDataChoice({ error, errorId, onBackUp, onDelete, onCance
</>
}
>
- <Card>
- <CardSection>
- <FormRadioGroup
- name="existing-data-choice"
- currentValue={choice ?? ""}
- onChange={(value) => setChoice(value as Choice)}
- values={[
- { value: "back-up", label: t("setup.existing-data-back-up") },
- { value: "delete", label: t("setup.existing-data-delete") }
- ]}
- />
- </CardSection>
+ <Card className="existing-data-choices">
+ {/* A segment each, rather than two rows in one: this is the question the whole screen
+ is for, and one of the answers erases a knowledge base. Which is checked is held
+ here rather than by the browser's own grouping, so the two stay exclusive. */}
+ {CHOICES.map(({ value, label }) => (
+ <CardSection key={value}>
+ <FormRadioGroup
+ name="existing-data-choice"
+ currentValue={choice ?? ""}
+ onChange={(chosen) => setChoice(chosen as Choice)}
+ values={[ { value, label: t(label) } ]}
+ />
+ </CardSection>
+ ))}
</Card>
{choice === "delete" && (
@@ -239,12 +247,13 @@ export function ExistingDataBackingUp() {
>
<div class="existing-data-progress">
<div class="existing-data-progress-message">
- <span class="spinner-border" role="status" aria-hidden="true" />
+ {/* The spinner is what stands in for a bar until the writer has said anything.
+ Once the bar is there it has nothing left to add, and two things moving at
+ once only compete. */}
+ {fraction === null && <span class="spinner-border" role="status" aria-hidden="true" />}
<span>{t("setup.existing-data-backing-up-message")}</span>
</div>
- {/* Only once the writer has said something. Until then there is nothing to draw, and
- an empty bar that never moves says less than no bar at all. */}
{fraction !== null && (
<div class="existing-data-progress-bar">
<progress value={fraction} max={1} />
@@ -285,17 +294,24 @@ export function ExistingDataBackedUp({ backup, onContinue, onCancel }: {
}
>
<Card>
- <CardSection>
- <dl class="existing-data-facts">
- <dt>{t("setup.existing-data-file-name")}</dt>
- <dd>{backup.fileName}</dd>
+ <CardOption label={t("setup.existing-data-file-name")}>
+ <span class="existing-data-file-name">{backup.fileName}</span>
+ </CardOption>
- <dt>{t("setup.existing-data-file-path")}</dt>
- <dd class="existing-data-path">{backup.filePath}</dd>
+ <CardOption label={t("setup.existing-data-file-path")}>
+ <BackupDirectory path={backup.directoryPath} />
+ </CardOption>
- <dt>{t("setup.existing-data-file-size")}</dt>
- <dd>{formatSize(backup.fileSize)}</dd>
- </dl>
+ <CardOption label={t("setup.existing-data-file-size")}>
+ {formatSize(backup.fileSize)}
+ </CardOption>
+
+ <CardSection className="existing-data-actions">
+ <Button
+ text={isElectron() ? t("setup.existing-data-save-as") : t("setup.existing-data-download")}
+ icon="bx bx-download"
+ onClick={() => downloadBackup(backup.filePath)}
+ />
</CardSection>
</Card>
@@ -318,6 +334,39 @@ export function ExistingDataBackedUp({ backup, onContinue, onCancel }: {
*/
const BACKUP_TIMEOUT_MS = 60 * 60 * 1000;
+/**
+ * Where the backup went, as something the user can act on.
+ *
+ * The directory rather than the whole path: the file name is on the line above, and what a user
+ * wants from this line is to go and look. Only the desktop can open it, so everywhere else it stays
+ * a plain, selectable line of text.
+ */
+function BackupDirectory({ path }: { path: string }) {
+ if (!isElectron()) {
+ return <span class="existing-data-path">{path}</span>;
+ }
+
+ return (
+ <a
+ class="existing-data-path existing-data-path-link"
+ href="#"
+ title={t("setup.existing-data-open-folder")}
+ onClick={(e) => {
+ e.preventDefault();
+ void window.electronApi?.shell.openPath(path);
+ }}
+ >
+ {path}
+ </a>
+ );
+}
+
+/** Saves a copy of the backup wherever the user says, through the platform's own download. */
+function downloadBackup(filePath: string) {
+ open.download(open.getUrlForDownload(
+ `api/database/backup/download?filePath=${encodeURIComponent(filePath)}`));
+}
+
/** Backs the existing database up, answering with what was written. */
export function backUpExistingData(): Promise<SetupExistingBackup> {
return server.postWithTimeout<SetupExistingBackup>("setup/existing/backup", BACKUP_TIMEOUT_MS);
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 557e9c3b8b..e1bbbe85cd 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3695,7 +3695,10 @@
"existing-data-backed-up": "Backup created",
"existing-data-backed-up-description": "Your existing knowledge base has been saved to a backup file.",
"existing-data-file-name": "Backup file name",
- "existing-data-file-path": "File path",
+ "existing-data-file-path": "Location",
+ "existing-data-open-folder": "Open this folder",
+ "existing-data-save-as": "Save a copy...",
+ "existing-data-download": "Download",
"existing-data-file-size": "Size",
"existing-data-encrypted-warning": "This backup is encrypted with the backup password you set in the options, which is not your Trilium password. If you no longer have that password, press Cancel now: nothing has been deleted yet, and you can change the password before trying again. Without it the backup cannot be restored.",
"existing-data-backup-failed": "The backup could not be created.",
diff --git a/apps/server/src/backup_provider.spec.ts b/apps/server/src/backup_provider.spec.ts
index 86f2c0a13b..75699ebfd0 100644
--- a/apps/server/src/backup_provider.spec.ts
+++ b/apps/server/src/backup_provider.spec.ts
@@ -509,3 +509,56 @@ describe("ServerBackupService.getBackupContent", () => {
expect(await desktopService("").getBackupContent(path.join(DEFAULT_DIR, "backup-absent.db"))).toBeNull();
});
});
+
+describe("ServerBackupService: sending a backup for download", () => {
+ /** Collects what was written to it, and records the moment the headers were committed. */
+ function fakeResponse() {
+ const headers: Record<string, string> = {};
+ const chunks: Buffer[] = [];
+ let flushedAfter: number | null = null;
+
+ const res = new Writable({
+ write(chunk: Buffer, _encoding, callback) {
+ chunks.push(Buffer.from(chunk));
+ callback();
+ }
+ }) as Writable & {
+ setHeader(name: string, value: string): void;
+ flushHeaders(): void;
+ };
+ res.setHeader = (name, value) => { headers[name] = value; };
+ res.flushHeaders = () => { flushedAfter = chunks.length; };
+
+ return { res, headers, chunks, flushed: () => flushedAfter };
+ }
+
+ async function written(res: Writable): Promise<void> {
+ await new Promise((resolve) => res.on("finish", resolve));
+ }
+
+ it("streams it with its headers committed first, so nothing downstream buffers it whole", async () => {
+ const filePath = path.join(CUSTOM_DIR, "Backup 2026-08-07 10-32-21.tnbackup");
+ fs.mkdirSync(CUSTOM_DIR, { recursive: true });
+ fs.writeFileSync(filePath, "backup-bytes");
+ const { res, headers, chunks, flushed } = fakeResponse();
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- the express Response surface this uses.
+ expect(desktopService(CUSTOM_DIR).sendBackup?.(filePath, res as any)).toBe(true);
+ await written(res);
+
+ expect(Buffer.concat(chunks).toString()).toBe("backup-bytes");
+ expect(headers["Content-Disposition"])
+ .toBe('attachment; filename="Backup 2026-08-07 10-32-21.tnbackup"');
+ expect(headers["Content-Length"]).toBe("12");
+ // Before any of the body: the desktop's protocol bridge streams only once headers are
+ // flushed, and buffers a multi-gigabyte backup whole otherwise.
+ expect(flushed()).toBe(0);
+ });
+
+ it("refuses anything that is not an existing backup, rather than sending a file", () => {
+ const { res } = fakeResponse();
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- as above.
+ expect(desktopService(CUSTOM_DIR).sendBackup?.("/etc/passwd", res as any)).toBe(false);
+ });
+});
diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.ts
index 46c599e6ff..f203ed76a3 100644
--- a/apps/server/src/backup_provider.ts
+++ b/apps/server/src/backup_provider.ts
@@ -7,6 +7,7 @@ import type { DatabaseBackup, SetupExistingBackup } from "@triliumnext/commons";
import { BackupOptionsService, BackupService, getLog, sync_mutex as syncMutexService, utils as coreUtils, ws } from "@triliumnext/core";
import fs from "fs";
import fsp from "fs/promises";
+import type { Response } from "express";
import { t } from "i18next";
import path from "path";
@@ -132,6 +133,7 @@ export default class ServerBackupService extends BackupService {
return {
fileName: path.basename(written.filePath),
filePath: written.filePath,
+ directoryPath: path.dirname(written.filePath),
fileSize: stat.size,
encrypted: written.encrypted
};
@@ -151,6 +153,24 @@ export default class ServerBackupService extends BackupService {
* path use this directly rather than {@link getBackupContent}, which reads the whole file into
* memory — no use at all for a backup measured in gigabytes.
*/
+ override sendBackup(filePath: string, res: Response): boolean {
+ const resolved = this.resolveBackupPath(filePath);
+ if (!resolved) {
+ return false;
+ }
+
+ res.setHeader("Content-Type", "application/octet-stream");
+ res.setHeader("Content-Disposition", `attachment; filename="${path.basename(resolved)}"`);
+ res.setHeader("Content-Length", String(fs.statSync(resolved).size));
+ // Committed before a single byte of the body: the desktop serves the renderer through a
+ // protocol bridge that only streams once headers are flushed, and buffers everything
+ // otherwise. A backup is exactly the response that must not be buffered.
+ res.flushHeaders();
+ fs.createReadStream(resolved).pipe(res);
+
+ return true;
+ }
+
resolveBackupPath(filePath: string): string | null {
const resolvedPath = path.resolve(filePath);
diff --git a/packages/commons/src/lib/setup_marker.ts b/packages/commons/src/lib/setup_marker.ts
index fa4976075f..a5bb093885 100644
--- a/packages/commons/src/lib/setup_marker.ts
+++ b/packages/commons/src/lib/setup_marker.ts
@@ -27,8 +27,15 @@ export type SetupTargetScreen = "restore-backup";
/** A backup the setup screen took of the database it is about to replace. */
export interface SetupExistingBackup {
fileName: string;
- /** Shown in full, because the user may lose sight of a custom backup directory afterwards. */
+ /** The whole path, for downloading it and for anything that needs to name the file itself. */
filePath: string;
+ /**
+ * The directory holding it, shown on its own.
+ *
+ * Shown because the user may lose sight of a custom backup location afterwards: the option
+ * naming it lives in the database that is about to be replaced.
+ */
+ directoryPath: string;
fileSize: number;
/** Whether it is encrypted, which decides whether the user needs their backup password to use it. */
encrypted: boolean;
diff --git a/packages/trilium-core/src/routes/api/backup.spec.ts b/packages/trilium-core/src/routes/api/backup.spec.ts
index 95b185b0e1..e0230cb24e 100644
--- a/packages/trilium-core/src/routes/api/backup.spec.ts
+++ b/packages/trilium-core/src/routes/api/backup.spec.ts
@@ -56,6 +56,30 @@ describe("Backup API (core)", () => {
expect(res.status).toBe(404);
});
+ it("lets the platform send the file rather than reading it into memory", async () => {
+ // Reading it first is what the route used to do, and Node refuses a file over 2 GiB
+ // outright, so every real backup failed to download with nothing shown to the user.
+ const backup = getBackup() as { sendBackup?: (filePath: string, res: unknown) => boolean };
+ const previous = backup.sendBackup;
+ const sent: string[] = [];
+ backup.sendBackup = (filePath, res) => {
+ sent.push(filePath);
+ (res as { send(body: unknown): unknown }).send("streamed");
+ return true;
+ };
+ const read = vi.spyOn(getBackup(), "getBackupContent");
+
+ const res = await api.get(`/api/database/backup/download`, {
+ query: { filePath: "/backups/Backup 2026-08-07 10-32-21.tnbackup" }
+ });
+
+ expect(res.status).toBe(200);
+ expect(sent).toEqual([ "/backups/Backup 2026-08-07 10-32-21.tnbackup" ]);
+ expect(read).not.toHaveBeenCalled();
+
+ backup.sendBackup = previous;
+ });
+
it("streams the backup content with download headers", async () => {
vi.spyOn(getBackup(), "getBackupContent").mockResolvedValue(Buffer.from("SQLite format 3 ") as never);
diff --git a/packages/trilium-core/src/routes/api/backup.ts b/packages/trilium-core/src/routes/api/backup.ts
index e3dd5fe5b8..d98ed2de1d 100644
--- a/packages/trilium-core/src/routes/api/backup.ts
+++ b/packages/trilium-core/src/routes/api/backup.ts
@@ -23,18 +23,29 @@ async function downloadBackup(req: Request, res: Response): Promise<void> {
return;
}
- const content = await getBackup().getBackupContent(filePath);
+ const backup = getBackup();
+ // Sent a piece at a time wherever the platform can: reading it first means holding a whole
+ // backup in memory, which Node refuses above 2 GiB and which any real one will exceed.
+ if (backup.sendBackup?.(filePath, res)) {
+ return;
+ }
+
+ const content = await backup.getBackupContent(filePath);
if (!content) {
res.status(404).send("Backup not found");
return;
}
- const fileName = filePath.split("/").pop() || "backup.db";
res.set("Content-Type", "application/x-sqlite3");
- res.set("Content-Disposition", `attachment; filename="${fileName}"`);
+ res.set("Content-Disposition", `attachment; filename="${fileNameOf(filePath)}"`);
res.send(content);
}
+/** The last segment of a path, on either kind of separator: these are read off a Windows disk too. */
+function fileNameOf(filePath: string): string {
+ return filePath.split(/[\\/]/).pop() || "backup.db";
+}
+
export default {
getExistingBackups,
backupDatabase,
diff --git a/packages/trilium-core/src/services/backup.ts b/packages/trilium-core/src/services/backup.ts
index 1a038de247..cc5ac8d674 100644
--- a/packages/trilium-core/src/services/backup.ts
+++ b/packages/trilium-core/src/services/backup.ts
@@ -1,4 +1,6 @@
import type { DatabaseBackup, FilterOptionsByType, OptionNames, SetupExistingBackup } from "@triliumnext/commons";
+import type { Response } from "express";
+
import { getContext } from "./context.js";
import dateUtils from "./utils/date.js";
@@ -79,6 +81,19 @@ export default abstract class BackupService {
*/
abstract getBackupContent(filePath: string): Promise<Uint8Array | null>;
+ /**
+ * Sends an existing backup to `res` as a download, a piece at a time.
+ *
+ * Neither reading it first nor handing the path to Express will do. {@link getBackupContent}
+ * holds the whole thing in memory, which Node refuses outright above 2 GiB, and `res.download`
+ * never flushes its headers, which is the signal the desktop's protocol bridge waits for before
+ * it streams — without it a multi-gigabyte backup is buffered whole on its way to the renderer
+ * and takes the application down with it.
+ *
+ * @returns whether it was sent; `false` for anything that is not an existing backup.
+ */
+ sendBackup?(filePath: string, res: Response): boolean;
+
/**
* Run the scheduled backup checks for daily, weekly, and monthly backups.
*/
diff --git a/packages/trilium-core/src/test/api_tester.ts b/packages/trilium-core/src/test/api_tester.ts
index 088352cb5a..b68b7bf289 100644
--- a/packages/trilium-core/src/test/api_tester.ts
+++ b/packages/trilium-core/src/test/api_tester.ts
@@ -58,6 +58,8 @@ export interface TestResponse<T = unknown> {
status: number;
headers: Record<string, string>;
body: T;
+ /** The file a handler asked Express to send rather than write itself, if it did. */
+ sentFile?: string;
}
export interface RequestOptions {
@@ -148,6 +150,8 @@ class MockResponse extends Writable {
statusCode = 200;
headers: Record<string, string> = {};
+ sentFile?: string;
+
private chunks: Buffer[] = [];
private sendBody: unknown;
private hasSendBody = false;
@@ -157,6 +161,16 @@ class MockResponse extends Writable {
setHeader(name: string, value: string) { this.headers[name] = value; return this; }
removeHeader(name: string) { delete this.headers[name]; return this; }
send(body: unknown) { this.used = true; this.hasSendBody = true; this.sendBody = body; return this; }
+ /**
+ * Express sends the file itself from here, so nothing passes through this object. Recorded
+ * rather than read, which is the whole point of a handler choosing this over `send`.
+ */
+ download(filePath: string, fileName?: string) {
+ this.used = true;
+ this.sentFile = filePath;
+ this.headers["Content-Disposition"] = `attachment; filename="${fileName ?? filePath}"`;
+ return this;
+ }
json(body: unknown) { return this.send(body); }
sendStatus(code: number) { this.used = true; this.statusCode = code; return this; }
@@ -173,7 +187,7 @@ class MockResponse extends Writable {
} else if (this.hasSendBody) {
body = normalizeResponseBody(this.sendBody);
}
- return { status: this.statusCode, headers: this.headers, body };
+ return { status: this.statusCode, headers: this.headers, body, sentFile: this.sentFile };
}
}