Eddy
Eddy

Reputation: 3713

How to run a process before anything else in a Node.js app?

I want to decrypt several config items based on environment variables before anything else starts running in a Node.js app.

I'm starting my app using the standard node ./app.js. Then I call a simple method from the top of my app.js file:

function setConfig() {
    var pass = process.env.pass;
    var conf = Encrypt.decrypt(encryptedConfig, pass);
    var configObj = JSON.parse(conf);
    // do stuff with the configObj
}

This works fine, but since everything is async other processes, which need the config variables, are already running and throwing errors.

What I want is to run my setConfig() before anything else. Is this doable?

Upvotes: 1

Views: 1600

Answers (2)

jakub.g
jakub.g

Reputation: 41398

Apart from accepted answer, what might be useful in some situations (where you can't/don't want to modify the executed file) is NODE_OPTIONS environmental variable + --require (-r) param of node executable

NODE_OPTIONS='--require "./first.js"' node second.js

That way, first.js executes before second.js.

Docs:

Upvotes: 2

Estus Flask
Estus Flask

Reputation: 222855

If a routine is synchronous, it can be executed before routines that depend on it. Executing it before anything else at the top of main module guarantees that there will be no race conditions:

setConfig();
require('module-that-depends-on-config');

If a routine is asynchronous, it should be treated as such in order to avoid race conditions. It's preferable for all asynchronous routines to return promises, so they could be chained with async function in main module:

(async () => {
  await setConfigAsync();
  require('module-that-depends-on-config');
  ...
})().catch(console.error);

Upvotes: 1

Related Questions