有没有使用原始Q承诺库节点递归遍历目录异步的例子吗? [英] Is there an example of using raw Q promise library with node to recursively traverse a directory asynchronously?

查看:162
本文介绍了有没有使用原始Q承诺库节点递归遍历目录异步的例子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道IO-Q,做异步IO造成的承诺图书馆。但是我正在寻找使用Q库递归遍历目录结构,在最终的结果是所有的一切的目录中提供的一些功能,在文件夹中启动文件列表的一个简单的例子,但在这个过程夷为平地为文件名的单个阵列。

I am aware of io-q, the library that does async IO resulting in promises. But I'm looking for a simple example of using the Q library to recursively traverse a directory structure, where the final result is a list of all the files in all the directories starting in the folder provided to some function, but flattened in the process to a single array of file names.

有这个在那里的一个例子吗?或者,也许有,是不是递归的,这是很好的一个例子。我猜这是pretty简单,但是这是我第一次接触到两个异步/承诺。

Is there an example of this out there? Or perhaps there's an example that isn't recursive, which is fine. I'm guessing this is pretty simple, but this is my first exposure to both async/promises.

推荐答案

我发现这个主旨这你想要做什么,很容易promisify:

I found this gist which does what you want and is easy to promisify:

var Q = require('q'),
    fs = require('fs'),
    p = require('path');
function readDir(path) {
    return Q.nfcall(fs.lstat, path).then(function(stat) {
        if (stat.isDirectory()) {
            return Q.nfcall(fs.readdir, path).then(function(files) {
                return Q.all(files
                // .map(p.join.bind(p, path)).map(readDir)
                .map(function(file) {
                    return readDir(p.join(path, file));
                })
                ).then(
                // Function.apply.bind(Array.prototype.concat, [])
                function(results) {
                    return [].concat.apply([], results);
                });
            });
        } else {
            return [path];
        }
    });
}

它使用 nfcall 以获取文件系统API的承诺和 Q.all 串联之前等待所有子目录的结果。

It uses nfcall to get promises for the filesystem API and Q.all to wait for all subdirectory results before concatenating them.

这篇关于有没有使用原始Q承诺库节点递归遍历目录异步的例子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆