如果目录不存在,下面的方法是否正确?
它应该对脚本具有完全的权限,并且其他人可以阅读。
var dir = __dirname + '/upload';
if (!path.existsSync(dir)) {
fs.mkdirSync(dir, 0744);
}
如果目录不存在,下面的方法是否正确?
它应该对脚本具有完全的权限,并且其他人可以阅读。
var dir = __dirname + '/upload';
if (!path.existsSync(dir)) {
fs.mkdirSync(dir, 0744);
}
当前回答
一行解决方案:如果目录不存在,则创建该目录
// import
const fs = require('fs') // In JavaScript
import * as fs from "fs" // in TypeScript
import fs from "fs" // in Typescript
// Use
!fs.existsSync(`./assets/`) && fs.mkdirSync(`./assets/`, { recursive: true })
其他回答
下面是一个递归创建目录的小函数:
const createDir = (dir) => {
// This will create a dir given a path such as './folder/subfolder'
const splitPath = dir.split('/');
splitPath.reduce((path, subPath) => {
let currentPath;
if(subPath != '.'){
currentPath = path + '/' + subPath;
if (!fs.existsSync(currentPath)){
fs.mkdirSync(currentPath);
}
}
else{
currentPath = subPath;
}
return currentPath
}, '')
}
最好的解决方案是使用名为node-fs-extra的npm模块。它有一个名为mkdir的方法,用于创建您提到的目录。如果您给出一个较长的目录路径,它将自动创建父文件夹。这个模块是npm模块fs的超集,所以如果你添加了这个模块,你也可以使用fs中的所有函数。
使用Node.js 10 + ES6:
import path from 'path';
import fs from 'fs';
(async () => {
const dir = path.join(__dirname, 'upload');
try {
await fs.promises.mkdir(dir);
} catch (error) {
if (error.code === 'EEXIST') {
// Something already exists, but is it a file or directory?
const lstat = await fs.promises.lstat(dir);
if (!lstat.isDirectory()) {
throw error;
}
} else {
throw error;
}
}
})();
我想添加一个TypeScript承诺重构josh3736的答案。
它做的是同样的事情,有同样的边界情况。它只是碰巧使用Promises, TypeScript typedefs,并使用“use strict”。
// https://en.wikipedia.org/wiki/File_system_permissions#Numeric_notation
const allRWEPermissions = parseInt("0777", 8);
function ensureFilePathExists(path: string, mask: number = allRWEPermissions): Promise<void> {
return new Promise<void>(
function(resolve: (value?: void | PromiseLike<void>) => void,
reject: (reason?: any) => void): void{
mkdir(path, mask, function(err: NodeJS.ErrnoException): void {
if (err) {
if (err.code === "EEXIST") {
resolve(null); // Ignore the error if the folder already exists
} else {
reject(err); // Something else went wrong
}
} else {
resolve(null); // Successfully created folder
}
});
});
}
使用async / await:
const mkdirP = async (directory) => {
try {
return await fs.mkdirAsync(directory);
} catch (error) {
if (error.code != 'EEXIST') {
throw e;
}
}
};
你需要承诺fs:
import nodeFs from 'fs';
import bluebird from 'bluebird';
const fs = bluebird.promisifyAll(nodeFs);