'Detecting which npm script command was run

I have an index.js file that can be run using the following scripts:

  "scripts": {
    "lint": "eslint .",
    "serve": "firebase emulators:start --only functions",
    "inspect": "firebase emulators:start --inspect-functions",
    "deploy": "firebase deploy --only functions",
  },

Is there any way that I can detect which command was executed in index.js file, so that I can initialize the method properly?

index.js

// if serve cmd
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://server.firebaseio.com'
});
//if deploy cmd
admin.initializeApp();



Solution 1:[1]

NPM sets several environment variables when running scripts, including npm_lifecycle_event. This is intended to figure out if it's a pre or post script running, but can also be used for your purposes:

if (process.env.npm_lifecycle_event === "serve") {
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://server.firebaseio.com'
  });
} else {
  admin.initializeApp();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1