Node.js
Rename a file within a directory
Use rename to move a path within a filesystem. For a simple rename, build both paths explicitly and await the operation before using the destination.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
const before = join(directory, "draft.txt");
const after = join(directory, "published.txt");
await fs.writeFile(before, "ready");
await fs.rename(before, after);
console.log(await fs.readFile(after, "utf8"));
} finally {
await fs.rm(directory, {recursive: true, force: true});
}How it works
The directory entry changes from draft.txt to published.txt, while the content remains ready. This differs from copying because the old path no longer names the file after success. The example confines both paths to one temporary directory.
Limits and mistakes
Renaming across filesystems can fail, and existing-destination behavior needs care. A rename alone does not establish power-loss durability for a full write-and-replace protocol. Do not describe every rename operation as a guaranteed safe backup mechanism.
Check the result
Expect ready. Confirm the old path is absent afterward and test destination conflicts according to the operating systems your script supports.
Sources
Reference documentation for the behavior used in this guide: