Search code examples
javascriptnode.jsnpmtext-filesline

How to iterate through all lines in "line-by-line" npm?


As a temporary method, I use a .txt file to store certain variables of my program. Writing goes perfectly with fs.appendFile, but given the size of it, reading with fs.readFile is not suitable - I'd like to get a certain line from the file, and npm line-by-line was told me may help.

I'm a bit lost with it, though. This is a function I call:

function LBL_SetValueToLine(path, lineid, value){

    var lr = new lblreader(path);
    var m = 0;

    lr.on('line', function (line) {
        // 'line' contains the current line without the trailing newline character.
        m=+1;
        if(m==lineid){ value = line; };
    });

};

And the call itself happens as a usual function call, with all input variable being surely proper.

I should have thought this is not a proper method, but the documentation said, this is the synchronous method. However, I can see that the work of .on is asysnc, because of the function input it needs.

Not sure if it has anything to do with the problem, but anyways, console.log after the function call always indicated that the variable hasn't been changed.

How can I do it?


Solution

  • You can use the Readline module that is provided by the Core Node API.

    Readline API Example for Line-by-Line

    const readline = require('readline');
    const fs = require('fs');
    
    const rl = readline.createInterface({
      input: fs.createReadStream('sample.txt')
    });
    
    rl.on('line', (line) => {
      console.log('Line from file:', line);
    });
    

    The example above was taken from the Node Readline API Docs