Search code examples
javascriptnode.jsnode.js-stream

How to make a NodeJS Server that emits a string file line by line with a time interval when connected?


I am trying to implement a simple NodeJS server that reads a file and then emits line by line to the requester with a time interval between emissions. The problem is the timeout which is not working as intended.

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

var server = http.createServer(function (req, res) {
  console.log('request was made: '+req.url);

  res.writeHead(200,{'Content-Type': 'text/plain'});

  var myReadStream = fs.createReadStream(__dirname+"/foo.txt", 'utf8');

  var rl= readline.createInterface({
    input: myReadStream
  });

  rl.on('line', function(input) {

    res.write(input);
    setTimeout(function(){}, 3000);

  });

});


server.listen(3000,'127.0.0.1');

Solution

  • You're almost there you just need to move the res.write(line) into your setTimeout() so the call to res.write(line) happens when the timeout callback is invoked.

    rl.on('line', line => {
      setTimeout(() => {
        res.write(line);
      }, 3000);
    });
    

    Also you should listen for the 'close' event from readline to know when you can call res.end() to end the response stream.

    rl.on('close', () => {
      res.end();
    });