a blog for those who code

Tuesday 26 July 2016

Creating and Removing Directories in Node.js

In this post we will be discussing about creating and removing directories in Node.js. If you want to manipulate the structure of your directories by adding or removing directories via your Node.js application then you can use the below code to do that.


Creating Directory Synchronously and Asynchronously


var fs = require('fs');

// Synchronously
try {
  fs.mkdirSync('MyNewDirectory');
  console.log('Directory Created');
} catch (err) {
    if(err.code === 'EEXIST') {
      console.log('The directory already exists');
    } else {
      console.log(err);
    }
}

// Asynchronously
fs.mkdir('MyNewDirectory', function(err) {
  if(err) {
    if(err.code === 'EEXIST') {
      console.log('The directory already exists');
    } else {
      console.log(err);
    }
  } else {
    console.log('Directory Created');
  }
});


Removing Directory Synchronously and Asynchronously


var fs = require('fs');

// Synchronously
try {
  fs.rmdirSync('MyNewDirectory');
  console.log('Directory Removed');
} catch (err) {
    if(err.code === 'ENOENT') {
        console.log('The directory does not exists');
    } else if(err.code === 'ENOTEMPTY') {
        console.log('Not empty directory');
    } else {
console.log(err);
  }
}

// Asynchronously
fs.rmdir('MyNewDirectory', function(err) {
  if(err) {
    if(err.code === 'ENOENT') {
        console.log('The directory does not exists');
    } else if(err.code === 'ENOTEMPTY') {
        console.log('Not empty directory');
    } else {
console.log(err);
    }
  } else {
      console.log('Directory Removed');
  }
});



Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment