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.
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
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.
When any folder along the given path is missing, mkdir
will throw an ENOENT
.
There are 2 possible solutions (without using 3rd party packages):
fs.mkdir
for every non-existent directory along the path. recursive
option, introduced in v10.12:fs.mkdir('./path/to/dir', {recursive: true}, err => {})
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With