2026-05-08 14:05:57 +09:00
|
|
|
import {
|
|
|
|
|
closeSync,
|
|
|
|
|
type fsyncSync as FsyncSync,
|
|
|
|
|
openSync,
|
|
|
|
|
renameSync,
|
|
|
|
|
unlinkSync,
|
|
|
|
|
writeFileSync,
|
|
|
|
|
} from "node:fs"
|
2026-04-04 14:33:52 +09:00
|
|
|
|
2026-05-08 14:05:57 +09:00
|
|
|
import { tolerantFsyncSync } from "./tolerant-fsync"
|
|
|
|
|
|
|
|
|
|
export function writeFileAtomically(
|
|
|
|
|
filePath: string,
|
|
|
|
|
content: string,
|
|
|
|
|
deps: { fsyncSync?: typeof FsyncSync } = {},
|
|
|
|
|
): void {
|
|
|
|
|
const tempPath = `${filePath}.tmp`
|
|
|
|
|
writeFileSync(tempPath, content, "utf-8")
|
2026-04-04 14:33:52 +09:00
|
|
|
const tempFileDescriptor = openSync(tempPath, "r")
|
|
|
|
|
try {
|
2026-05-08 14:05:57 +09:00
|
|
|
tolerantFsyncSync(tempFileDescriptor, `writeFileAtomically:${filePath}`, deps.fsyncSync)
|
2026-04-04 14:33:52 +09:00
|
|
|
} finally {
|
|
|
|
|
closeSync(tempFileDescriptor)
|
|
|
|
|
}
|
2026-04-12 02:28:05 +09:00
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
renameSync(tempPath, filePath)
|
|
|
|
|
} catch (error) {
|
|
|
|
|
const isWindows = process.platform === "win32"
|
|
|
|
|
const isPermissionError =
|
|
|
|
|
error instanceof Error &&
|
|
|
|
|
(error.message.includes("EPERM") || error.message.includes("EACCES"))
|
|
|
|
|
|
|
|
|
|
if (isWindows && isPermissionError) {
|
|
|
|
|
unlinkSync(filePath)
|
|
|
|
|
renameSync(tempPath, filePath)
|
|
|
|
|
} else {
|
|
|
|
|
throw error
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-04-04 14:33:52 +09:00
|
|
|
}
|