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

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

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

当前回答

对于个人dirs:

var fs = require('fs');
var dir = './tmp';

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}

或者,对于嵌套的dirs:

var fs = require('fs');
var dir = './tmp/but/then/nested';

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir, { recursive: true });
}

其他回答

我的解决方案

CommonJS


var fs = require("fs");

var dir = __dirname + '/upload';

// if (!fs.existsSync(dir)) {
//   fs.mkdirSync(dir);
// }

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir, {
    mode: 0o744,
  });
  // mode's default value is 0o744
}

ESM

更新包。json配置

{
  //...
  "type": "module",
  //...
}
import fs from "fs";
import path from "path";

// create one custom `__dirname`, because it not exist in es-module env ⚠️
const __dirname = path.resolve();

const dir = __dirname + '/upload';

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}

// OR
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir, {
    mode: 0o744,
  });
  // mode's default value is 0o744
}

refs

https://nodejs.org/api/fs.html#fsexistssyncpath

https://github.com/nodejs/help/issues/2907#issuecomment-671782092

解决方案

CommonJS

const fs = require('fs');
const path = require('path');

const dir = path.resolve(path.join(__dirname, 'upload');

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}

// OR
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir, {
    mode: 0o744, // Not supported on Windows. Default: 0o777
  });
}

ESM

更新您的包。Json文件配置

{
  // declare using ECMAScript modules(ESM)
  "type": "module",
  //...
}
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// create one custom `__dirname`, because it does not exist in es-module env ⚠️
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const dir = path.resolve(path.join(__dirname, 'upload');

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}

// OR
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir, {
    mode: 0o744, // Not supported on Windows. Default: 0o777
  });
}

更新2022

import { existsSync } from 'node:fs';

refs

NodeJS版本:v18.2.0

https://nodejs.org/api/fs.html#fsexistssyncpath

https://nodejs.org/api/fs.html#fsmkdirsyncpath-options

https://nodejs.org/api/url.html#urlfileurltopathurl

https://github.com/nodejs/help/issues/2907#issuecomment-757446568

ESM: ECMAScript模块

https://nodejs.org/api/esm.html#introduction

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

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

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

您可以使用Node.js文件系统命令fs。Stat检查目录是否存在。Mkdir创建一个带有回调的目录,或fs. Mkdir。mkdirSync创建一个没有回调的目录,如下所示:

// First require fs
const fs = require('fs');

// Create directory if not exist (function)
const createDir = (path) => {
    // Check if dir exist
    fs.stat(path, (err, stats) => {
        if (stats.isDirectory()) {
            // Do nothing
        } else {
            // If the given path is not a directory, create a directory
            fs.mkdirSync(path);
        }
    });
};

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