argv and env

process.argv slice

The argv array always holds at least two entries: the Node path and the script path. User words start at index two, so slice there to isolate them.

const words: string[] = process.argv.slice(2); console.log(words.join(", "));

node main.js hello brave world

hello, brave, world

Parse simply

Small tools need only positional words, not a parser library. Read by position, convert numbers with Number, and fall back when conversion fails.

const words: string[] = process.argv.slice(2); const name: string = words[0] ?? "Ada"; const count: number = Number(words[1] ?? 1); if (Number.isNaN(count)) { console.log("Count must be numeric"); }

process.env

Environment values carry settings that change between machines, such as ports and modes. They arrive as strings or undefined, never as numbers.

const mode: string = process.env.MODE ?? "dev"; console.log("Mode:" + mode);

MODE=prod node main.js

Mode:prod

Defaults for missing

Always plan for missing input, because users forget flags and servers forget settings. Nullish coalescing keeps one clear default in one place.

const portText: string = process.env.PORT ?? "3000"; const port: number = Number(portText); const safePort: number = Number.isNaN(port) ? 3000 : port; console.log(safePort);

Text default first, numeric conversion second, sanity check third. That order turns absent or broken settings into a safe local port.

Next: Files with fs

Article author: Arthur Isaev