How to abort a chunked connection

Posted on
  • Hello!

    I connect to some API that continuously sends events via a chunked transfer ("Transfer-Encoding": "chunked"). My goal is to terminate the request after receiving a specific event.

    require("http").get("­", function(res) {
        res.on('data', function(data) {
            if (data == "someEvent") {
                // terminate the request
        res.on('close', function() { print("closed"); });

    How can I achieve it? I know that get returns a httpCRq object, but it doesn't have abort() or destroy() methods. If I keep the connection open, it consumes a lot of memory, so I need to close it.

  • Mon 2021.04.05

    Although I haven't tried as your example implies, has an attempt to use this function been tried?

    See: req.end()­_request

  • @Robin yes, I've tried calling end(), but I'm getting an error:
    Uncaught Error: This socket is closed.

  • A little trickier than I first thought. In all articles I've been able to find so far, the same socket is used for efficiency, and would explain the 'Closed' error after each chunk that was seen. It appears that it needs to be understood what the server API requirements are for your specific "https ://" domain to terminate as so desired. Would it be possible to supply that web service link for others to tackle perhaps?

    'In those circumstances a Connection: close header can be added to inform the receiving party that the persistent connection should not be used again.'­es/articles/javame/chunking.html

    'As for disabling chunked encoding, to do that, you must provide the content length via HttpServletResponse.setContentLength(lon­g), before you access the HttpServletResponse.getOutputStream() and HttpServletResponse.getWriter().'­s/msg03053.html­1365/chunked-transfer-encoding-terminato­r-sequence-and-tcp-recv

  • @Robin thanks for your response. Unfortunately I have no control over the API and like I said it keeps sending chunked data and never stops doing it. Based on your hint I rewrote my code using tls and plain HTTP like so:

    var socket = require('tls').connect(opts, function() {
      socket.write('GET /somemethod  HTTP/1.1\r\n' +
                 'host:\r\n' +
    socket.on('data', function(chunk) {
      if (chunk== "someEvent") {
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview

How to abort a chunked connection

Posted by Avatar for akot @akot