2026-08-06 15:39:49 -04:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
|
|
const crypto = require('crypto');
|
|
|
|
|
const fs = require('fs');
|
|
|
|
|
const path = require('path');
|
|
|
|
|
|
|
|
|
|
function writeFileAtomic(filePath, content, options = {}) {
|
|
|
|
|
const resolvedPath = path.resolve(filePath);
|
|
|
|
|
const parentDir = path.dirname(resolvedPath);
|
|
|
|
|
const tempPath = path.join(
|
|
|
|
|
parentDir,
|
|
|
|
|
`.${path.basename(resolvedPath)}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp`
|
|
|
|
|
);
|
|
|
|
|
const mode = options.mode || 0o600;
|
|
|
|
|
|
2026-09-07 16:31:33 -04:00
|
|
|
if (options.validateParent) options.validateParent();
|
2026-08-06 15:39:49 -04:00
|
|
|
fs.mkdirSync(parentDir, { recursive: true });
|
|
|
|
|
|
|
|
|
|
let descriptor;
|
|
|
|
|
try {
|
2026-09-07 16:31:33 -04:00
|
|
|
if (options.validateParent) options.validateParent();
|
2026-08-06 15:39:49 -04:00
|
|
|
descriptor = fs.openSync(tempPath, 'wx', mode);
|
2026-09-07 16:31:33 -04:00
|
|
|
if (options.validateParent) options.validateParent();
|
2026-08-06 15:39:49 -04:00
|
|
|
fs.writeFileSync(descriptor, content, { encoding: options.encoding || 'utf8' });
|
|
|
|
|
fs.fsyncSync(descriptor);
|
|
|
|
|
fs.closeSync(descriptor);
|
|
|
|
|
descriptor = undefined;
|
2026-09-07 16:31:33 -04:00
|
|
|
if (options.validateParent) options.validateParent();
|
|
|
|
|
if (options.beforeRename) options.beforeRename();
|
2026-08-06 15:39:49 -04:00
|
|
|
fs.renameSync(tempPath, resolvedPath);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
if (descriptor !== undefined) {
|
|
|
|
|
fs.closeSync(descriptor);
|
|
|
|
|
}
|
2026-09-07 16:31:33 -04:00
|
|
|
// If the parent was replaced, this pathname may now name somebody else's
|
|
|
|
|
// file. Leave the private staging file in its original directory.
|
|
|
|
|
let parentUnchanged = true;
|
|
|
|
|
try {
|
|
|
|
|
if (options.validateParent) options.validateParent();
|
|
|
|
|
} catch (_error) {
|
|
|
|
|
parentUnchanged = false;
|
|
|
|
|
}
|
|
|
|
|
if (parentUnchanged) fs.rmSync(tempPath, { force: true });
|
2026-08-06 15:39:49 -04:00
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return resolvedPath;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
|
writeFileAtomic,
|
|
|
|
|
};
|