Pure Programmer
Blue Matrix


Cluster Map

Command Line Arguments

L1

This page is under construction. Please come back later.

When running programs from the command line we have the option of supplying additional information in the form of arguments on the command line. Command line arguments take the form of strings separated by spaces. For example the following command line program invokation has three additional arguments.

$ nodejs Program.js Fred 123 Flintstone

In our programs we can access each of these arguments using the variables process.argv[0], process.argv[1], process.argv[2], etc. The name of the JavaScript interpreter is found in the variable with the 0 subscript. Our program filename will be in the variable with subscript 1. The user supplied arguments are in the variables with subscripts 2, 3, 4, etc.

CmdLineArgs1.js
#!/usr/bin/env node;
const Utils = require('./Utils');

const main = async () => {
	console.log("Number of arguments: " + (process.argv.length - 2));
	console.log("Program Name: " + Utils.filename(process.argv[1]));
	console.log("Arg 1: " + process.argv[2]);
	console.log("Arg 2: " + process.argv[3]);
	console.log("Arg 3: " + process.argv[4]);
	console.log("Arg 4: " + process.argv[5]);
}
main().catch( e => { console.error(e) } );
Output
$ node CmdLineArgs1.js Fred Barney Wilma Betty Number of arguments: 4 Program Name: CmdLineArgs1.js Arg 1: Fred Arg 2: Barney Arg 3: Wilma Arg 4: Betty $ node CmdLineArgs1.js Φρειδερίκος Барнеи ウィルマ 贝蒂 Number of arguments: 4 Program Name: CmdLineArgs1.js Arg 1: Φρειδερίκος Arg 2: Барнеи Arg 3: ウィルマ Arg 4: 贝蒂

If we want to treat a command line argument as a number we first need to convert from the string representation passed on the command line to a numeric type. This is where conversion functions come in handy. The example below illustrates how to convert command line arguments to integers.

CmdLineArgs2.js
#!/usr/bin/env node;
const Utils = require('./Utils');

const main = async () => {
	const a = Utils.stoiWithDefault(process.argv[2], 0);
	const b = Utils.stoiWithDefault(process.argv[3], 0);
	const c = a + b;
	console.log(Utils.format("{0:d} + {1:d} = {2:d}", a, b, c));
}
main().catch( e => { console.error(e) } );
Output
$ node CmdLineArgs2.js 326 805 326 + 805 = 1131

The example below converts the command line arguments to floating point values.

CmdLineArgs3.js
#!/usr/bin/env node;
const Utils = require('./Utils');

const main = async () => {
	const a = Utils.stodWithDefault(process.argv[2], 0);
	const b = Utils.stodWithDefault(process.argv[3], 0);
	const c = a + b;
	console.log(Utils.format("{0:f} + {1:f} = {2:f}", a, b, c));
}
main().catch( e => { console.error(e) } );
Output
$ node CmdLineArgs3.js 3.21 7.01 3.21 + 7.01 = 10.219999999999999

Questions

Projects

More ★'s indicate higher difficulty level.

References