How to read from stdin line by line in Node

前端 未结 8 1395
闹比i
闹比i 2020-11-28 01:47

I\'m looking to process a text file with node using a command line call like:

node app.js < input.txt

Each line of the file needs to be proce

相关标签:
8条回答
  • 2020-11-28 02:37

    shareing for others:

    read stream line by line,should be good for large files piped into stdin, my version:

    var n=0;
    function on_line(line,cb)
    {
        ////one each line
        console.log(n++,"line ",line);
        return cb();
        ////end of one each line
    }
    
    var fs = require('fs');
    var readStream = fs.createReadStream('all_titles.txt');
    //var readStream = process.stdin;
    readStream.pause();
    readStream.setEncoding('utf8');
    
    var buffer=[];
    readStream.on('data', (chunk) => {
        const newlines=/[\r\n]+/;
        var lines=chunk.split(newlines)
        if(lines.length==1)
        {
            buffer.push(lines[0]);
            return;
        }   
    
        buffer.push(lines[0]);
        var str=buffer.join('');
        buffer.length=0;
        readStream.pause();
    
        on_line(str,()=>{
            var i=1,l=lines.length-1;
            i--;
            function while_next()
            {
                i++;
                if(i<l)
                {
                    return on_line(lines[i],while_next);
                }
                else
                {
                    buffer.push(lines.pop());
                    lines.length=0;
                    return readStream.resume();
                }
            }
            while_next();
        });
      }).on('end', ()=>{
          if(buffer.length)
              var str=buffer.join('');
              buffer.length=0;
            on_line(str,()=>{
                ////after end
                console.error('done')
                ////end after end
            });
      });
    readStream.resume();
    
    0 讨论(0)
  • 2020-11-28 02:38
    // Work on POSIX and Windows
    var fs = require("fs");
    var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0
    console.log(stdinBuffer.toString());
    
    0 讨论(0)
提交回复
热议问题