Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to delete a file in Node.js

Short answer

unlink() deletes a file:

import { unlink, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
 
await writeFile('temp.txt', 'data');
await unlink('temp.txt');
 
console.log(existsSync('temp.txt'));

Output:

false

If the file may be missing

rm() with force: true does not throw an error for a missing file:

import { rm } from 'node:fs/promises';
 
await rm('maybe-missing.txt', { force: true });
console.log('no error');

Output:

no error

By extension

Read the folder and delete the files that match:

import { mkdir, readdir, unlink, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
 
await mkdir('cache', { recursive: true });
for (const name of ['a.tmp', 'b.tmp', 'keep.txt']) await writeFile(join('cache', name), '');
 
for (const name of await readdir('cache')) {
  if (name.endsWith('.tmp')) await unlink(join('cache', name));
}
 
console.log(await readdir('cache'));

Output:

[ 'keep.txt' ]

Common mistake

unlink() for a missing file throws the ENOENT error and stops the script if you do not catch it:

import { unlink } from 'node:fs/promises';
 
try {
  await unlink('ghost.txt');
} catch (error) {
  console.log(error.code);
}

Output:

ENOENT

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.