Home > Software engineering >  how to run a script with custom values?
how to run a script with custom values?

Time:12-06

My script prints text to the console every second and stops after 4 seconds. I need to make sure that the interval and stop values ​​can be specified when the file is run. The file should be run with this command: node index.js -i 1000 -t 4000. How can i do this?

app.get("/", (req, res) => {
  function outputText() {
    console.log("Some Text");
  }
  const interval = setInterval(outputText, 1000);
  setTimeout(() => {
    clearInterval(interval);
  }, 4000);

  res.send();
});

app.listen(3000);

CodePudding user response:

You can use the npm package yargs

const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers');

const argv = yargs(hideBin(process.argv)).argv;

console.log('Interval', argv.i);
console.log('Stop', argv.t);

CodePudding user response:

You may use process.argv to read command line arguments passed to the script. For the simple case, as in your example, you don't need any libraries. It is also best practice to check that all expected input values are passed upfront to avoid accidental runtime errors. You may also want to set some defaults.

As an alternative to command line arguments, you may prefer to use environment variables process.env. In this case you don't need to parse key/value, but just access the environment variable by it's name (see how I used it to optionally customize the port on which server is listening).

// Parse command line arguments.
// The first two values are node itself and path to the script
const args = process.argv.slice(2).reduce((acc, cur, i, arr) => {
  if (i % 2) {
    acc[arr[i-1]] = cur;
  }
  return acc;
}, {});

// Validate input
['-i', '-t'].forEach(opt => {
  if (!args[opt]) {
    console.error(`Missing required command line argument '${opt}'`);
    process.exit(1);
  }
});

app.get("/", (req, res) => {
  function outputText() {
    console.log("Some Text");
  }
  const interval = setInterval(outputText, args['-i']);
  setTimeout(() => {
    clearInterval(interval);
  }, args['-t']);

  res.send();
});

app.listen(process.env.PORT ?? 3000); // use 3000 as default, if environment variable is not set
  • Related