fs.rmdir() vs fs.rmdirSync() in Node.js

The main purpose of rmdir() and rmdirSync() methods in the fs module is to remove a directory. If you are going to use any of these two methods, you should also remember that using them it is only possible to remove an empty directory. In case your goal is to get rid of the folder which contains another files or directories you would need to install the additional fs-extra module that would add more features on top of the fs. You can use remove() method from the fs-extra module to delete directories that contain something.

fs.rmdir(path, callback)

Removes a directory asynchronously.
If the directory isn’t empty the function will throw an exception.

Passed Parameters:

  1. path – string, path to the directory which you want to remove. The function won’t work if you will pass a path to the file instead of the directory (will result in ENOENT error on Windows and an ENOTDIR error on POSIX)
  2. callback – function, returns an error.
 function rmdir(path, callback) {
    callback = makeCallback(callback);
    path = toPathIfFileURL(path);
    validatePath(path);
    const req = new FSReqCallback();
    req.oncomplete = callback;
    binding.rmdir(pathModule.toNamespacedPath(path), req);
 }  

fs.rmdirSync(path)

Removes a directory synchronously.
If the directory isn’t empty synchronously the function will throw an exception.

Passed Parameters:

  1. path – string, path to the directory which you want to remove. The function won’t work if you will pass a path to the file instead of the directory (will result in ENOENT error on Windows and an ENOTDIR error on POSIX)

Source code: 

 function rmdirSync(path) {
    path = toPathIfFileURL(path);
    validatePath(path);
    const ctx = { path };
    binding.rmdir(pathModule.toNamespacedPath(path), undefined, ctx);
    handleErrorFromBinding(ctx);
 }

Example:

Cars directory is located in the users/olena folder. We want to asynchronously remove the cars directory. If the directory doesn’t exist or it is not empty, the error will be thrown.
var fs = require('fs');
   // Asynchronously remove the directory 
   try {
      fs.rmdir('/users /olena/cars’, { recursive: true }, (err) => {   
        console.log(‘cars directory is removed.');  
      } catch(err) {
      if (err.code===’ENOENT’){
          console.log(‘Directory doesn’t exist’)
      } else if (err.code===’ENOTEMPTY’) {
          console.log(‘Directory not empty’);
      } else {
          console.log(err);
      }
   }  

Comments

Popular posts from this blog

Release 0.4, Second Blog

Release 0.3, Update 1