Read a file one line at a time in node.js?

前端 未结 29 1082
深忆病人
深忆病人 2020-11-22 04:33

I am trying to read a large file one line at a time. I found a question on Quora that dealt with the subject but I\'m missing some connections to make the whole thing fit to

29条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:11

    i use this:

    function emitLines(stream, re){
        re = re && /\n/;
        var buffer = '';
    
        stream.on('data', stream_data);
        stream.on('end', stream_end);
    
        function stream_data(data){
            buffer += data;
            flush();
        }//stream_data
    
        function stream_end(){
            if(buffer) stream.emmit('line', buffer);
        }//stream_end
    
    
        function flush(){
            var re = /\n/;
            var match;
            while(match = re.exec(buffer)){
                var index = match.index + match[0].length;
                stream.emit('line', buffer.substring(0, index));
                buffer = buffer.substring(index);
                re.lastIndex = 0;
            }
        }//flush
    
    }//emitLines
    

    use this function on a stream and listen to the line events that is will emit.

    gr-

提交回复
热议问题