Summary - Process
- Node.js course
- Intermediate
- Lesson 64/116
- 5 min
Combine argv, env and child_process to write a CLI tool.
Summary - Process
In this group you learned the core tools of process management: CLI arguments with process.argv, environment variables with process.env, exit codes with process.exit, streams with process.stdin/stdout and child processes with child_process.exec.
You can combine these five tools to build a real CLI tool. For example, you can read a name from an argument, take a setting from an environment variable, set the exit code and write to stdout. This is the basic pattern of command-line tools in Node.js. Now you will combine all pieces in one piece of code.
Practice Combine the CLI tool
Read the name from process.argv[2]; if missing, use "Node". Set process.exitCode to 0. Write the name with process.stdout.write (no newline).
Starter code
// Read the first argument, use "Node" if missing
// Set exitCode to 0
// Write the name to stdout
// write hereSample solution
const name = process.argv[2] || "Node";
process.exitCode = 0;
process.stdout.write(name);Expected output
Node
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each tool to its role
| Term | Meaning |
|---|---|
argv |
CLI arguments |
env |
Environment variables |
exit |
Exit code |
exec |
Child process |
2 What happens if process.argv[2] is not given?
process.argv[2]- It throws an error
- The program crashes
- An empty string is returned
- undefined is returned Correct answer
Explanation: A missing argument is undefined; || gives a default.
3 Complete the default value
const name = process.argv[2] || ____;
const name = process.argv[2] || "Node";
Explanation: || "Node" gives a default on a missing argument.