Reputation: 1901
I'm using Node.js to run background jobs (no frontend). I think the best way for me to run the workers is to have one file for each kind of job (like that I can easily run one worker per server).
main.js
require('scribe-js')(); // github.com/bluejamesbond/Scribe.js
process.console = console;
...
worker_*.js
require('./lib/main');
console.tag('testing').log('this is a test');
The console
variable isn't passed to worker_*.js. I to set it in main.js
because if the value of the variable ever changes I want to be able to change it only once (in main.js) and not in each worker_*.js file. Any idea?
I think this is not a duplicate: I know there's plenty of "how do I include a JS file in another JS file in Node.js" and the answer is usually "use var s = require('yourfile');
". I think this question is a bit different.
Upvotes: 0
Views: 822
Reputation: 707446
To share a variable between node modules, you can:
The preferred method is to explicitly share a variable via an exported method and then let the module store its own copy of the variable. See here for info about globals.
In your case, it might make a lot of sense to support a common constructor for each worker and pass the worker an object that you can put properties on to share the same variables to each worker.
So, you'd so something like this:
worker_1.js
var savedArgs;
module.exports = function(args) {
savedArgs = args;
}
And, then when worker_1.js was loaded, you'd do this:
var args = {console: process.console};
require('./worker_1.js')(args);
The design of modules is to be as self-contained as possible (e.g. not rely on global state) to encourage modularity and reusability. They should require()
in what they need and any app configuration or singletons that they need in order to do their job that are created by other modules should be given to them in their constructor or via some other exported method.
Upvotes: 2