Skip to content
Tutorials Center
My learning

Topics

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.

NODE
import { unlinkSync } from 'node:fs';

unlinkSync('cache.tmp');

Try it

Node.js Deleting files and symlinks

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.

Node.js Missing files, directories and open handles

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

NODE
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 use rm(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 EBUSY or EPERM.
  • 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() with recursive: true for trees.
  • Security: never build the path from untrusted input without checking it stays inside the intended directory.