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

How to use require inside global and local function

我正在使用节点 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) {
    ...
}