我有以下问题。我想阅读一个文件,在行读取之间有一个非阻塞暂停。我使用wait.for和lazy分别等待和读取文件。
当我调用等待时,我得到错误:wait.for只能在光纤内部调用任何人都可以告诉我如何访问线对象。我试图创建一个单独的函数,但后来我丢失了持有该行的行变量。
var lazy = require("lazy"),
fs = require("fs");
wait = require('wait.for');
wait.helper={};
wait.helper.timeout_callback = function(ms,callback){
setTimeout(callback,ms); //call callback(null,null) in ms miliseconds
}
wait.miliseconds = function(ms){
wait.for(wait.helper.timeout_callback,ms);
}
function test(){
new lazy(fs.createReadStream('./test.txt'))
.lines
.forEach(
function(line){
//wait.miliseconds(1*1000); // this causes Error: wait.for can only be called inside a fiber
console.log(line.toString());
}
);
}
wait.launchFiber(test);
答案 0 :(得分:1)
如果您不介意非光纤解决方案,可以使用回调方式:
var fs = require('fs');
var stream = fs.createReadStream('file.txt');
stream.on('data', onData).buffer = '';
function onData(chunk) {
var i, hasData = Buffer.isBuffer(chunk);
if (hasData) {
stream.buffer += chunk.toString('utf8');
if (stream.paused)
return;
}
if ((i = stream.buffer.indexOf('\n')) > -1) {
var line = stream.buffer.substring(0, i);
stream.buffer = stream.buffer.substring(i + 1);
stream.pause();
stream.paused = true;
onLine(line, onData);
} else if (!hasData) {
stream.resume();
stream.paused = false;
}
}
function onLine(line, cb) {
setTimeout(function() {
// do something with line
console.log(line);
cb();
}, 1000);
}