Node.js Reference ยท fs and fs/promises
Node.js fs.unlink() method
Reference for fs.unlink() in Node.js: delete a file or symbolic link, what happens to open handles, and why directories need rmdir() or rm() instead.
fs.unlink(path, callback) removes a name from the file system. For a normal file that deletes it (once nothing has it open and no other hard link points to it). For a symbolic link it removes the link only, never the file the link points to.
unlink() is for files. It does not remove directories; use rmdir() for an empty directory and rm() for trees. The name comes from Unix: files are really "links" to data, and the data goes away when its last link does.
import { unlinkSync } from 'node:fs'; unlinkSync('cache.tmp');
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
fs.unlink(path, callback) fs.unlinkSync(path): undefined fsPromises.unlink(path): Promise<undefined> // path: string | Buffer | URL // callback: (err: Error | null) => void
| Name | Description |
|---|---|
path |
The file or symbolic link to remove. |
Returns: nothing.
Errors: ENOENT (nothing there), EISDIR or EPERM (the path is a directory; Linux and macOS differ), EACCES/EPERM (no write permission on the parent directory), EBUSY (in use, mostly Windows).
Usage notes
- Permission to delete comes from the directory, not the file. You need write permission on the containing directory.
- Missing files are an error. For "delete if present" catch
ENOENT, or userm(path, { force: true }). - Open handles survive on POSIX. A process that has the file open can keep reading and writing; the disk space is freed when the last handle closes. On Windows, deleting an open file usually fails with
EBUSYorEPERM. - Hard links: deleting one name leaves the data reachable through the others.
- Symlinks are not followed. The link disappears and its target is untouched. A dangling link can still be unlinked.
- No undo, no trash. The data is gone. Move files to a temporary folder first if you need a safety net.
- Directories: use
rmdir()for empty ones,rm()withrecursive: truefor trees. - Security: never build the path from untrusted input without checking it stays inside the intended directory.