// Write a file so a crash or power cut never leaves half of it: write to a temp file, then rename over the original. const fs = require('fs'); const crypto = require('crypto'); module.exports = function writeFileAtomic(file, data, opts = { mode: 0o600 }) { const tmp = file + '.' + crypto.randomBytes(4).toString('hex') + '.tmp'; try { fs.writeFileSync(tmp, data, opts); fs.renameSync(tmp, file); } catch (e) { try { fs.unlinkSync(tmp); } catch {} throw e; } };