Is this the right way to create a directory if it doesn\'t exist. It should have full permission for the script and readable by others.
var dir = __dirname +
fs.exist() is deprecated. So I have used fs.stat() to check the directory status. If the directory does not exist fs.stat() throw an error with message like 'no such file or directory'. Then I have created a directory.
const fs = require('fs').promises;
const dir = './dir';
fs.stat(dir).catch(async (err) => {
if (err.message.includes('no such file or directory')) {
await fs.mkdir(dir);
}
});
Using async / await:
const mkdirP = async (directory) => {
try {
return await fs.mkdirAsync(directory);
} catch (error) {
if (error.code != 'EEXIST') {
throw e;
}
}
};
You will need to promisify fs
:
import nodeFs from 'fs';
import bluebird from 'bluebird';
const fs = bluebird.promisifyAll(nodeFs);
I had to create sub-directories if they didn't exist. I used this:
const path = require('path');
const fs = require('fs');
function ensureDirectoryExists(p) {
//console.log(ensureDirectoryExists.name, {p});
const d = path.dirname(p);
if (d && d !== p) {
ensureDirectoryExists(d);
}
if (!fs.existsSync(d)) {
fs.mkdirSync(d);
}
}
With the fs-extra package you can do this with a one-liner:
const fs = require('fs-extra');
const dir = '/tmp/this/path/does/not/exist';
fs.ensureDirSync(dir);
With Node 10 + ES6:
import path from 'path';
import fs from 'fs';
(async () => {
const dir = path.join(__dirname, 'upload');
try {
await fs.promises.mkdir(dir);
} catch (error) {
if (error.code === 'EEXIST') {
// Something already exists, but is it a file or directory?
const lstat = await fs.promises.lstat(dir);
if (!lstat.isDirectory()) {
throw error;
}
} else {
throw error;
}
}
})();
The best solution would be to use the npm module called node-fs-extra. It has a method called mkdir
which creates the directory you mentioned. If you give a long directory path, it will create the parent folders automatically. The module is a super set of npm module fs
, so you can use all the functions in fs
also if you add this module.