Suppose that you wrote code in a file called engineIgnition.js and exported it as a module. The contents of the file are as follows:

module.exports.ignition = function() {
    console.log('Ignition Sequence Start');
}

Now we describe different ways of invoking this code. We will check them out one by one.

nodejs different methods to run code

Method 1: Run from command line terminal:

node -e 'require("./engineIgnition").ignition()'

Method 2: Running the above command in a similar way:

node ./engineIgnition.js

Method 3: Using NPM script. Assuming that you have package.json in your code base, add the following to it:

"scripts": {
   "ignitionScript": "node -e 'require("./engineIgnition").ignition()'"
}

Then run the following from the terminal from the root of the project where package.json is present:

npm run ignitionScript

Method 4: Now let’s suppose we got multiple methods inside the engineIgnition.js:

module.exports = {
  engineIgnition: function () { ... },
  liftOff: function () { ... }
}

Then in order to invoke these multiple methods in a sequence, create a new file, engineIgnitionInitialise.js with the following code:

const engineIgnitionModule = require('engineIgnition');

engineIgnitionModule.engineIgnition();
engineIgnitionModule.liftOff();

Now from the command line run:

node ./engineIgnitionInitialise.js

Or

node -e 'require("./engineIgnitionInitialise")'