添加新方法到 node.js http.ServerResponse.prototype 不起作用

Addition of new methods to node.js http.ServerResponse.prototype not working

作为我学习 Node 内部结构的一部分,我正在尝试向 Node 响应原型添加一些基本功能,而不需要一些外部库。这应该不是一项艰巨的任务,但是,响应永远不会传递给新函数,也永远无法通过 this 语句检索。这是将模板呈现函数绑定到服务器响应的示例。

const http = require('http');

const newMethods = Object.create(http.ServerResponse.prototype);

newMethods.render = async (view, data) => {
    const renderResult = await aTemplateLibray(view, data);
    this.writeHead(200, {'Content-Type': 'text/html'});
    this.end(renderResult);
}
// Other methods here...

// Then
Object.assign(http.ServerResponse.prototype, newMethods);

module.exports = http;

一旦我使用这个http服务器,我就可以使用新的渲染函数,但是响应没有传递给它,所以会抛出一条错误消息,像this.writeHead这样的东西不会函数.

我也试过 Object.defineProperty 方法。

Object.defineProperty(http.ServerResponse.prototype, 'render', 
    {writable: true,
     enumerable: true,
     get: return this.socket.parser.incoming
    });

我发现一些旧的库用旧的 __defineGetter__ 方法返回那个套接字,我用新的形式测试它,但它也不起作用。

主要问题是您使用箭头函数表达式 (=>),这对 this 指向函数内部的内容有特殊影响(更多关于 here).

在你的情况下,你想使用 async function(...):

newMethods.render = async function(view, data) {
    const renderResult = await aTemplateLibray(view, data);
    this.writeHead(200, {'Content-Type': 'text/html'});
    this.end(renderResult);
}