Sergino
Sergino

Reputation: 10838

Node define unique variable that I need to use across the modules

Currently I am just passing my fileNamePrefix like that:

let shortid = require('shortid');
let fileNamePrefix = shortid.generate();

module1.run(fileNamePrefix); //generating a file based on `fileNamePrefix` `xxxxx.f1.json`
module2.run(fileNamePrefix); //generating a file based on `fileNamePrefix` `xxxxx.f2.json`
module3.run(fileNamePrefix); //generating a file based on `fileNamePrefix` `xxxxx.f3.js

Which I think in not quite right, I might need to pass more things to my modules later on, so I want to avoid to pass that as function params.

What is the best way to approach that in nodejs?

Will global object like global.fileNamePrefix = shortid.generate(); will do in that case or would you approach that different? I just read that global is not good...

Upvotes: 0

Views: 335

Answers (2)

Mihir Bhende
Mihir Bhende

Reputation: 9045

You can use either singleton approach or approach suggested by @Сергей Тертичный

  1. Singleton :

    //shortid.js
    
    var fileSingleTon = module.exports = {
    
        fileNamePrefix: null,
    
        getFileNamePrefix: function() {
            return fileSingleTon.fileNamePrefix || fileSingleTon.generate()
        },
        generate: function() {
            console.log('generating..');
            return fileSingleTon.fileNamePrefix = 'your_file_prefix';
        }
    }
    
    //module1.js
    
    var fileNamePrefix = require('./shortid').getFileNamePrefix();
    
    //do stuff for module1
    
    //module2/js
    
    var fileNamePrefix = require('./shortid').getFileNamePrefix();
    
    //do stuff for module1
    

    and so on..

Even now you are calling require('./shortid').getFileNamePrefix(); multiple times, generate function is getting called only once.

  1. Node Caching approach :

Consider you have shortid.js as following :

// A: block of code to do some manipulations

// B : module.exports = manipulation result.

So basically in node js "modules" core module which is responsible for giving us module.export functionality executes whatever is here above export(in abode example the part A) only for the first time and caches it even if you have required in in multiple other files. However, it only executes the functions or block of code in every require which is inside export. So you can use this approach where your A block will have login to generate fileNamePrefix and then B just returns it.

Upvotes: 1

Sergaros
Sergaros

Reputation: 831

Just create module like that:

// unicname.js
let shortid = require('shortid');
let fileName = shortid.generate();

module.exports = {fname: fileName};

//module1.js
const {fname} = require('./unicname.js');
....

Since the node.js caching the modules the value will be calculated only one time so you can get same value in all your modules.

Upvotes: 1

Related Questions