3

Suppose there are 2 files in my nodejs app say index.js,users.js

Sample code for index.js :

var express = require('express');
var app = express(); 
var winston = require('winston');
....
var signup=require('./apis/users.js');
app.use('/apis/signup',signup);

Sample code for users.js

var express = require('express');
var winston = require('winston');
....

Now we are including express and winston twice in our app.so does that hampers my app performance.What if I say need to include winston only once and use that same object everywhere in app.Whats the right way to do this and in which case we should do what.

Vibhas
  • 241
  • 5
  • 20
  • Performance optimisation rule #1: Measure. Performance optimisation rule #2: If you cannot measure it reliably - it is not important for you. – zerkms Sep 05 '16 at 06:43
  • Proper module design is to build for reuse which has each module `require()` in the things it needs so it can more likely be used in other contexts. Modules are cached by node.js so they will only be loaded and run just once no matter how many times they are `require()` ed in . And, any performance difference would only be upon first initialization, not once your app is up and running anyway. Though with module caching there probably is no performance difference. – jfriend00 Sep 05 '16 at 06:44

2 Answers2

0

The require caches the value after the first load. If you try to fetch again it returns the cache object.

Your answer: It does not affect the performance.

Additional :

However you can delete the value from the require cache if you do not want the same object to reappear again after the first load : node.js require() cache - possible to invalidate?

Community
  • 1
  • 1
ajaykumar
  • 646
  • 7
  • 17
0

Node js uses the cached copy for the require module in the following way.

  1. Check Module._cache for the cached module.

  2. Create a new Module instance if cache is empty.

  3. Save it to the cache.

  4. Call module.load() with your the given filename. This will call module.compile() after reading the file contents.

  5. If there was an error loading/parsing the file, delete the bad module from the cache.

  6. return module.exports.

following article will give you better understanding of the how module and require function works. link

Vora Ankit
  • 682
  • 5
  • 8