NodeJS 需要具有不同行为的脚本
NodeJS require script with different behaviour
我正在编写一个包含文件的无服务器应用程序,为简单起见,我们将其称为 icecream.js
。现在我有多种构建和部署方法。
One 只是获取此文件 icecream.js
,并将其移动到该构建所需的许多其他代码中。让我们调用构建的脚本,其中包含与 icecream.js
、hotfudgesundae.js
(Ice burried by delicious hot fudge) 相同的代码(在某些时候)。我无法控制构成其余构建脚本的热软糖。我也无法控制构建过程。
构建进程号 two 执行一个脚本(让我们称之为 sundaepie.js
),它需要 icecream.js
(We all know there must be some ice cream buried in there somewhere) 的 module.exports
值。它 不能 执行 hotfudgesundae.js
需要的任何代码。
现在有第四个脚本 SearchingSolutions.js
,它需要 hotfudgesundae.js
脚本。
我唯一可以控制的是 sundaepie.js
和 icecream.js
,所以我可以改变圣代派需要 icecream.js 的方式以及 icecream.js 包含的内容。
问题: 我需要以一种方式编写 icecream.js
,它包含的代码 IS 为 hotfudgesundae.js
执行,但不是在 sundaepie.js
需要时执行。 module.exports
可以保持不变。
我尝试了什么: 我不能只检查 module.parent
是否存在,因为虽然 hotfudgesundae.js
不需要脚本(icecream.js
被烘焙到它在构建时), hotfudgesundae.js
本身是 SearchingSolutions.js
.
所必需的
我试图让 module.exports
成为一个只有一个参数的函数,如果给定这个参数,return 一些东西,否则执行 hotfudgebrownie.js
需要的代码。然后我会从 sundaepie.js
中这样称呼它 require('icecream.js')(true)
并从 SearchingSolutions.js
中以常规方式要求 hotfudgesundae.js
(因为我无法控制它),但它不会在需要时执行函数而不传递括号来调用函数。
module.exports = function(isexport) {
if (isexport) {
return "For sundaepie";
} else {
console.log("Executing code in hotfudgesundae.js");
...
}
}
我怎样才能让它工作?如果您有任何问题,请发表评论 ;)
您可以使用 全局变量(是的,那会很痛):
// inside the module
if(global.isCold) /*...*/
// before you require it
global.isCold = true
我正在编写一个包含文件的无服务器应用程序,为简单起见,我们将其称为 icecream.js
。现在我有多种构建和部署方法。
One 只是获取此文件 icecream.js
,并将其移动到该构建所需的许多其他代码中。让我们调用构建的脚本,其中包含与 icecream.js
、hotfudgesundae.js
(Ice burried by delicious hot fudge) 相同的代码(在某些时候)。我无法控制构成其余构建脚本的热软糖。我也无法控制构建过程。
构建进程号 two 执行一个脚本(让我们称之为 sundaepie.js
),它需要 icecream.js
(We all know there must be some ice cream buried in there somewhere) 的 module.exports
值。它 不能 执行 hotfudgesundae.js
需要的任何代码。
现在有第四个脚本 SearchingSolutions.js
,它需要 hotfudgesundae.js
脚本。
我唯一可以控制的是 sundaepie.js
和 icecream.js
,所以我可以改变圣代派需要 icecream.js 的方式以及 icecream.js 包含的内容。
问题: 我需要以一种方式编写 icecream.js
,它包含的代码 IS 为 hotfudgesundae.js
执行,但不是在 sundaepie.js
需要时执行。 module.exports
可以保持不变。
我尝试了什么: 我不能只检查 module.parent
是否存在,因为虽然 hotfudgesundae.js
不需要脚本(icecream.js
被烘焙到它在构建时), hotfudgesundae.js
本身是 SearchingSolutions.js
.
所必需的
我试图让 module.exports
成为一个只有一个参数的函数,如果给定这个参数,return 一些东西,否则执行 hotfudgebrownie.js
需要的代码。然后我会从 sundaepie.js
中这样称呼它 require('icecream.js')(true)
并从 SearchingSolutions.js
中以常规方式要求 hotfudgesundae.js
(因为我无法控制它),但它不会在需要时执行函数而不传递括号来调用函数。
module.exports = function(isexport) {
if (isexport) {
return "For sundaepie";
} else {
console.log("Executing code in hotfudgesundae.js");
...
}
}
我怎样才能让它工作?如果您有任何问题,请发表评论 ;)
您可以使用 全局变量(是的,那会很痛):
// inside the module
if(global.isCold) /*...*/
// before you require it
global.isCold = true