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

前端 未结 29 1419
深忆病人
深忆病人 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条回答
  •  滥情空心
    2020-11-22 05:03

    var fs = require('fs');
    
    function readfile(name,online,onend,encoding) {
        var bufsize = 1024;
        var buffer = new Buffer(bufsize);
        var bufread = 0;
        var fd = fs.openSync(name,'r');
        var position = 0;
        var eof = false;
        var data = "";
        var lines = 0;
    
        encoding = encoding || "utf8";
    
        function readbuf() {
            bufread = fs.readSync(fd,buffer,0,bufsize,position);
            position += bufread;
            eof = bufread ? false : true;
            data += buffer.toString(encoding,0,bufread);
        }
    
        function getLine() {
            var nl = data.indexOf("\r"), hasnl = nl !== -1;
            if (!hasnl && eof) return fs.closeSync(fd), online(data,++lines), onend(lines); 
            if (!hasnl && !eof) readbuf(), nl = data.indexOf("\r"), hasnl = nl !== -1;
            if (!hasnl) return process.nextTick(getLine);
            var line = data.substr(0,nl);
            data = data.substr(nl+1);
            if (data[0] === "\n") data = data.substr(1);
            online(line,++lines);
            process.nextTick(getLine);
        }
        getLine();
    }
    

    I had the same problem and came up with above solution looks simular to others but is aSync and can read large files very quickly

    Hopes this helps

提交回复
热议问题