javascript - How to use require inside global and local function -


im using node js aplication , i've created new js file module , in module export 1 function,in module lets i've additional 2 functions internal use only , should not exposed outside, each function use different require modules following:

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'); ....  } 

my question best practice should put require (for url http etc)

1.inside every function need it?in case internal , external

2.globally in file every function can use?

3.if 2 not ok should put require url should use in 2 functions?better put in both function or in global or doesn't matter

the modules should exposed outside functions calling require each time function called adds overhead. compare:

const url = require('url'); const start = date.now();  (let = 0; < 10000000; i++) {     url.parse('http://stockexchange.com'); }  console.log(date.now() - start); 

to:

const start = date.now();  (let = 0; < 10000000; i++) {     require('url').parse('http://stackexchange.com'); }  console.log(date.now() - start); 

on machine, former takes 95.641 seconds finish executing, while latter takes 125.094 seconds. if export function uses required module, still have access other variables within file when imported. declare modules locally in each file they're needed, , not globally.

edit: mean you'd want instead:

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) {     ... } 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -