javascript - 如何在全局和局部函数中使用 require

标签 javascript node.js require

我正在使用 Node JS应用程序,我已经使用模块创建了新的js文件,在这个模块中我只导出一个函数,在这个模块中可以说我有另外两个函数仅供内部使用并且不应该暴露在外,每个函数使用不同的require模块,如下所示:

module.exports = function (app, express) {

    var bodyParser = require('body-parser'),
        url = require('url'),
        http = require('http');

.....
};


function prRequest(req, res) {

    httpProxy = require('http-proxy');
....

}

function postRequest(req, res) {

 url = require('url');
....

}

我的问题是来自最佳实践,我应该将要求放在哪里(对于 url http 等)

1.inside every function that need it?in my case internal and external

2.globally in the file that every function can use?

3.if two is not OK where should I put the require URL which I should use in two functions?better to put in both function or in global or it doesn't matter

最佳答案

模块应该暴露在函数之外,因为每次调用函数时调用 require 都会增加额外的开销。比较:

const url = require('url');
const start = Date.now();

for (let i = 0; i < 10000000; i++) {
    url.parse('http://stockexchange.com');
}

console.log(Date.now() - start);

至:

const start = Date.now();

for (let i = 0; i < 10000000; i++) {
    require('url').parse('http://stackexchange.com');
}

console.log(Date.now() - start);

在我的机器上,前者需要 95.641 秒才能完成执行,而后者需要 125.094 秒。即使导出使用所需模块的函数,导入时它仍然可以访问其文件中的其他变量。因此,我会在每个需要的文件中本地声明模块,而不是全局声明。

编辑:这意味着您需要这样做:

var bodyParser = require('body-parser'),
    url = require('url'),
    http = require('http');

module.exports = function (app, express) {
    ....
};

var httpProxy = require('http-proxy');

function prRequest(req, res) {
    ...
}

关于javascript - 如何在全局和局部函数中使用 require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31354076/

相关文章:

Javascript 库使用 require() 但我没有或没有使用 nodeJS?

javascript - 如何检测html元素是否在浏览器窗口中?

node.js - 为什么一段时间后我不断收到此 Node 语法错误?

node.js - 蒙哥错误: write EPIPE

ruby - 不需要 require(s) 问题吗?

javascript - webpack 和 oclazyload - 为 require() 指定完整的 url

javascript - 检查任何 if 语句中是否使用了 Javascript 变量

javascript - 如何从 $.getJSON 函数返回变量

javascript - ng-show 未正确更新

node.js - 在部署之前还是之后构建 Web 应用程序?