Skip to content

Error: ENOENT: no such file or directory, mkdir when trying to create directory

I’m trying to create a folder if it does not exist, using NodeJs. But I’m getting Error: ENOENT: no such file or directory, mkdir when trying to create directory error. How can I fix it?

const folderName = `./images/logger`;

try {
  if (!fs.existsSync(folderName)) {
    fs.mkdirSync(folderName);
  }
} catch (err) {
  console.error(err);
}

Answer

You need to add {recursive:true} option since you want to create more than one directory:

const folderName = `./images/logger`;

try {
if (!fs.existsSync(folderName)) {
  fs.mkdirSync(folderName,{recursive:true});
}
} catch (err) {
 console.error(err);
}