Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ENOENT, no such file or directory on fs.mkdirSync

Tags:

node.js

I'm currently starting up my NodeJS application and I have the following if-statement:

Error: ENOENT, no such file or directory './realworks/objects/'     at Object.fs.mkdirSync (fs.js:654:18)     at Object.module.exports.StartScript (/home/nodeusr/huizenier.nl/realworks.js:294:7) 

The weird thing, however, is that the folder exists already, but the check fails on the following snippet:

if(fs.existsSync(objectPath)) {     var existingObjects = fs.readdirSync(objectPath);     existingObjects.forEach(function (objectFile) {         var object = JSON.parse(fs.readFileSync(objectPath+objectFile));         actualObjects[object.ObjectCode] = object;     }); }else{     fs.mkdirSync(objectPath); // << this is line 294 } 

I fail to understand how a no such file or directory can occur on CREATING a directory.

like image 853
Ruben Rutten Avatar asked Feb 13 '15 11:02

Ruben Rutten


People also ask

What is Enoent?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

What is fs mkdir?

Creating Permanent Directories with fs. mkdir Family of Functions. To create permanent directories, we can use the mkdir function to create them asynchronously. It takes 3 arguments. The first argument is the path object, which can be a string, a Buffer object or an URL object.


2 Answers

When any folder along the given path is missing, mkdir will throw an ENOENT.

There are 2 possible solutions (without using 3rd party packages):

  • Recursively call fs.mkdir for every non-existent directory along the path.
  • Use the recursive option, introduced in v10.12:
    fs.mkdir('./path/to/dir', {recursive: true}, err => {})
like image 175
Yoav Kadosh Avatar answered Oct 01 '22 17:10

Yoav Kadosh


Solve here How to create full path with node's fs.mkdirSync?

NodeJS version 10.12.0 has added a native support for both mkdir and mkdirSync to create a directory recursively with recursive: true option as the following:

fs.mkdirSync(targetDir, { recursive: true }); 

And if you prefer fs Promises API, you can write

fs.promises.mkdir(targetDir, { recursive: true }); 
like image 31
ztvmark Avatar answered Oct 01 '22 17:10

ztvmark