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

前端 未结 29 1425
深忆病人
深忆病人 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 04:54

    Another solution is to run logic via sequential executor nsynjs. It reads file line-by-line using node readline module, and it doesn't use promises or recursion, therefore not going to fail on large files. Here is how the code will looks like:

    var nsynjs = require('nsynjs');
    var textFile = require('./wrappers/nodeReadline').textFile; // this file is part of nsynjs
    
    function process(textFile) {
    
        var fh = new textFile();
        fh.open('path/to/file');
        var s;
        while (typeof(s = fh.readLine(nsynjsCtx).data) != 'undefined')
            console.log(s);
        fh.close();
    }
    
    var ctx = nsynjs.run(process,{},textFile,function () {
        console.log('done');
    });
    

    Code above is based on this exampe: https://github.com/amaksr/nsynjs/blob/master/examples/node-readline/index.js

提交回复
热议问题