有没有一种方法可以在原始函数执行结束时将所有节点函数从一个 npm 模块覆盖到 运行 自定义函数?
Is there a way to override ALL node functions from one npm module to run a custom function at the end of the original function's execution?
示例:我有一个导入的 NPM 模块:
const ex = require('ex');
我在很多不同的地方使用它:
const response1 = await ex.doThis()
const response2 = await ex.doThat()
在每个函数的末尾,我还想记录 ex
中所有方法的响应的特定部分。有没有办法 'override' doThis
和 doThat
(以及所有其他功能)这样我就可以在功能完成后简单地记录一些东西 运行ning 而无需手动每次调用这些函数时都添加一个日志?
我正在考虑在 ex
上制作一个包装器并重新导出它,但我不确定如何修改函数,以便首先它们 运行 本身保持原样,然后运行 我的自定义日志功能来自他们的响应 return。感谢您的帮助!
这将覆盖包的所有方法并在方法执行完成后执行console.log('DONE');
。您将需要做更多的工作来处理承诺,但这应该不是问题。
const path = require('path');
function override(module) {
Object.getOwnPropertyNames(module).forEach((property) => {
if (typeof module[property] === 'function') {
const method = module[property];
module[property] = function () {
// You need to handle promises here
const res = method.apply(module, arguments);
console.log('DONE'); // Replace this with your logging function
return res;
};
}
});
}
override(path);
console.log(path.extname('https://www.google.com'));
示例:我有一个导入的 NPM 模块:
const ex = require('ex');
我在很多不同的地方使用它:
const response1 = await ex.doThis()
const response2 = await ex.doThat()
在每个函数的末尾,我还想记录 ex
中所有方法的响应的特定部分。有没有办法 'override' doThis
和 doThat
(以及所有其他功能)这样我就可以在功能完成后简单地记录一些东西 运行ning 而无需手动每次调用这些函数时都添加一个日志?
我正在考虑在 ex
上制作一个包装器并重新导出它,但我不确定如何修改函数,以便首先它们 运行 本身保持原样,然后运行 我的自定义日志功能来自他们的响应 return。感谢您的帮助!
这将覆盖包的所有方法并在方法执行完成后执行console.log('DONE');
。您将需要做更多的工作来处理承诺,但这应该不是问题。
const path = require('path');
function override(module) {
Object.getOwnPropertyNames(module).forEach((property) => {
if (typeof module[property] === 'function') {
const method = module[property];
module[property] = function () {
// You need to handle promises here
const res = method.apply(module, arguments);
console.log('DONE'); // Replace this with your logging function
return res;
};
}
});
}
override(path);
console.log(path.extname('https://www.google.com'));