Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用内联require_Node.js_Require - Fatal编程技术网

Node.js 使用内联require

Node.js 使用内联require,node.js,require,Node.js,Require,如果我使用内联require,如下所示: function something(...paths) { return require('path').join(...paths); } something('etc', 'etc'); 发动机在每次呼叫中是否都需要?例如: let i = 10; while (--i) something(i, 'etc'); 谢谢。系统将通过您的循环每次调用require(),但是使用require()加载的模块将被缓存,并且模块加载代码仅在第一

如果我使用内联require,如下所示:

function something(...paths) {
  return require('path').join(...paths);
}

something('etc', 'etc');
发动机在每次呼叫中是否都需要?例如:

let i = 10;
while (--i)
  something(i, 'etc');

谢谢。

系统将通过您的循环每次调用
require()
,但是使用
require()
加载的模块将被缓存,并且模块加载代码仅在第一次加载模块时运行。因此,虽然调用
require('path')
会有一些额外的开销,但只需在缓存中查找该模块名称并返回缓存的模块句柄即可。它不需要在每次调用
require()
时加载、解析和运行模块

也就是说,最好还是养成这样的习惯:

const pathModule = require('path');

function something(...paths) {
  return pathModule.join(...paths);
}
您这样做的另一个缺点是,第一次加载
路径
模块时,系统将使用同步文件I/O来加载它,这在多用户服务器中不是一个好主意。文件I/O只是第一次发生,但仍然不是很好的实践。最好在服务器初始化时消除同步I/O