0.1.0 • Published 3 years ago
ff-reddit v0.1.0
Create a CLI Command (program)
CLI frameworks
- Keep in mind that there are entire Node frameworks to help with building out a CLI (just like there are server and frontend frameworks).
- Commander - the defacto standard
- oclif
- Caporal
Interpreter
#! /usr/bin/env node- That
hashbangtells the machine where to find theinterpreter, which is Node. - I believe it works b/c
PATHis in theenvand somewhere in the path it'll find Node (since Node's path location can/will be different on different machines depending on how it was installed).
package.json
- Register our new command (CLI) in the
binfolder.- This instructs
npmto do that (install our command in the user'sbinfolder) when a user usesnpmto globally install our command.
- This instructs
- Need to tell Node.js what the
nameof our CLI is so when can actually use it in our terminal. Just have to add this section to our package.json:
{
...
"bin": {
"reddit": "./reddit.mjs"
}
}redditis the name of theCLI."./reddit.mjs"is the path to the entry file for the command's code.- Once installed, this package will have its
bincommand installed into your machine'sbinfolder allowing us to use theredditcommand globally in the terminal.- All global commands exist in your machine's
bindirectory.
- All global commands exist in your machine's
- The
binproperty (in package.json) is used when your package is used as aCLI. - The
mainproperty (in package.json) is used when someone isimportingyour package (usingimportorrequire) into their project's code.- It points to the entry point for your package's code.
Install package globally
- We must install our own package globally on our machine so we can test out the CLI. We could just execute the file with the node runtime, but we want to see the CLI actually work.
npm install -g .- We can simply install with no args (or
.) which tells npm to install the current director. The-gflag means we want to globally install this package vs in a local project'snode_modulesfolder. - Can confirm it's been installed, and its location, with:
which redditRun command
# Will print to the console a random post's Title and Link
reddit --print
# Will open that random post in your default browser
reddit0.1.0
3 years ago