This article shows you a couple of different ways to remove a file or a directory using Node.js. We’ll use modern Javascript (ES6 and newer) and the latest features provided by Node.js core. No third-party libraries need to be installed.
Removing FIles
Using fsPromises.unlink() with async/await
Nowadays developers often prefer to use async/await over callback functions.
Example:
import fsPromises from 'fs/promises'
// for CommonJS, use this:
// const fsPromises = require("fs/promises");
const deleteFile = async (filePath) => {
try {
await fsPromises.unlink(filePath);
console.log('Successfully removed file!');
} catch (err) {
console.log(err);
}
};
// Try it
const filePath = "./kindacode.com";
deleteFile(filePath);
If the file exists, you will see this:
Successfully removed file!
Otherwise, the output should look like this:
[Error: ENOENT: no such file or directory, unlink './kindacode.com'] {
errno: -2,
code: 'ENOENT',
syscall: 'unlink',
path: './kindacode.com'
}
Using fs.unlink() and fs.unlinkSync()
You can use the unlink() method from the fs module to asynchronously unlink a file. There is no need to check whether the file exists before executing deletion.
Example:
import fs from 'fs'
// for CommonJS, use this:
// const fs = require("fs");
const filePath = "./kindacode.jpeg";
fs.unlink(filePath, (err) => {
if (err && err.code == "ENOENT") {
console.info("Error! File doesn't exist.");
} else if (err) {
console.error("Something went wrong. Please try again later.");
} else {
console.info(`Successfully removed file with the path of ${filePath}`);
}
});
If you want to synchronously unlink a file, use the unlinkSync() method instead:
import fs from 'fs';
const filePath = 'path-to-your-file';
fs.unlinkSync(filePath);
Removing Directories
Using fsPromises.rmdir() with async/await
If you want to delete a folder and all files and subfolders inside it, you can use fsPromises.rmdir() with the recursive: true option, like this:
import fsPromises from "fs/promises";
/* Other code go here */
fsPromises.rmdir(dirPath, { recursive: true });
If you only want to remove an empty folder, just set recursive to false.
Full Example:
import fsPromises from "fs/promises";
// Delete a directory and its children
const removeDirectory = async (dirPath) => {
try {
await fsPromises.rm(dirPath, { recursive: true });
console.log("Directory removed!");
} catch (err) {
console.log(err);
}
};
const dir = "./some";
removeDirectory(dir);
Using fs.rm() and fs.rmSync()
If you like the old-fashioned callback things of Node.js, you can use the rm() method to asynchronously remove a directory or use the rmSync() method to synchronously remove a directory.
Example:
import fs from 'fs'
const dir1 = "./some-dir";
fs.rmdir(dir1, (err) => {
if (err) {
console.log(err);
}
});
const dir2 = "./kindacode-directory";
// Delete dir2 and its child files or sub directories
fs.rmdirSync(dir2, { recursive: true });
Conclusion
We’ve walked through a few examples of deleting files and directories in Node.js. If you’d like to learn more interesting stuff about this Javascript runtime, take a look at the following articles:
- Node.js: Ways to Create a Directory If It Doesn’t Exist
- 7 Best Open-Source HTTP Request Libraries for Node.js
- 4 Ways to Convert Object into Query String in Node.js
- Node.js: Get domain, hostname, and protocol from a URL
- Top 5 best Node.js Open Source Headless CMS
- 7 best Node.js frameworks to build backend APIs
You can also check out our Node.js category page or PHP category page for the latest tutorials and examples.