ES6实现的遍历目录函数示例

// npm init // npm install koa --save-dev // node --harmony app.js const fs = require('fs'); var eachDir = (() => { let queue = []; var eachFiles = (options) => { if (queue.length) { let path = queue.shift(); fs.readdir(path, (err, files) => { if (err) { options.fail(err); return; } files.forEach((file, i) => { let url = path + 'https://www.jb51.net/' + file; let stats = fs.statSync(url); if (stats.isDirectory()) { queue.push(url); } else { options.callback && options.callback.call(stats, { name: file, size: stats.size, path: url }); } }); eachFiles(options); }); } else { options.done(); } }; return (path, options) => { let stats = fs.statSync(path); if (stats.isDirectory()) { queue.push(path); } eachFiles(options); }; })(); let total = 0, fileTypes = {}; eachDir('./', { callback(file) { let ret = file.name.match(/\.(\w+$)/); if (ret) { if (!fileTypes[ret[0]]) { fileTypes[ret[0]] = 0; } fileTypes[ret[0]] += 1; } // console.log(file); total++; }, done() { console.log(total, fileTypes); fs.writeFile('./result.txt', JSON.stringify(fileTypes), (err) => { if (err) throw err; console.log('done'); }); }, fail(err) { console.log(err); } });

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwyzjp.html