Welcome to the Linux Foundation Forum!

Lab 4.2 - Stream Some Content

Hi there,

app.js file:

const express = require('express');
const app = express();

const stream = require('./stream')

app.get('/data', (req,res) => {
    res.type('text/html')
    res.send(stream());
})

app.listen(3000);

node validate fails with the following:

response data should be "this<br>is<br>a<br>stream<br>of<br>data<br>"

When I visit localhost:3000/data this is the response:

{"_readableState":{"objectMode":false,"highWaterMark":16384,"buffer":{"head":null,"tail":null,"length":0},"length":0,"pipes":.........

Any idea what is wrong?

TIA

Answers

  • Ok this seems to work:

    app.get('/data', (req, res) => {
        res.type('text/html');  
        const readableStream = stream();
        readableStream.pipe(res);
    });
    
  • function(req, res, next)  {
      res.type('text/html');
      const readable = stream()
      readable.pipe(res, {end: false});
      finished(readable, (err) => {
        if (err) {
          next(err);
          return;
        }
        res.end();
      })
    }
    

    This could be another approach. The key is to invoke the stream() function only in the request handler method.

  • xdxmxc
    xdxmxc Posts: 157

    exactly, in Express you have to set up the stream piping. You can also use require('stream').pipeline(stream(), res, next) - the next function is automatically called (with any error) when the pipe finishes

Categories

Upcoming Training