Search code examples
javascriptnode.jsterminalfilestream

Doubled output on screen in Node.js, while reading line by line file


I'm reading a file line by line in node with this code:

const readInterface = readline.createInterface({
    input: fs.createReadStream('/path/to/file'),
    output: process.stdout,
    console: false
});
readInterface.on('line', function(line) {
    console.log(line);
    if(i == 1) photoNumber = line;
    if(i == 2) imgFolder = line;
    if(i == 3) timeString = line;
    i++;
});

This is the output I am getting in terminal:

3  
3  
/home/eugen/Pictures/wallpapers  
/home/eugen/Pictures/wallpapers  
[10 20], [14 50], [18 32][10 20], [14 50], [18 32]

Therefore, the content is doubled for some reason. How can I avoid this? Also, I've observed that some commands would result in not doubling some content on the screen. For example, using

rl.question("\nDo you want to reset the saved data? (y/n): ", r => {
    if(r.toLocaleLowerCase() == 'yes' || r.toLocaleLowerCase() == 'y') readData_();
});

in the the 3rd if would result in not doubling the 3rd line: [10 20], [14 50], [18 32]


Solution

  • Its because you are writing to the terminal twice

    output: process.stdout,
    

    and

    console.log(line);
    

    looking at the docs, you also have the wrong option passed, for you intended effect you can use terminal: false not console: false

    https://nodejs.org/api/readline.html#readline_readline_createinterface_options