Node.js 节点流-在流完成时进行同步以返回数组。
我编写这个函数是为了从流中提取文件列表。它可以工作,但是流是异步的,Node.js 节点流-在流完成时进行同步以返回数组。,node.js,stream,Node.js,Stream,我编写这个函数是为了从流中提取文件列表。它可以工作,但是流是异步的,文件数组在流完成之前返回。我真的不想使用promise库……尽可能地简化代码。流完成后,如何返回文件数组 function fileList(source) { var files = []; source.pipe(through2.obj(function(obj, enc, next) { file = obj.history[0].split("/").pop(); fil
文件
数组在流完成之前返回。我真的不想使用promise库……尽可能地简化代码。流完成后,如何返回文件
数组
function fileList(source) {
var files = [];
source.pipe(through2.obj(function(obj, enc, next) {
file = obj.history[0].split("/").pop();
files.push(file);
next();
}));
return files;
}
提供回调,而不是从函数返回值:
function fileList(source, callback) {
var files = [];
source.pipe(through2.obj(function(obj, enc, next) {
file = obj.history[0].split("/").pop();
files.push(file);
next();
}, function(flushcb) {
flushcb();
callback(null, files);
}));
}
// ...
fileList(stream, function(err, files) {
if (err) throw err;
// use `files` here ...
});
不能使异步操作同步。只是不能在JS中完成。使用回调、承诺或类似的方式进行异步设计以返回值。快速提问,flushcb()在这里做什么,它在哪里定义?该函数与streams2中的函数相同。它表示流的
end()
已被调用。我应该澄清一下:我的意思是第二个函数是\u flush()
等效函数。对flushcb()
的实际调用只是让node知道,您已经完成了刷新任何我们可能出于任何原因在内部缓冲的数据(在这种情况下,我们没有这样的数据,所以我们只是立即调用回调)。