Creating and Deleting Directories With NodeJS Image Creating and Deleting Directories With NodeJS

In this tutorial I’ll be showing you how to create and delete directories using NodeJS and we’ll be using the mkdirp and the rimraf node package in order to achieve this.

Creating Directories

In order to create a directory we’ll need first download the mkdirp npm package, we can do this like so:

npm install mkdirp --local

This should install the mkdirp package as well as any of it’s dependencies in a node_modules directory within your current directory. Once this has completed we can then start using this new package.

If you wish to read up more about this package you check it’s code out here: mkdirp github

The Code
// first we import our newly installed mkdirp
// package so that we can use it further down
var mkdirp = require("mkdirp");

// and then we call it giving 2 parameters, the first
// being the name of the directory we wish to create
// and the second a callback function.
mkdirp("test", function(err) {
  // if any errors then print the errors to our console
  if (err) console.log(err);
  // else print a success message.
  console.log("Successfully created test directory");

Deleting Directories in Node

In order to delete directories using node we’ll use the rimraf package and we’ll need to again install this using the node package manager:

npm install rimraf --local

Again, if you want to see the code for this package you can do so here

The Code

var rimraf = require("rimraf");

rimraf("test", function(err) {
  if (err) console.log(err);
  console.log("Successfully deleted a directory");

Run this using node delete.js and you should hopefully see the success message printed out in your console as well as the test directory we created in the first part of the tutorial deleted.

Elliot Forbes

Elliot Forbes
Twitter: @Elliot_f

Hey, I'm Elliot and I've been working on TutorialEdge for the last 4 years! If you have any tips or suggestions as to how I can make it better, please let me know in the suggestion box below!

Comments Section