Pausing readline in Node.js

后端 未结 3 968
余生分开走
余生分开走 2020-12-06 01:45

Consider the code below ... I am trying to pause the stream after reading the first 5 lines:

var fs          = require(\'fs\');
var readline    = require(\'r         


        
3条回答
  •  无人及你
    2020-12-06 02:17

    add some points:

    .on('pause', function() {
        console.log(numlines)
    })
    

    You will get the 5. It mentioned in the node.js document :

    • The input stream is not paused and receives the SIGCONT event. (See events SIGTSTP and SIGCONT)

    So, I created a tmp buffer in the line event. Use a flag to determine whether it is triggered paused.

    .on('line', function(line) {
       if (paused) {
          putLineInBulkTmp(line);
       } else {
          putLineInBulk(line);
       }
    }
    

    then in the on pause, and resume:

    .on('pause', function() {
        paused = true;
        doSomething(bulk, function(resp) {
            // clean up bulk for the next.
            bulk = [];
            // clone tmp buffer.
            bulk = clone(bulktmp);
            bulktmp = [];
            lr.resume();
        });
    })
    .on('resume', () => {
      paused = false;
    })
    

    Use this way to handle this kind of situation.

提交回复
热议问题