Node.js 如何覆盖模块的函数
覆盖 意味着不改变任何对象或模块的原始定义,而是改变其在当前情景(导入或继承的地方)下的行为。为了实现覆盖,我们将覆盖Node.js内置模块 url 的函数。让我们来看一下覆盖模块的步骤:
- 首先, require 我们想要覆盖的模块。
const url = require('url')
- 然后删除我们想要覆盖的模块的功能。在这里,我们将覆盖“链接”模块的format()函数
delete url['format']
- 现在添加一个与同名的函数’format’来为模块的format()函数提供一个新的定义。
url.format = function(params...) {
// statement(s)
}
- 现在重新导出‘url’模块,以使更改生效
module.exports = url
让我们逐步实现完整的工作代码:
步骤1: 创建一个名为“ app.js ”的文件,并使用 npm 初始化项目。
npm init
项目结构将如下所示:
步骤2: 现在让我们来编写“ app.js ”文件。在这个文件中,我们按照上面提到的所有步骤来覆盖一个模块。完成这些步骤后,你将成功 覆盖 了‘url’模块的 format() 函数。在下面的完整工作代码中,你可以找到在覆盖之前和之后 format() 函数的行为。
app.js
// Requiring the in-built url module
// to override
const url = require("url");
// The default behaviour of format()
// function of url
console.log(url.format("http://localhost:3000/"));
// Deleting the format function of url
delete url["format"];
// Adding new function to url with same
// name so that it would override
url.format = function (str) {
return "Sorry!! I don't know how to format the url";
};
// Re-exporting the module for changes
// to take effect
module.exports = url;
// The new behaviour of export() function
// of url module
console.log(url.format("http://localhost:3000/"));
步骤3: 使用以下命令运行你的节点应用程序。
node app.js
输出: