MBehtemam
MBehtemam

Reputation: 7919

Rules for Require in Nodejs

Recently im working on new Nodejs project and find some codes like this :

function a(){
   var http = require('http');
   var fs = require('fs');
}

function b(){
   var path = require('path');
   var http = require('http');
}

function c(){
  var fs = require('fs');
 }

so i have a some question about coding like this :

Upvotes: 0

Views: 389

Answers (3)

Salar
Salar

Reputation: 5509

Manning publication has a good book about node, called Node.js in action this is how the node's module requiring rules described it.
enter image description here

Upvotes: 0

vkurchatkin
vkurchatkin

Reputation: 13570

You definitely should avoid these in production. Modules are cached indeed, so it can affect performance only during initial calls to require, but still it can. Also fs, http and and path are built-in modules, so require-ing them doesn't involve reading from disk, only code compilation and execution, but if you use non built-in modules you will also block event loop for the time of reading from disk.

In general, if you use any sync functions, including require, you should use them only during first tick, since no servers are listening yet anyway.

Upvotes: 2

Louis
Louis

Reputation: 151541

Some rules for when to call require:

  • By default, require a module globally once at the start of the file and do not reassign the variable to which the result of require is assigned.

  • If requiring a module has been proved to impact performance significantly (maybe it has initialization routines that take a long time to run) and it is not used throughout the file, then require it locally, inside the function that needs it.

  • If the module's name must be computed in a function, then load it locally.

If the code you show in your question is all in one file and is meant to be used in production, I'd ask the coder who produced it what warrants using require in that way, and if a good, substantial reason, supported by evidence cannot be formulated, I'd tell this coder to move the require calls to the start of the file.

Upvotes: 3

Related Questions