Reading command line arguments

TypeScript:
Reading command line arguments

How to:

In TypeScript, you use Node.js to read command line arguments. Here’s how:

// Needed to import process from Node.js
import process from 'process';

// Grab command line args from the third position onward
const args = process.argv.slice(2);

console.log('Command line arguments:', args);

Run this script like ts-node yourscript.ts arg1 arg2 and see:

Command line arguments: ['arg1', 'arg2']

Deep Dive

Back in the early command-line days, user interaction was all about text. Linux, UNIX, and Windows used command line args to tell programs what to do.

Now for the alternatives: besides process.argv, in Node.js, you could use libraries like yargs or commander for more features like parsing and validation.

The guts of this in TypeScript are simple: process.argv is an array with all the arguments. Index 0 is the path to Node, index 1 is the script path, so real args start from index 2.

See Also

To explore further, start with these: