我需要一个函数,该函数从带有换行符的文件中发出单独的行。没什么难的。
但是使用node很难,而使用Meteor则有另外一个复杂之处:您必须使用Meteor.wrapAsync
。令人惊讶的是,wrapAsync
在文档中没有如何使用的示例,而我在网上只能找到几个示例,没有一个有帮助。
我有类似的东西:
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);
我知道这是错误的,因为它不起作用,那么我该怎么写呢?
有两种解决方法。
您需要调整自己喜欢的流方法的示例代码:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句