[英]How do I create a derived http(s) server in Node.js?
I want to derive the Node.js http(s) server, as I need to add some behavior. 我想派生Node.js http(s)服务器,因为我需要添加一些行为。
Eg, I want to have an http server that also has a foobar
function. 例如,我想要一个也具有
foobar
功能的http服务器。 So I want to be able to do something like this: 所以我希望能够做到这样的事情:
var server = http.createServer(function (req, res) { ... }).listen(3000);
server.foobar();
Of course I somehow need to derive from the http
module, but how could I do this? 当然我不知何故需要从
http
模块派生,但我怎么能这样做呢? Apparently there is no Http
constructor I could override ... 显然没有我可以覆盖的
Http
构造函数...
Any ideas or hints? 任何想法或提示?
I haven't tested, but giving in it a though I would say you would only have to: 我没有测试过,但是虽然我会说你只需要:
var http = require('http');
http.Server.prototype.foobar = function () {};
As you can see here the createServer function is nothing but a factory instantiating a new Server object that was exposed two lines before. 正如您在此处所看到的,createServer函数只是一个工厂,实例化之前暴露过两行的新Server对象。
The correct way is to create a subclass of the server. 正确的方法是创建服务器的子类。
var http = require('http')
class MyServer extends http.Server {
foobar () {
// any code
}
}
var server = new MyServer(function (req, res) {
// any code
})
If you are running a version of Node.js that is <1.0 you need to use the old class syntax: 如果您运行的Node.js版本<1.0,则需要使用旧的类语法:
var http = require('http')
function MyServer (handler) {
http.Server.call(this, handler)
}
MyServer.prototype = Object.create(http.Server.prototype)
MyServer.prototype.foobar = function () {
// any code
}
var server = new MyServer(function (req, res) {
// any code
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.