Runtime and core tooling · Lesson 4 of 18
process and command-line apps
Read arguments and environment, set exit codes, and clean resources before exit.
process represents the current program. process.argv contains command-line arguments, process.env carries string configuration, and process.cwd() is the working directory. Exit code zero means success; non-zero means failure—the contract between a CLI, shell and CI.
shell arguments + env
Node process
stdout / stderr
exit code
function parseArgs(args) {
const nameAt = args.indexOf("--name")
return { name: nameAt >= 0 ? args[nameAt + 1] : "learner" }
}
const config = parseArgs(["--name", "Mona"])
console.log("Hello " + config.name)
console.log(process.env.APP_MODE || "development")Never print secrets from process.env. Validate configuration at startup and fail with a useful message. Instead of process.exit() during asynchronous work, set process.exitCode and let the event loop finish logs and cleanup.
Quick question
A CLI fails validation. Appropriate exit code?
Exercise
Write getPort(env) returning numeric PORT or 3000, then print two cases.
Expected output: 8080 3000
function getPort(env) {
}
console.log(getPort({ PORT: "8080" }), getPort({}))Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.