Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/utils/fs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Nitro } from "nitro/types";
import { stat, mkdir, writeFile as fspWriteFile } from "node:fs/promises";
import { stat, mkdir, rename, rm, writeFile as fspWriteFile } from "node:fs/promises";
import { dirname } from "pathe";
import consola from "consola";
import { colors } from "consola/utils";
Expand Down Expand Up @@ -47,9 +47,21 @@ function _compilePathTemplate(contents: string) {
});
}

let _tmpFileCounter = 0;

export async function writeFile(file: string, contents: Buffer | string, log = false) {
await mkdir(dirname(file), { recursive: true });
await fspWriteFile(file, contents, typeof contents === "string" ? "utf8" : undefined);
// Write to a sibling temp file and rename it into place. `rename` is atomic within a
// filesystem, so two writers racing for the same path produce last-one-wins instead
// of a file torn between both payloads.
const tmpFile = `${file}.${process.pid}-${_tmpFileCounter++}.tmp`;
try {
await fspWriteFile(tmpFile, contents, typeof contents === "string" ? "utf8" : undefined);
await rename(tmpFile, file);
} catch (error) {
await rm(tmpFile, { force: true });
throw error;
}
if (log) {
consola.info("Generated", prettyPath(file));
}
Expand Down
57 changes: 57 additions & 0 deletions test/unit/fs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { mkdtemp, readFile, readdir, rm, writeFile as fspWriteFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { join } from "pathe";
import { writeFile } from "../../src/utils/fs.ts";

describe("writeFile", () => {
let dir: string;

beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), "nitro-fs-"));
});

afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});

it("writes contents and creates missing parent directories", async () => {
const file = join(dir, "nested/deeply/index.html");

await writeFile(file, "<h1>hello</h1>");

expect(await readFile(file, "utf8")).toBe("<h1>hello</h1>");
});

it("leaves no temporary files behind", async () => {
await writeFile(join(dir, "index.html"), "<h1>hello</h1>");

expect(await readdir(dir)).toEqual(["index.html"]);
});

it("overwrites an existing file", async () => {
const file = join(dir, "index.html");
await fspWriteFile(file, "old");

await writeFile(file, "new");

expect(await readFile(file, "utf8")).toBe("new");
});

it("never leaves a file torn between two concurrent writers", async () => {
// Two prerender routes can resolve to a single output file, and with
// `prerender.concurrency > 1` their writes overlap. A non-atomic write then
// leaves the longer payload's tail after the shorter payload's body.
const file = join(dir, "other/index.html");
const long = Buffer.from("L".repeat(300));
const short = Buffer.from("S".repeat(256));

for (let i = 0; i < 100; i++) {
await Promise.all([writeFile(file, long), writeFile(file, short)]);

const written = await readFile(file);
const isWhole = written.equals(long) || written.equals(short);
expect(isWhole, `torn after ${written.length} bytes on run ${i}`).toBe(true);
}
});
});