首先现在安装yflow
yflow 借助es6 生成器函数来解决金字塔回调问题。
这个连接
http://faylai.iteye.com/blog/1924523
是我先前使用async 做的但是代码超长不好理解,写做困难。
比较下面的实现简直就是nodejs的曙光啊
---------------------------------------------------------------------------
首先安装 yflow 组建 :npm install yflow
var yflow = require("yflow"); var FS = require("fs"); var fs = yflow.wrap(FS); var path = require("path"); // 检测文件或者文件夹是否存在 var isExists = yflow.wrap(function (dir, cb) { FS.exists(dir, function (isExist) { cb(null, isExist); }); }); // 创建多级目录 function mkdirs(p, mode, f, made) { if (typeof mode === 'function' || mode === undefined) { f = mode; mode = 0777 & (~process.umask()); } if (!made) { made = null; } var cb = f || function () {}; if (typeof mode === 'string') { mode = parseInt(mode, 8); } yflow( function * () { p = path.resolve(p); var startDir = p; while (true) { var exist = yield isExists(startDir); if (exist) { break; } else { startDir = path.dirname(startDir); } } var slashees = p.split(startDir)[1].split(path.sep); for (var i = 0; i < slashees.length; i++) { var slashee = slashees[i].trim(); if (slashee != '') { startDir = path.join(startDir, slashee); yield fs.mkdir(startDir, mode); } } })(f) } // 单个文件复制 function copyFile(file, toDir, cb) { yflow(function * () { yield yflow.wrap(mkdirs)(toDir); var reads = FS.createReadStream(file); var writes = FS.createWriteStream(path.join(path.resolve(toDir), path.basename(file))); reads.pipe(writes); reads.on("end", function () { writes.end(); }); })(cb); } //文件夹复制 function copyDir(from, to, cb) { yflow(function * () { var stat = yield isExists(from); stat = yield fs.stat(from); if (stat.isFile()) { yield yflow.wrap(copyFile)(from, to); } else if (stat.isDirectory) { var files = yield fs.readdir(from); for (var i = 0; i < files.length; i++) { var newFile = path.join(from, files[i]); stat = yield fs.stat(newFile); if (stat.isFile()) { yield yflow.wrap(copyFile)(newFile, to); } else if (stat.isDirectory()) { yield yflow.wrap(copyDir)(newFile, path.join(to, files[i])); } } } })(cb); }
测试代码如下:
copyDir("F:\\jar", "F:\\jar2", function (e) { if (e) { console.log(e.stack); } else { console.log("copy ok!"); } })