Node 创建多级目录

1,926 阅读1分钟

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')
// })