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:
falseIf 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 errorBy 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:
ENOENTFunctions used in this recipe
- String.prototype.endsWith — Checks whether a string ends with the given text.