building a CLI with NodeJS
I recently created a little CLI for my own use to run an ffmpeg command to transform a series of images into a video (I have some notes on that process here: ffmpeg commands for image sequences). Here are a few notes on the process of building a CLI with NodeJS!
very basic setup:
-
Create an empty directory,
cd
into it, andnpm init
orpnpm init
. -
Create
index.js
in your new directory. At the top, add a shebang like this:#! /usr/bin/env node
. This tells our shell which interpreter to use (in this case, NodeJS). -
Add a bin entry to your
package.json
."bin": {
"mycli": "index.js"
},
"type": "module"This sets your cli command as
mycli
andindex.js
as the file which will be run when you use that command. I also added type to use ES module syntax but that part is optional. -
In the same directory, run this command to install your command globally:
npm install -g .
-
Add shebang at the top of
index.js
- this tells our shell which interpreter to use (in this case, NodeJS):#! /usr/bin/env node
Resources
- NodeJS: Accept input from the command line in Node.js
- Codecademy: Getting user input in Node.js
- Let's build a CLI (medium article)
- Building a CLI App with Node.js in 2024 (medium article)
- NodeJS readline documentation
- helpful packages (I haven't used all these)
- Inquirer.js - set of command line interfaces like prompts, checkboxes, confirmation, etc
- commander.js - a bunch of utilities for building a CLI. Not prompts like Inquirer from what I can tell, but setting up commands with options etc.
- Chalk - use pretty colors