如何使用Node.js创建一个目录(文件夹)如果它不存在

1145

如果目录不存在,以下是创建目录的正确方法吗?

脚本应该拥有完全权限,并可被其他人阅读。

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

4
在提问之前,你尝试运行你的脚本了吗?当我尝试运行时,我收到了 TypeError: path.existsSync is not a function 的错误提示(我正在使用 Node v8.10)。 - Jean Paul
3
根据官方API文档 https://nodejs.org/api/fs.html#fsexistssyncpath,应该使用`fs.existsSync(dir)`而不是`path.existsSync(dir)`。 - xgqfrms
24个回答

1
这里有一个递归创建目录的小函数:
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
  }, '')
}

1

my solutions

  1. 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
}

  1. ESM

更新 package.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


0

使用 async/await:

const mkdirP = async (directory) => {
  try {
    return await fs.mkdirAsync(directory);
  } catch (error) {
    if (error.code != 'EEXIST') {
      throw e;
    }
  }
};

你需要将fs转换为Promise:
import nodeFs from 'fs';
import bluebird from 'bluebird';

const fs = bluebird.promisifyAll(nodeFs);

promisifyAll() 是从哪里来的?Node.js?某个 Node.js 模块?还是其他什么东西? - Peter Mortensen
bluebird 包中 - sdgfsdh
Bluebird - Peter Mortensen

0
一个异步执行此操作的函数(从一个使用同步函数的类似 SO 答案进行了调整,但现在我找不到了)。
// ensure-directory.js
import { mkdir, access } from 'fs'

/**
 * directoryPath is a path to a directory (no trailing file!)
 */
export default async directoryPath => {
  directoryPath = directoryPath.replace(/\\/g, '/')

  // -- preparation to allow absolute paths as well
  let root = ''
  if (directoryPath[0] === '/') {
    root = '/'
    directoryPath = directoryPath.slice(1)
  } else if (directoryPath[1] === ':') {
    root = directoryPath.slice(0, 3) // c:\
    directoryPath = directoryPath.slice(3)
  }

  // -- create folders all the way down
  const folders = directoryPath.split('/')
  let folderPath = `${root}`
  for (const folder of folders) {
    folderPath = `${folderPath}${folder}/`

    const folderExists = await new Promise(resolve =>
      access(folderPath, error => {
        if (error) {
          resolve(false)
        }
        resolve(true)
      })
    )

    if (!folderExists) {
      await new Promise((resolve, reject) =>
        mkdir(folderPath, error => {
          if (error) {
            reject('Error creating folderPath')
          }
          resolve(folderPath)
        })
      )
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接