G
G
gleendo2017-05-12 09:57:42
JavaScript
gleendo, 2017-05-12 09:57:42

Why is there an error in the console (node.js, curl)?

I repeated the code exactly after the lecturer, but I don’t understand why the error occurs.
Please explain what is the problem.

// node app.js
// curl -d "Hello" http://localhost:8080

let http = require(`http`).createServer().listen(8080);

http.on(`request`, (req, res) => {
  res.writeHead(200);

  res.write(`Start...\n`);

  setTimeout(() => {
    res.write(`Finish...`);

    res.end();
  }, 3000);

  req.pipe(res);
});

events.js:160                                                          
      throw er; // Unhandled 'error' event                             
      ^                                                                
                                                                       
Error: write after end                                                 
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:441:15) 
    at IncomingMessage.ondata (_stream_readable.js:555:20)             
    at emitOne (events.js:96:13)                                       
    at IncomingMessage.emit (events.js:188:7)                          
    at IncomingMessage.Readable.read (_stream_readable.js:381:10)      
    at flow (_stream_readable.js:761:34)                               
    at resume_ (_stream_readable.js:743:3)                             
    at _combinedTickCallback (internal/process/next_tick.js:80:11)     
    at process._tickCallback (internal/process/next_tick.js:104:9)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey, 2017-05-13
@evgeniy8705

The bug seems to be that pipe closes the stream by default. In that case, the fix would be to add {end:false} as an option
https://nodejs.org/api/stream.html#stream_readable...
readable.pipe(destination[, options])#
Added in: v0.9.4
destination The destination for writing data
options Pipe options
end End the writer when the reader ends. defaults to true.
Google by the way suggests
stackoverflow.com/questions/39804007/how-to-write-...

E
Eugene, 2017-05-12
@immaculate

I'm new to Node.js, but I'm guessing it's because when your function ends, the response rescloses. When the timeout ends and the handler starts, the socket is already closed.

S
Severus256, 2017-05-12
@severus256

I think the problem is that one of res.write() is called after res.end()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question