【发布时间】:2023-01-20 02:29:21
【问题描述】:
我有我的节点应用程序的 index.js 文件,它需要一次这个文件,传入应用程序对象。
我应该在函数内还是函数外要求“http”?
// this file is required once by index.js
// ...put it here
function exported(app) {
const http = require('http'); // ...or put it here
return http.createServer(app).listen(process.env.PORT || 3000, () => {
console.log('DEBUG: express: started');
});
}
module.exports = exported;
它可以双向工作,但首选哪种方式或最佳做法?
【问题讨论】:
-
除非有特殊原因,否则将所有导入 (
require) 放在文件顶部 -
只是好奇文件何时实际运行。整个文件是在我每次需要时运行还是仅在我第一次需要时运行?
require('my_file');。
标签: javascript node.js