我需要一个从带有换行符的文件中发出单独行的函数。没什么难的。
但是对于节点来说,这很难,而且对于Meteor来说,还有一个额外的复杂因素:你必须使用Meteor.wrapAsync
。令人惊讶的是,没有一个如何使用wrapAsync
in the docs的示例,我只能在网上找到几个例子,但没有一个帮助过。
我有类似的东西:
var readFileAsync = function (file, cb) {
// From here to below comment works synchronously
var instream = fs.createReadStream(file, function () {
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;
var rl = readline.createInterface({
input: instream,
output: outstream,
terminal: false
});
rl.on('line', function(line) {
console.log(line);
return line;
});
});
// Reference to aforementioned comment
};
var readWatFile = Meteor.wrapAsync(readFileAsync);
var line = readWatFile('/path/to/my/file');
console.log(line);
我知道这是错的,因为它不起作用,所以我该怎么写呢?
答案 0 :(得分:1)
有两种方法可以绕过它。
您需要调整到您喜爱的流媒体方法的示例代码:
var Future = Npm.require('fibers/future');
var byline = Npm.require('byline');
var f = new Future;
// create stream in whatever way you like
var instream = fs.createReadStream(...);
var stream = byline.createStream(instream);
// run stream handling line-by-line events asynchronously
stream.on('data', Meteor.bindEnvironment(function (line) {
if (line) console.log(line)
else future.return();
}));
// await on the future yielding to the other fibers and the line-by-line handling
future.wait();