// Getting error throw new Error(`Error creating log folder ${logFolder} -
// ${JSON.stringify(e)}`);
// Error: Error creating log folder ./logs/Pranjals-MacBook-Air.local -
// {"errno":-2,"code":"ENOENT","syscall":"mkdir","path":"./logs/Pranjals-
// MacBook-Air.local"}
// I am trying to create new directory if do not exists but it's throwing
// me the error
let logFolder = `./logs/${os.hostname()}`;
if (!fs.existsSync(logFolder)) {
try {
fs.mkdirSync(logFolder);
} catch(e) {
throw new Error(`Error creating log folder ${logFolder} - ${JSON.stringify(e)}`);
}
}
答案 0 :(得分:0)
要递归创建目录,我使用的是mkdirp包。
这里是一个例子:
/**
* CREATE DIR SYNC
* Used to create a directory
* @param {String} path
*/
let createDirSync = function (path = '') {
const fs = require('fs');
const mkdirp = require('mkdirp');
if (!fs.existsSync(path)) {
mkdirp.sync(path);
}
};
createDirSync('/path/to/create/');
希望有帮助。
答案 1 :(得分:0)
与@Sparw的答案相比,您可以在不使用库的情况下进行操作。 nodejs v10.x
,并将递归选项设置为true。
let logFolder = `./logs/${os.hostname()}`;
if (!fs.existsSync(logFolder)) {
try {
await fs.promises.mkdir(logFolder, { recursive: true }) //or fs.mkdirSync(logFolder, { recursive: true })
} catch(e) {
throw new Error(`Error creating log folder ${logFolder} - ${JSON.stringify(e)}`);
}
}
答案 2 :(得分:0)
///我只是简单地将'{recursive:true}'属性添加为第二个参数 对我来说很好
let logFolder = `logs/${os.hostname()}`;
if (!fs.existsSync(logFolder)) {
try {
fs.mkdirSync(logFolder, { recursive: true })
} catch(e) {
throw new Error(`Error creating log folder ${logFolder} - ${JSON.stringify(e)}`);
}
}