How to Create a CLI Tool in Node.js: Simple Guide
To create a CLI tool in
Node.js, write a JavaScript file with a #!/usr/bin/env node shebang, use process.argv to read command-line arguments, and set the file as executable. You can also use libraries like commander for easier argument parsing and then run your tool from the terminal.Syntax
Here is the basic syntax pattern for a Node.js CLI tool:
#!/usr/bin/env node: This line tells the system to use Node.js to run the script.process.argv: An array that holds command-line arguments passed to the script.chmod +x filename.js: Makes the script executable on Unix-like systems.#!/usr/bin/env nodemust be the very first line in the file.
javascript
#!/usr/bin/env node // Access command-line arguments const args = process.argv.slice(2); console.log('Arguments:', args);
Example
This example shows a simple CLI tool that greets the user by name passed as an argument.
javascript
#!/usr/bin/env node const args = process.argv.slice(2); if (args.length === 0) { console.log('Please provide your name.'); process.exit(1); } const name = args[0]; console.log(`Hello, ${name}! Welcome to your CLI tool.`);
Output
Please provide your name.
# When run with argument:
Hello, Alice! Welcome to your CLI tool.
Common Pitfalls
Common mistakes when creating CLI tools in Node.js include:
- Forgetting the shebang line
#!/usr/bin/env node, so the system doesn't know to use Node.js. - Not making the script executable with
chmod +x, causing permission errors. - Not slicing
process.argvto skip the first two default arguments (node path and script path). - Ignoring error handling for missing or invalid arguments.
javascript
/* Wrong way: Missing shebang and not slicing args */ console.log(process.argv); /* Right way: */ #!/usr/bin/env node const args = process.argv.slice(2); console.log(args);
Quick Reference
Summary tips for creating Node.js CLI tools:
- Always start your script with
#!/usr/bin/env node. - Use
process.argv.slice(2)to get user arguments. - Make your script executable with
chmod +xon Unix systems. - Consider using libraries like
commanderoryargsfor complex argument parsing. - Test your CLI tool by running it directly in the terminal.
Key Takeaways
Start your CLI script with the shebang line #!/usr/bin/env node to run with Node.js.
Use process.argv.slice(2) to access command-line arguments passed by the user.
Make your script executable with chmod +x to run it directly from the terminal.
Handle missing or invalid arguments gracefully to improve user experience.
Use libraries like commander for easier and more powerful CLI argument parsing.