如果目录不存在,下面的方法是否正确?

它应该对脚本具有完全的权限,并且其他人可以阅读。

var dir = __dirname + '/upload';
if (!path.existsSync(dir)) {
    fs.mkdirSync(dir, 0744);
}

当前回答

使用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);

其他回答

单行版本:

// Or in TypeScript: import * as fs from 'fs';
const fs = require('fs');
!fs.existsSync(dir) && fs.mkdirSync(dir);
var dir = 'path/to/dir';
try {
  fs.mkdirSync(dir);
} catch(e) {
  if (e.code != 'EEXIST') throw e;
}

使用fs-extra包,你可以用一行代码做到这一点:

const fs = require('fs-extra');

const dir = '/tmp/this/path/does/not/exist';
fs.ensureDirSync(dir);

如果文件夹存在,您可以使用mkdir并捕获错误。 这是异步的(因此是最佳实践)并且安全。

fs.mkdir('/path', err => { 
    if (err && err.code != 'EEXIST') throw 'up'
    .. safely do your stuff here  
    })

(可选地使用mode添加第二个参数。)


其他的想法:

You could use then or await by using native promisify. const util = require('util'), fs = require('fs'); const mkdir = util.promisify(fs.mkdir); var myFunc = () => { ..do something.. } mkdir('/path') .then(myFunc) .catch(err => { if (err.code != 'EEXIST') throw err; myFunc() }) You can make your own promise method, something like (untested): let mkdirAsync = (path, mode) => new Promise( (resolve, reject) => mkdir (path, mode, err => (err && err.code !== 'EEXIST') ? reject(err) : resolve() ) ) For synchronous checking, you can use: fs.existsSync(path) || fs.mkdirSync(path) Or you can use a library, the two most popular being mkdirp (just does folders) fsextra (supersets fs, adds lots of useful stuff)

我想添加一个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
                }
            });
    });
}