fs.rename Atomically Replaces Files

Publish new content with fs.rename so the destination is replaced in one filesystem operation and readers never observe a half-written file.

JavascriptData Integrity

Code

javascriptsnippet
13 lines
import { writeFile, rename, readFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';

await writeFile('report.txt', 'draft v1');
await writeFile('report.txt.new', 'draft v2');

// rename overwrites the destination in one filesystem operation,
// so readers never observe a half-written report
await rename('report.txt.new', 'report.txt');

console.log('published content:', await readFile('report.txt', 'utf8'));
console.log('temp file consumed by rename:', !existsSync('report.txt.new'));
console.log('content length:', (await readFile('report.txt', 'utf8')).length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

published content: draft v2
temp file consumed by rename: true
content length: 8

Inside the snippet

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The import names the platform contact area: writeFile, rename, readFile, existsSync, all from node:fs/promises, node:fs.

Points of care

  • The dependency surface is just node:fs/promises, and that one is built into Node.js.

Putting it to use

Look for the published content:, temp file consumed by rename:, content length: prefixes when the file runs; they tie each line to its step.

Core lines

await writeFile('report.txt.new', 'draft v2');
await rename('report.txt.new', 'report.txt');
await writeFile('report.txt', 'draft v1');

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.