为node.js中的方法设置before/after钩子

setting a before/after hook for methods in node.js

本文关键字:before after 钩子 设置 方法 node js      更新时间:2024-06-15

如何为node.js中的方法设置before/after"hook"?

在调用某个方法之前,我需要它执行某些操作。我使用的是node.js 10.36和socket.io 1.2。

扩展Function:

这里是对Function.Prototype 的一个小扩展

Function.prototype.before = function (callback) {
    var that = this;
    return (function() {
        callback.apply(this, arguments);
        return (that.apply(this, arguments));
    });
}
Function.prototype.after = function (callback) {
    var that = this;
    return (function() {
        var result = that.apply(this, arguments);
        callback.apply(this, arguments);
        return (result);
    });
}

这两个扩展返回要调用的函数。

这里有一个小例子:

function test(a) {
    console.log('In test function ! a = ', a);
}
test(15); // "In test function ! a =  15"

与之前:

var beforeUsed = test.before(function(a) {
    console.log('Before. Parameter = ', a);
});
beforeUsed(65); // "Before. Parameter =  65"
                // "In test function ! a =  65"

之后:

var afterUsed = beforeUsed.after(function(a) {
    console.log('After. Parameter = ', a);
});
afterUsed(17); // "Before. Parameter =  17"
               // "In test function ! a =  17"
               // "After. Parameter =  17"

您还可以链接:

var both = test.before(function(a) {
    console.log('Before. Parameter = ', a);
}).after(function(a) {
    console.log('After. Parameter = ', a);
});
both(17); // Prints as above