📎 Webclip
Writing a Command Line Utility using Node
The article shows how to build a small command-line calculator with Node. It starts from a Grunt-init scaffold, adds a shebang line, links the package locally with npm link, and reads user input from process.argv before adding two values and printing the result.
It then extends the tool with package.json configuration for global installation, npm publishing steps, Commander.js for named options, Underscore.js for input checks, and a man page generated from README.md so users can run man calc.
Reading notes#
- Create the project with
grunt-init nodeand review the generated files. - Add
preferGlobaland abinentry inpackage.jsonsocalcmaps tolib/calc.js. - Put
#! /usr/bin/env nodeat the top of the script so Node executes it. - Use
npm linkto install the package locally and test the command. - Read arguments from
process.argv.slice(2)and convert the values withparseInt. - Add the two numbers and print the answer with
console.log. - Before publishing, authenticate with
npm adduser, verify the repository settings, and runnpm publish. - Use
commanderto define named options like--number1and--number2, then read them fromprogram.number1andprogram.number2. - Use
underscoreto detect missing or invalid numeric values and print an error message when needed. - Generate a manual with
marked-man, add it to themanfield inpackage.json, and view it withman calc.
