You write scripts that receive arguments with process.argv, read environment variables, and return an exit code.
Open this lesson in KodokonYou already use command-line programs: node, npm, git, and so on. Each one accepts arguments, the words typed after its name, which change its behavior. Let's write our own. Node exposes the global object process, which describes the currently running program - you came across it with process.version. Its property process.argv is an array that contains: at index 0, the path to Node; at index 1, the path to your script; and starting at index 2, the arguments actually typed by the user.
console.log(process.argv);
const args = process.argv.slice(2);
console.log("Your arguments:", args);A second source of information: environment variables. These are name/value pairs provided to the program by the system at launch time. They're used for configuration: a secret API key, debug mode, a database address, and so on. You read them in the process.env object. A missing variable is undefined: always plan for a default value, for instance with the ?? operator.
const level = process.env.LOG_LEVEL ?? "info";
console.log("Log level:", level);LOG_LEVEL=debug node config.jsWhen a program finishes, it returns an exit code to the system: a number that sums up how things went. Universal convention: 0 means "success", any other value signals an error - this is what other tools and scripts check to know whether everything worked. process.exit(1) immediately stops the script with code 1. Also use console.error for error messages: it writes to the error output (stderr), a channel separate from normal output. Let's put it all together in a complete script.
const name = process.argv[2];
if (!name) {
console.error("Usage: node greet.js <name>");
process.exit(1);
}
console.log(`Hello, ${name}!`);