简体   繁体   中英

Show file lines with delay in Node.js

I am trying to make a program in node.js that reads a text file line by line and shows each of them with a delay of 2 seconds. The code I am testing is the following.

var fs = require('fs'),
readline = require('readline');

var FileSystem_Lectura=function()
{
  this._rd=null;
}

FileSystem_Lectura.prototype.abrirArchivoCSV=function(nombreArchivo)
{
    this._rd = readline.createInterface
    ({
        input: fs.createReadStream(nombreArchivo),
        output: process.stdout,
        terminal: false
    });
}

FileSystem_Lectura.prototype.leerArchivoCSV=function()
{
    self=this;
    this._rd.on('line',self.mostraLineasDelay);
} 

FileSystem_Lectura.prototype.mostraLineasDelay=function(linea)
{
    setTimeout(self.mostraLinea,20000,linea);
}

FileSystem_Lectura.prototype.mostraLinea=function(linea)
{
    console.log("Linea:"+ linea);
}

var FS =new FileSystem_Lectura();
FS.abrirArchivoCSV(process.argv[2]);
FS.leerArchivoCSV();

The problem is that settimeout shows me all the lines together, it does not apply the delay. Except for the first line. So, how can I make it work properly?

From already thank you very much

Use pause/resume on your stream :

var fs = require('fs'),
readline = require('readline');

var FileSystem_Lectura=function()
{
  this._rd=null;
}

FileSystem_Lectura.prototype.abrirArchivoCSV=function(nombreArchivo)
{
    this._rd = readline.createInterface
    ({
        input: fs.createReadStream(nombreArchivo),
        output: process.stdout,
        terminal: false
    });
}

FileSystem_Lectura.prototype.leerArchivoCSV=function()
{
    self=this;
    this._rd.on('line',self.mostraLineasDelay);
} 

FileSystem_Lectura.prototype.mostraLineasDelay=function(linea)
{
    this._rd.pause();
    setTimeout(self.mostraLinea,2000,linea);
}

FileSystem_Lectura.prototype.mostraLinea=function(linea)
{
    console.log("Linea:"+ linea);
    this._rd.resume();
}

Also, 2 seconds is 2000ms, not 20000.

This sort of thing is way easier these days:

import {createInterface} from 'readline';
import {createReadStream} from 'fs';
import {pipe, delay} from 'iter-ops';

const file = createInterface(createReadStream('./my-file.txt'));

const i = pipe(file, delay(2000)); //=> AsyncIterable<string>

(async function () {
    for await(const line of i) {
        console.log(line); // prints line-by-line, with 2s delays
    }
})();

Libraries readline and fs are now standard. And iter-ops is an extra module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM