Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features
Autoplay

    Create a Simple CLI Tool in Node.js with CAC

    John LindquistJohn Lindquist
    nodeNode.js

    Command-line tools can help you with all sorts of tasks. This lesson covers the very basics of setting up a CLI tool in Node.js by creating your project with npm, setting up your bin script, and using CAC to parse a single argument.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 Use NPM to initialize your project. I'll say npm init y. Then in the package.json, I'm going to name my project hi, and create an index.js file. Make sure to start this file with #/usr/bin/env node. Your terminal will launch this using the Node executable.

    00:27 Now, we can simply go to the package.json and set up a bin. Add our bin reference to ./index.js. You're saying, "When I invoke hi, use this script." We'll just console.log out "hi." Then in my terminal, I'm just going to npm link inside the current directly, then clear that out.

    00:55 Now, if I just say H-I for hi, hit enter, you'll see it'll return hi. I can change this to hello, type in hi, hit enter, and you'll see hello. To simplify arguments, commands, options, and that stuff, I'm going to npm install cac.

    01:14 Then I'll require CAC. CAC is require cac. Set up a CLI, which is just CAC being invoked, and then say that my cli.command. Then pass in a string with these angle brackets that say name on it, meaning that this is a required field.

    01:38 Then an action, which takes a function, which will have that name on it. I'm going to have the action console.log "Hi, name. Today is," then just new date, and toDate string. Then we need to tell the CLI to parse, so it configures everything we told it to do.

    02:03 Clear this out, and from here, I can say, "Hi, John." Hit enter, and you'll see, "Hi, John. Today is," that. Then when I'm done, I can npm unlink, and you'll see that "Hi, John," no longer works, because hi is not found on the path.

    02:21 I can simply install it, so npm i -g, the current directory. Now, I have a tool where anywhere, I can just tell myself, "Hi, John," and my terminal will say hi back.

    Discuss

    Discuss