How to Delete a File or Directory in Node.js

Last updated on July 17, 2021 A Goodman Loading... Post a comment

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:

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:

const fs = require("fs");

const filePath = "./kindacode.jpeg";

fs.unlink(dir, (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:

var fs = require('fs');
var 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:

const fsPromises = require("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:

const fsPromises = require("fs/promises");

// Delete a directory and its children
const removeDirectory = async (dirPath) => {
  try {
    await fsPromises.rmdir(dirPath, { recursive: true });
    console.log("Directory removed!");
  } catch (err) {
    console.log(err);
  }
};

const dir = "./some";
removeDirectory(dir);

Using fs.rmdir() and fs.rmdirSync()

If you like the old fashion of Node.js, you can use the rmdir() method to asynchronously remove a directory or use the rmdirSync() method to synchronously remove a directory.

Example:

const fs = require("fs");

const dir1 = "./some-dir";
fs.rmdir(dir1, (err) => {
  if (err) {
    console.log(err);
  }
});

const dir2 = "./kindacode-directory";
fs.rmdirSync(dir2, { recursive: true }); // Delete dir2 and its child files or sub directories

Conclusion

We’ve walked through a few of 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:

You can also check out our Node.js category page or PHP category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles