Pregunta

I have the following problem. I would like to read a file with a non blocking pause between line reads. I use wait.for and lazy to wait and read the file respectively.

When I call the wait I get Error: wait.for can only be called inside a fiber Could anyone tell me how to access the line object. I tried to make a separate function but then I lose the line variable holding the line.

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);
¿Fue útil?

Solución

If you don't mind a non-fiber solution, here is one using callbacks:

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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top