Home >Web Front-end >Front-end Q&A >nodejs mkdir error report
Recently, while using Node.js, I encountered a mkdir error problem. When I tried to use the fs.mkdir() method to create a new directory, the system threw the following error message:
Error: ENOENT: no such file or directory, mkdir 'path/to/new/directory'
The first thing I thought of was the path problem, so I checked whether the path was correct. . It turned out that the path was correct, which made me a little confused.
I looked back and forth through the code and finally found the problem. In fact, the prompt of this error message is already very obvious-no such file or directory. That is, this error is not caused by an incorrect path, but by the file or folder not existing.
The problem is that I did not create the superior directory in the path before using the mkdir method to create the directory. In this case, the fs.mkdir() method only creates the last level directory in the path, not intermediate directories.
For example, before creating the path/to/new/directory directory, the path/to/ directory must be created first, otherwise an ENOENT error will result.
To solve this problem, we only need to use the fs.mkdirSync() method to recursively create the intermediate directory before using the mkdir method. The following is an implemented sample code:
const fs = require('fs'); const path = require('path'); function mkdirSyncR(targetDir) { const sep = path.sep; const initDir = path.isAbsolute(targetDir) ? sep : ''; targetDir.split(sep).reduce((parentDir, childDir) => { const curDir = path.resolve(parentDir, childDir); try { if (!fs.existsSync(curDir)) { fs.mkdirSync(curDir); } } catch (err) { if (err.code !== 'EEXIST') { throw err; } } return curDir; }, initDir); } const newDir = 'path/to/new/directory'; mkdirSyncR(path.dirname(newDir)); fs.mkdirSync(newDir);
The mkdirSyncR() method in this sample code can recursively create a directory and determine whether the directory exists when creating the directory. Before using the mkdir() method to create a directory, we first use the part of the path excluding the last level directory (that is, calling the path.dirname() method) to create an intermediate directory.
Now, we can create a new directory smoothly.
Summary
When using the mkdir method in Node.js, if the intermediate directory of the directory does not exist, an ENOENT error will occur. To solve this problem, we can first use the fs.mkdirSync() method to recursively create an intermediate directory, and then use the fs.mkdir() method to create a new directory.
The above is the detailed content of nodejs mkdir error report. For more information, please follow other related articles on the PHP Chinese website!