美文网首页
Node 创建多级目录

Node 创建多级目录

作者: 草帽lufei | 来源:发表于2019-10-12 19:23 被阅读0次

    测试示例目录结构

    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"
      }
    }
    

    相关文章

      网友评论

          本文标题:Node 创建多级目录

          本文链接:https://www.haomeiwen.com/subject/kkwnwqtx.html