barretlee / Node-Daily-Practice

每天写个小程序。
https://github.com/barretlee/Node-Daily-Practice/issues
MIT License
30 stars 2 forks source link

Day2 遍历文件 #2

Open barretlee opened 9 years ago

barretlee commented 9 years ago

问题:遍历某个目录下所有的 json 文件,将这些文件的文件名和文件目录保存到指定的位置。

后续思考:

  1. 过滤 node_module 文件件下的 JSON 文件
  2. 使用同步方式编写异步代码
  3. 使用 Promise 编程,让程序更加易读
  4. 当文件层级达到一千层的时候如何优化代码
barretlee commented 9 years ago
var fs = require('fs');
var Path = require('path');

var ROOT = "../../../work";
var ret = [];
var output = "./output.json";

function walk(path){
    var files = fs.readdirSync(path);
    files.forEach(function(file){
        var filePath = Path.join(path, file);

        if(/node_module/.test(filePath)) return;

        if(fs.statSync(filePath).isDirectory()){
            walk(filePath);
        } else {
            if(/\.json$/.test(file)){
                console.log('> DEBUG: ' + filePath);
                ret.push({
                    name: file,
                    path: filePath/*,
                    file: fs.readFileSync(filePath)*/
                });
            }
        }
    });
}

walk(ROOT);
fs.writeFileSync(output, JSON.stringify(ret, null, 2));

同步方式写代码。