异步递归文件系统遍历

时间:2018-02-13 17:08:40

标签: node.js fs

我试图用一些特定文件中的数据编译数组,使用递归方法读取目录,文件系统方法是异步的。我无法弄清楚回调调用的适当位置。

const fs = require('fs');
const ENTRY =  "../a/b";
const FILE_NAME = 'index.json';
var nodes = [];

function doThisOnceDone() {
    console.log(nodes);
}

function readFile(path) {
    fs.readFile(path + '/' + FILE_NAME,{
        encoding:"UTF-8"
    }, function(err, data) {
        if(err) {
            return;
        }
        nodes.push(data);
    });
}
function compileArray(path, callback) {
    fs.readdir(path, {
        encoding:"UTF-8"
    }, function(err, files) {
        if(err) {
            console.error(err);
            return;
        }
        files.forEach(function(file) {
            var nextPath = path + '/' + file;
            fs.stat(nextPath, function(err, stats) {
                if(err) {
                    return;
                }
                if(stats.isDirectory()) {
                    if(file === 'specific') {
                        readFile(nextPath);
                    }
                    else {
                        compileArray(nextPath);
                    }
                }
            });
        });
    });
}

compileArray(ENTRY, doThisOnceDone);

我什么时候知道递归树已经完成,我可以访问节点数组?

2 个答案:

答案 0 :(得分:0)

试试这个

const util = require('util');
const fs = require('fs');
const stat = util.promisify(fs.stat);
const readFile = util.promisify(fs.readFile);
const readdir = util.promisify(fs.readdir);

const ENTRY = "../a/b";
const FILE_NAME = 'index.json';
var nodes = [];

const compileArray = async (path) => {
    try {
        const files = await readdir(path);
        files.forEach((file) => {
            try {
                var nextPath = path + '/' + file;
                const stats = await stat(nextPath); //check other conditions
                if (file === 'specific') {
                    const data = await readFile(path + '/' + FILE_NAME, {
                        encoding: "UTF-8"
                    });
                    nodes.push(data);
                }
            } catch (error) {
                console.log(error);
            }
        });
    } catch (error) {
        console.log(error);
    }
}

答案 1 :(得分:0)

interface counts_t{
    time?: string,
    messages?: number
}

var data: counts_t[] = [
    { time: '9:54' }, 
    { time: '9:55' }, 
    { time: '9:56' }, 
    { time: '9:57' }
];

    var counts = data.reduce((newArray:counts_t, item:counts_t) => {
       let time = item.time;
       if (!newArray.hasOwnProperty(time)) {
           newArray[time] = 0;
       } 
       newArray[time]++;
       return newArray;
    }, {});

    console.log(counts);

    var countsExtended: counts_t[] = Object.keys(counts).map(k => {
       return { time: k, messages: counts[k] };
    });

   console.log(countsExtended);