Bug busters

How to delete a file in node.js

Node.js exposes the unlink and unlinkSync methods from the fs module that allows you to delete files.

const fs = require('fs');

// async approach
fs.unlink("path/to/file", (err)=>{ if(!err) console.log("file deleted!") });

// sync approach
fs.unlinkSync("path/to/file");


If you'd like to delete multiple files that matches a certain pattern, I'll recommend you install the rimraf module which supports glob patterns.

// install module
yarn add rimraf


// async approach
rimraf("/path/folder/**/*.txt", ()=>{ console.log("all .txt files in path/folder and sub folders deleted") })

// sync approach
rimraf.sync("/path/folder/**/*.txt")

node.js

How to delete a folder in node.js

Use the fs.rmSync method introduced in node 14.

const fs = require("fs");

fs.rmSync("path/to/folder", { recursive: true, force: true });


Or if you need to use complex glob patterns, I'll recommend you install the rimraf package

// install rimraf
yarn add rimraf


// async approach
rimraf("path/folder/**", ()=>{ console.log("everthing in /path/folder was deleted") })

// sync approach
rimraf.sync("path/folder/**");


node.js