I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdi
The node.js docs for fs.mkdir
basically defer to the Linux man page for mkdir(2). That indicates that EEXIST
will also be indicated if the path exists but isn't a directory which creates an awkward corner case if you go this route.
You may be better off calling fs.stat which will tell you whether the path exists and if it's a directory in a single call. For (what I'm assuming is) the normal case where the directory already exists, it's only a single filesystem hit.
These fs
module methods are thin wrappers around the native C APIs so you've got to check the man pages referenced in the node.js docs for the details.
You can also use fs-extra, which provide a lot frequently used file operations.
Sample Code:
var fs = require('fs-extra')
fs.mkdirs('/tmp/some/long/path/that/prob/doesnt/exist', function (err) {
if (err) return console.error(err)
console.log("success!")
})
fs.mkdirsSync('/tmp/another/path')
docs here: https://github.com/jprichardson/node-fs-extra#mkdirsdir-callback
@Liberateur's answer above did not work for me (Node v8.10.0). Little modification did the trick but I am not sure if this is a right way. Please suggest.
// Get modules node
const fs = require('fs');
const path = require('path');
// Create
function mkdirpath(dirPath)
{
try {
fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
}
catch(err) {
try
{
fs.mkdirSync(dirPath);
}
catch(e)
{
mkdirpath(path.dirname(dirPath));
mkdirpath(dirPath);
}
}
}
// Create folder path
mkdirpath('my/new/folder/create');
I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :
LAST UPDATE :
In v10.12.0, NodeJS impletement recursive options :
// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });
UPDATE :
// Get modules node
const fs = require('fs');
const path = require('path');
// Create
function mkdirpath(dirPath)
{
if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
{
try
{
fs.mkdirSync(dirPath);
}
catch(e)
{
mkdirpath(path.dirname(dirPath));
mkdirpath(dirPath);
}
}
}
// Create folder path
mkdirpath('my/new/folder/create');
Raugaral's answer but with -p functionality. Ugly, but it works:
function mkdirp(dir) {
let dirs = dir.split(/\\/).filter(asdf => !asdf.match(/^\s*$/))
let fullpath = ''
// Production directory will begin \\, test is on my local drive.
if (dirs[0].match(/C:/i)) {
fullpath = dirs[0] + '\\'
}
else {
fullpath = '\\\\' + dirs[0] + '\\'
}
// Start from root directory + 1, build out one level at a time.
dirs.slice(1).map(asdf => {
fullpath += asdf + '\\'
if (!fs.existsSync(fullpath)) {
fs.mkdirSync(fullpath)
}
})
}//mkdirp
Here is the ES6 code which I use to create a directory (when it doesn't exist):
const fs = require('fs');
const path = require('path');
function createDirectory(directoryPath) {
const directory = path.normalize(directoryPath);
return new Promise((resolve, reject) => {
fs.stat(directory, (error) => {
if (error) {
if (error.code === 'ENOENT') {
fs.mkdir(directory, (error) => {
if (error) {
reject(error);
} else {
resolve(directory);
}
});
} else {
reject(error);
}
} else {
resolve(directory);
}
});
});
}
const directoryPath = `${__dirname}/test`;
createDirectory(directoryPath).then((path) => {
console.log(`Successfully created directory: '${path}'`);
}).catch((error) => {
console.log(`Problem creating directory: ${error.message}`)
});
Note:
createDirectory
function, I normalize the path to guarantee that the path seperator type of the operating system will be used consistently (e.g. this will turn C:\directory/test
into C:\directory\test
(when being on Windows)fs.exists
is deprecated, that's why I use fs.stat
to check if the directory already existsENOENT
(Error NO ENTry)fs.mkdir
fs.mkdir
over it's blocking counterpart fs.mkdirSync
and because of the wrapping Promise
it will be guaranteed that the path of the directory will only be returned after the directory has been successfully created