Pergunta

I'm trying to implement something similar to ExpressJS' res.send() which uses a part of the NodeJS Http response object.

A Http server is created like this:

res.send = function(data){
  // Here define how res.send behaves
}

var responseHandler = function(req, res){
   // req and res are passed on from the HTTP call below
   // This code is fired every time a now page is accessed on port 3000
}

http.createServer(responseHandler).listen(3000);

I could just add the send() function to res every time a new page is served, but this seems very inefficient; instead I'd like a way to access the res or response object in http and add the function directly.

Another way to put this might be: how can I access node http's response object directly, so that I can do something like:

var res = http.responseObject;
res.send = function(data){
   // do stuff
}

Note that I'm using vanilla NodeJS here, not Express (which does this sorta thing automatically).

Foi útil?

Solução

I think what you're looking for is something like this:

var http = require('http');
http.ServerResponse.prototype.send = function(data) {
  // ...
};


var responseHandler = function(req, res){
  res.send('hello world');
}
http.createServer(responseHandler).listen(3000);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top