Deleting & Renaming Files
Removing files (unlink, rm), renaming and moving them (rename), and copying (copyFile) round out the basic filesystem toolkit. These operations are destructive, so the emphasis here is on doing them safely — and on the platform quirks that bite people moving files between drives.
Deleting a file
import { unlink } from 'node:fs/promises'
await unlink('temp.txt') // delete a single file
// Handle the "already gone" case gracefully:
try {
await unlink('maybe-gone.txt')
} catch (err) {
if (err.code !== 'ENOENT') throw err // ignore not-found, re-throw the rest
}Deleting directories and trees
The modern rm (Node 14.14+) handles files and directory trees, with options that make it forgiving:
import { rm } from 'node:fs/promises'
await rm('build', { recursive: true, force: true }) // like 'rm -rf build'
// recursive: delete contents too · force: don't error if it's missing
await rm('single.txt') // a single file works tooRenaming and moving
rename both renames and moves — moving is just renaming to a path in another directory. It's atomic on the same filesystem:
import { rename } from 'node:fs/promises'
await rename('draft.txt', 'final.txt') // rename in place
await rename('final.txt', 'archive/final.txt') // move (same filesystem)Cross-device-safe move
import { rename, copyFile, unlink } from 'node:fs/promises'
async function move(src, dest) {
try {
await rename(src, dest) // fast path: same filesystem
} catch (err) {
if (err.code !== 'EXDEV') throw err
await copyFile(src, dest) // fallback: copy across devices
await unlink(src) // then remove the original
}
}Copying files
import { copyFile, constants } from 'node:fs/promises'
await copyFile('a.txt', 'b.txt') // overwrite if exists
await copyFile('a.txt', 'b.txt', constants.COPYFILE_EXCL) // fail if b existsCheck-then-act is a race condition
// ✗ Racy
if (await exists('f.txt')) await unlink('f.txt') // f.txt may vanish between!
// ✓ Robust — act, then handle the outcome
try { await unlink('f.txt') }
catch (err) { if (err.code !== 'ENOENT') throw err }Operation reference
Goal | Function |
|---|---|
Delete a file |
|
Delete a tree (rm -rf) |
|
Delete an empty dir |
|
Rename / move (same FS) |
|
Move across filesystems |
|
Copy a file |
|
Copy a tree |
|