How to do AOP with node.js?

前端 未结 3 1231
独厮守ぢ
独厮守ぢ 2021-02-09 06:01

I have a little problem doing some AOP with node.js: Let\'s say I have an application in a script called server.js, and I want to monitor its functions.

Here is

3条回答
  •  盖世英雄少女心
    2021-02-09 07:05

    A naive attempt would look something like this.

    var before = function(object, functionName, action) {
      var oldFunction = object.functionName;
      var newFunction = function() {
        action();
        oldFunction();
      };
      object.functionName = oldFunction;
    }
    
    var after = function(object, functionName, action) {
      var fn = object.functionName;
      var after = function() {
        fn();
        action();
      };
      object.functionName = oldFunction;
    }
    

    JS is very flexible; you could easily improve on this by storing the after and before actions and adding/removing them as required, but at the very least this should do what you want (albeit not in a very good manner).

提交回复
热议问题