Khaled Garbaya

Engineering Leader, Software Developer & Educator

How to create a node js command line tool with yargs middleware

macro-1452986 1920

Using Express.js a lot, I was always a big fan of the middleware approach when handling routes.

When I started building cli tools I noticed that there is a lot of similarity between a server-side program and a command line tool. 

Think of the command that a user types as the route or url. For example  cli-tool project new in a server environment will be the following url example.com/project/new.

A Request object in the cli world can be the stdin and the Response as the stdout.

A while ago I introduced the middleware concept to yargs, the main framework I was using to build clis.

You can check the pull request if you want to checkout the code.

Update: I created an egghead.io lesson about using yargs middleware, feel free to check it out

What is a middleware?

A middleware is a function that has access to the incoming data in our case will be the argv. It is usually executed before a yargs command.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the argv.
  • End the request-response cycle.
                        --------------         --------------        ---------
stdin ----> argv ----> | Middleware 1 | ----> | Middleware 2 | ---> | Command |
                        --------------         --------------        ---------

What is yargs?

yargs-logo

Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.

It's an amazing library that remove all the pain of parsing the command line args also it provides more features like:

  • commands and (grouped) options.
  • A dynamically generated help menu based on your arguments.
  • bash-completion shortcuts for commands and options.

and more...

A simple Node.js command line tool with yargs

bash-161382 1280

Let's create a simple command line program that authenticate the user saves the state to a file called .credentials to be used in the next commands.

1const argv = require('yargs') 2const fs = require ('fs') 3 4argv 5 .usage('Usage: $0 <command> [options]') 6 .command('login', 'Authenticate user', (yargs) => { 7 // login command options 8 return yargs.option('username') 9 .option('password') 10 }, 11 ({username, password}) => { 12 // super secure login, don't try this at home 13 if (username === 'admin' && password === 'password') { 14 console.log('Successfully loggedin') 15 fs.writeFileSync('~/.credentials', JSON.stringify({isLoggedIn: true, token:'very-very-very-secret'})) 16 } else { 17 console.log('Please provide a valid username and password') 18 } 19 } 20 ) 21 .command('secret', 'Authenticate user', (yargs) => { 22 return yargs.option('token') 23 }, 24 ({token}) => { 25 if( !token ) { 26 const data = JSON.parse(fs.readFile('~/.credentials')) 27 token = data.token 28 } 29 if (token === 'very-very-very-secret') { 30 console.log('the secret word is `Eierschalensollbruchstellenverursacher`') // <-- that's a real german word btw. 31 } 32 } 33 ) 34 .command('change-secret', 'Authenticate user', (yargs) => { 35 return yargs.option('token') 36 }, 37 ({token, secret}) => { 38 if( !token ) { 39 const data = JSON.parse(fs.readFile('~/.credentials')) 40 token = data.token 41 } 42 if (token === 'very-very-very-secret') { 43 console.log(`the new secret word is ${secret}`) 44 } 45 } 46 ) 47 .argv; 48

The very first problem in the code is that you have a lot of duplicate code whenever you want to check if the user authenticated.

One more problem can popup is when more then one person is working on this. Adding another "secret" command feature will require someone to care about authentication, which is not ideal. What about an authentication function that gets called before every command and attach the token to your args.

Adding yargs middleware

building-674828 1280

1const argv = require('yargs') 2const fs = require ('fs') 3cosnt normalizeCredentials = (argv) => { 4 if( !argv.token ) { 5 const data = JSON.parse(fs.readFile('~/.credentials')) 6 token = data.token 7 } 8 return {token} // this will be added to the args 9} 10const isAuthenticated = (argv) => { 11 if (token !== 'very-very-very-secret') { 12 throw new Error ('please login using the command mytool login command') 13 } 14 return {} 15} 16argv 17 .usage('Usage: $0 <command> [options]') 18 .command('login', 'Authenticate user', (yargs) => { 19 // login command options 20 return yargs.option('username') 21 .option('password') 22 }, 23 ({username, password}) => { 24 // super secure login, don't try this at home 25 if (username === 'admin' && password === 'password') { 26 console.log('Successfully loggedin') 27 fs.writeFileSync('~/.credentials', JSON.stringify({isLoggedIn: true, token:'very-very-very-secret'})) 28 } else { 29 console.log('Please provide a valid username and password') 30 } 31 } 32 ) 33 .command('secret', 'Authenticate user', (yargs) => { 34 return yargs.option('token') 35 }, 36 (argv) => { 37 console.log('the secret word is `Eierschalensollbruchstellenverursacher`') // <-- that's a real german word btw. 38 } 39 ) 40 .command('change-secret', 'Authenticate user', (yargs) => { 41 return yargs.option('token') 42 }, 43 (argv) => { 44 console.log(`the new secret word is ${secret}`) 45 } 46 ) 47 .middleware(normalizeCredentials, isAuthenticated) 48 .argv; 49

With these two small changes we now have cleaner commands code. This willl help you a lot when maintaining the code especially when you change the authentication code for example. Middlewares can be global, thanks to aorinevo or can be specific to a command which was the part I worked on.

Command-level Middlware

You can also have command-level middlewares. If you want your middlware to be called before a specific command. You can add an array of middlware as the last argument of the .command() function.

Example:

1const normalizeCredentials = (argv) => { 2 if (!argv.username || !argv.password) { 3 const credentials = JSON.parse(fs.readSync('~/.credentials')) 4 return credentials 5 } 6 return {} 7} 8 9var argv = require('yargs') 10 .usage('Usage: $0 <command> [options]') 11 .command('login', 'Authenticate user', (yargs) =>{ 12 return yargs.option('username') 13 .option('password') 14 } ,(argv) => { 15 authenticateUser(argv.username, argv.password) 16 }, 17 [normalizeCredentials] 18 ) 19 .argv; 20

Can I use yargs middleware now?

Update: this is now available in the latest stable version of yargs.

To be able to use yargs you need to have the @next version installed. You can install it using npm i yargs@next.

Next one in your inbox

no spam only content