How CLIs in Node.js actually work

A CLI is just a process

A process is a series or set of activities that interact to produce a result; it may occur once-only or be recurrent or periodic. — Wikipedia

If you know how to run Node.JS scripts you’re halfway there

node my-cli.js
  • Accepting arguments.
  • Having an alias.

The I/O of a process (accepting arguments)

  • An arguments vector, which represents a set of strings provided by the user (aka argv).
  • An arguments count, which represents the number of arguments provided by the user (aka argc). In Node.JS it will actually be embedded into argv using the length property.
  • Environment variables, which describe the environment of the process caller. These by default will be set to the system’s variables, but may as well get extended or overridden with each execution.
  • process.argv — Arguments vector. This is an array of strings.
  • process.env — Environment variables. This is a simple object which maps environment names to string values.
  • process.stdin — Standard input. This is a readable stream.
  • process.stdout — Standard output. This is a writable stream.
  • process.stderr — Standard error. This is a writable stream as well.
node my-cli.js --foo=1 --bar=2 --baz=3

PATH binaries (having an alias)

/home/{username}/.cargo/bin:/home/{username}/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/{username}/.npm/bin:/home/{username}/n/bin:/home/{username}/.deno/bin
export PATH=/home/{username}/my-cli:$PATH
permission denied: my-cli
chmod +x /home/{username}/my-cli
#!/usr/bin/node
#!/usr/bin/env node

BONUS: Uploading CLIs as NPM packages

$ npm install -g my-cli
$ my-cli --help
hello world!
/home/{username}/.npm/bin
{
"bin": {
"my-cli": "./my-cli.js"
}
}
#!/usr/bin/env node
require('../lib/my-cli.js')
  • Appfairy — A CLI for transpiling Webflow designs to React components.
  • Git Streamer — A CLI for starting video calls and sharing code simultaneously.
  • Tortilla —A CLI for writing step-by-step tutorials using Git.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store