Node 创建多级目录

测试示例目录结构

w@w:~/my/project-exercise/node-test$ ls
index.js  node_modules  package.json  package-lock.json

index.js

let fs = require('fs')

function mkdirSync(dir, cb) {
  let paths = dir.split('/');
  let index = 1;

  function next(index) {
    if (index > paths.length) return cb();
    let newPath = paths.slice(0, index).join('/');
    fs.stat(newPath, function (err) {
      if (err) {
        fs.mkdir(newPath, function (err) {
          next(index + 1);
        });
      } else {
        next(index + 1);
      }
    })
  }
  next(index);
}

// call mkdirSync func
// mkdirSync(paths, function () {
//   console.log('success')
// })


// eg.
// mkdirSync('/home/w/my/project-exercise/node-test/abc/abc_1/abc_2', function () {
//   console.log('success')
// })

package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "fs": "0.0.1-security"
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容