import fs from "node:fs"; import os from "node:os"; import path from "node:path"; const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ch06-log-")); const file = path.join(dir, "main.log"); const limit = 100; const records = [ { at: 1, level: "info", evt: "boot" }, { at: 2, level: "warn", evt: "slow", msg: "示例" }, { at: 3, level: "error", evt: "boom" }, ]; let size = 0; let rotated = false; for (const record of records) { const line = JSON.stringify(record); process.stdout.write(`${line}\n`); fs.appendFileSync(file, `${line}\n`); size += Buffer.byteLength(line) + 1; if (size >= limit) { fs.renameSync(file, `${file}.1`); fs.writeFileSync(file, ""); size = 0; rotated = true; } } const archive = `${file}.1`; const lines = fs.existsSync(archive) ? fs.readFileSync(archive, "utf8").trim().split("\n").filter(Boolean).length : 0; console.log( JSON.stringify({ evt: "smoke", ok: rotated && lines >= 1, lines, rotated }), ); fs.rmSync(dir, { recursive: true, force: true });