Home > Software engineering >  Where should I put a require for in this particular case?
Where should I put a require for in this particular case?

Time:01-20

I have and index.js file for my node application which requires this file once, passing in the app object.

Should I require 'http', in the function or outside the function?

// 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;

It works both ways, but which way is preferred, or best practice?

CodePudding user response:

require() behaves like a singleton. This means the module is only run once even if you call require on the same module multiple times.

Therefore, leave it outside your function which could be called more than once, resulting in unknown behavior.

In short, put requires at the top of your file, outside any other function so that they have file scope.

From ringstack

The module loading mechanism in Node.js is caching the modules on the first require call. It means that every time you use require('awesome-module') you will get the same instance of awesome-module, which ensures that the modules are singleton-like and have the same state across your application.

CodePudding user response:

It is generally considered best practice to require modules at the top of the file, before any other code. This makes it clear what dependencies the code has, and also allows the modules to be cached by Node.js after the first time they are required, improving performance. So in this case, it is better to put the require('http') statement outside the function, at the top of the file.

CodePudding user response:

The best practice is to place all imports at the top of the file. This is so that you can see at a glance what dependencies a given file has, and also makes some testing easier -- if you need to mock out a module, it's simpler to do if that module is guaranteed to be loaded before the rest of the file is executed. In a case where you may need to use the same module higher up, you won't need to move the import (and if the order of execution varies, there's no risk of trying to use a module before it's imported).

It's also more consistent and when you're not the only person working on a codebase then consistency becomes very important.

  • Related