Thursday, 16 March 2017

Proxy server with Express on Node.js is wrapping callback multiple times

Problem

I'm writing a pretty simple proxy server in node. It takes a requests, passes it on, then collects the response, and sends it back the original caller. Main purpose of the proxy is to wrap the response to the original caller with a callback. problem I'm having, is that the response.on('data', function... gets called multiple times for large responses, and the callback gets wrapped each time (only want it to be wrapped once around the entire response)

Code

function respond(response) {
res.statusCode = response.statusCode;
// when the server sends a data

response.on('data', function(chunk) {
  var chunkString = '';
  // wrap chunck in callback
  if (jsonpCallback !== '') {
    chunkString += jsonpCallback;
    chunkString +=  '(';
    chunkString += chunk.toString();
    chunkString += ')';

    res.write(chunkString);

  } else {
    chunkString += chunk.toString('utf8');
    res.write(chunkString);
  }
});

response.on('end', function() {
  res.end();
});
}

What I've Tried

I attempted to solve the issue by adding a counter variable. I then only attached the callback when the counter === 0. However, since I don't know how many times it may get called, I don't know when to wrap the last ) of the callback.



via NickHeidke

No comments:

Post a Comment