Creating Directories Using NodeJS fs Module

Mera Gangapersaud
MeraG
Published in
2 min readSep 17, 2018

A how-to blog

The NodeJS fs module is an API used to ease interaction with a file system. If you are familiar with UNIX scripting (like me), some of the functions may look similar to UNIX commands. I believe that could be because this module closely follows POSIX standards which used UNIX as a basis.

To explore this module I looked at the mkdir feature which creates a new directory. Below are implementations of three different functions in the fs module that can do this.

fs.mkdir
fs.mkdir(path[, mode], callback);

const fs = require(‘fs’);fs.mkdir(‘fs_test’, function(err){
if(err){
console.log(‘failed to create directory’);
return console.error(err);
}else{
console.log(‘Directory created successfully’);
}
});

This is an asyncronous function with three parameters: path, mode and callback.

  • Path <String> | <Buffer> | <URL> specifies what the new directory is called and where it is to be created.
  • Mode <Integer> is optional and specifies the permissions for the directory.
  • Callback <Function> is the function called when fs.mkdir is done.

fs.mkdirSync
fs.mkdirSync(path[, mode]);

const fs = require(‘fs’);fs.mkdirSync(‘fs_test/test2’);

This function is synchronous and has two parameters: path and mode. A callback is not used since it is not an async function.

  • Path <String> | <Buffer> | <URL> specifies what the new directory is called and where it is to be created.
  • Mode <Integer> is optional and specifies the permissions for the directory.

fsPromises.mkdir
fsPromises.mkdir(path[, mode]);


const fs = require(‘fs’);
const fsPromises = fs.promises;
fsPromises.mkdir('fs_test2').then(function() {
console.log('Directory created successfully');
}).catch(function() {
console.log('failed to create directory');
});

This function is asynchronous as well but differs from fs.mkdir by using a promise instead of a callback function. It has two parameters; path and mode.

  • Path <String> | <Buffer> | <URL> specifies what the new directory is called and where it is to be created.
  • Mode <Integer> is optional and specifies the permissions for the directory.

Ensure that you are using version 10.0.0 or higher of nodeJS to use this function as it is not supported in the earlier versions. Also, note that fs.promises is still experimental and you will get a warning message when this code is run.

the output of fsPromises.mkdir

--

--