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
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.mkdirfs.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