是否有必要多次要求一个模块(在这种情况下为child_process)?

时间:2014-12-29 14:04:26

标签: node.js

在我选择的代码中,app.js包含,在同一范围内:

var childProcess1 = require("child_process");
childProcess1.fork(...)
...
var childProcess2 = require("child_process");
childProcess2.fork(...)

有没有理由要求两次?

PS:有关要求的更多详情:)

3 个答案:

答案 0 :(得分:2)

如果require具有不同的功能,则可能是必要的。像这样:

function foo() {
  var childProcess1 = require("child_process");
  childProcess1.fork(...)
}

function bar() {
  // here you can't use childProcess1, so
  var childProcess2 = require("child_process");
  childProcess2.fork(...)
}

但是将代码更改为以下内容会更好:

var childProcess = require("child_process");

function foo() {
  childProcess.fork(...)
}

function bar() {
  childProcess.fork(...)
}

可能有理由没有像这样的全局变量(但我不想使用内置的child_process模块)

答案 1 :(得分:1)

通常,您只需require()一个模块,因为同一模块的未来require()将返回完全相同的值。由于此特征,重新使用第一个require()的结果可避免调用require()的额外最小开销。

答案 2 :(得分:1)

不,几乎没有必要。事实上,values returned by require are cached,因此第一次调用require("foo")实际上会运行模块,而其他调用只会访问require.cache中存储的原始返回值(特别是require.cache[require.resolve("foo")] )。

如果您的代码篡改了require.cache,那么唯一需要多次调用的情况(或者无论如何都会产生任何影响),这可能是不可能的。