Become a member
to unlock all features

Level Up!

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


    Create a Simple CLI Tool in Node.js with CAC


    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 Pro 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
    orLog In




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.