Building CLI Tools
Create your own command-line tools! Learn to build scripts that run in the terminal using Node.js.
Create your own command-line tools! Learn to build scripts that run in the terminal using Node.js. This hands-on tutorial focuses on practical implementation of building cli tools concepts.
Building CLI Tools
You've used CLI (Command Line Interface) tools like git, npm, and node. Now, let's build our own!
A CLI tool is just a Node.js script that you run from the terminal to perform tasks (like creating files, calculating math, or fetching data).
1. The Shebang Line (#!) π₯
To make a script executable like a real program (instead of typing node script.js), we add a special line at the top.
This tells the operating system: "Use Node.js to run this file."
2. Reading Arguments (process.argv) π₯
When you run node app.js hello world, how does your code know you typed "hello" and "world"?
It uses process.argv (Argument Vector). It's an array containing:
- Path to Node.js executable.
- Path to your script file.
- Your arguments (starting from index 2).
3. Interactive Input (readline) π¬
Sometimes you want to ask the user a question.
4. Practical Example: File Creator π οΈ
Let's build a tool that creates a file with some text.
Usage: node create.js <filename> <text>
5. Making it Global π
To run your tool from any folder (just by typing mytool), you need to:
- Add
"bin"to yourpackage.json. - Run
npm link.
// package.json
{
"name": "my-cool-cli",
"bin": {
"mytool": "./index.js"
}
}
Now, typing mytool in the terminal runs your script!
AI Mentor
Confused about "Node.js CLI tools, process.argv, readline, and creating global commands"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 4What does the shebang line (#!/usr/bin/env node) do?
Key Takeaways
β
process.argv reads command-line inputs.
β
process.exit(1) quits with an error.
β
readline takes interactive user input.
β
bin in package.json creates global commands.
What's Next?
We've mastered the terminal. Now let's conquer the web! Next up: HTTP Server Basics.
Keep coding! π