I would like to create a small NodeJS service for testing purposes. This simplified example returns a custom phrase upon being called.

const PORT_HTTP = 8080;
const RESPONSE = 'Hello';

const express = require('express');
const http = require('http');
const app = express();

app.get('', (req, res) => {
    res.status(200).send(RESPONSE);
});

const httpServer =  http.createServer(app);

console.log('==== Server stub started ====');
httpServer.listen(PORT_HTTP, () => console.log(`Listening on ${PORT_HTTP}`));

You see, to change the returned value, I need to go inside the file main.js, change the constant and then restart the application. Too many steps, one would say.

Each NodeJS application fortunately has access to command line arguments via process.argv array.

For simple applications with several positional arguments, it is perfectly satisfactory to access the process.argv directly. In my case, I would like to start with one argument. I can call my application for example like this:

$ node ./main.js "Hello from CMD"

The application code can look for example like this:

const PORT_HTTP = 8080;
const DEFAULT_RESPONSE = 'Default hello';

const express = require('express');
const http = require('http');
const app = express();

const args = process.argv.slice(2);
const response = args > 1 ? args[0] : DEFAULT_RESPONSE 1

app.get('', (req, res) => {
    res.status(200).send(response);
});

// ...etc
  1. First two arguments in process.argv are name of the environment (node) and path to the script (~/somewhere/main.js). They are present even if no other arguments are passed.

Things get more complicated when I would like to have multiple arguments, some of which are named, some of which positional, etc. In that case, an argument parser would come in very handy. Why waste time writing a custom parser when there are already implemented ones, such as yargs.

I think Yargs deserve a more detailed look soon.