Become a member
to unlock all features

Save 40% this week only!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create a Simple CLI Tool in Node.js with CAC

    John LindquistJohn Lindquist

    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.



    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


    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.