21 lines
644 B
JavaScript
21 lines
644 B
JavaScript
const fs = require("node:fs/promises");
|
|
const { randomUUID } = require("node:crypto");
|
|
|
|
async function writeOutput(file, contents, io = fs) {
|
|
try {
|
|
if (await io.readFile(file, "utf8") === contents) return;
|
|
} catch (error) {
|
|
if (error.code !== "ENOENT") throw error;
|
|
}
|
|
// Replace a complete file; never remove or truncate a script the browser may load.
|
|
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
try {
|
|
await io.writeFile(temporary, contents, { encoding: "utf8", flag: "wx" });
|
|
await io.rename(temporary, file);
|
|
} finally {
|
|
await io.rm(temporary, { force: true });
|
|
}
|
|
}
|
|
|
|
module.exports = { writeOutput };
|