LEARNNode CLI Automation

Checking Node Version

There are many scenarios in which you would need to make sure that the user is running a particular version of Node.js or above while running your CLI. The simplest one might be if you have implemented a feature using a core node module that was not supported by earlier versions of Node.js.

So what would you need to do to implement this? Let's take a look at it.

cli-check-node

I have written a node module that allows you to define a node version for your CLI. It's called cli-check-node. If the user is running a lower Node.js version, it will exit the CLI and present a clean error message.

Go ahead and install it in your project by running the following command in the terminal:

npm install cli-check-node

Now open the file which is the main entry point in your CLI and require the cli-check-node module inside it. Then the only thing you need to do now is set a Node.js version like this:

const checkNode = require('cli-check-node');
checkNode(10)

I have defined a Node.js version of 10. So if anyone who has a lower version runs my CLI, he will see an error message showing to update your Node.js version. It will also exit the CLI.

You can also make sure that your CLI is not exited and the user will still see your error message of updating Node.js. For that, you would need to pass an object as a second parameter to checkNode function.

checkNode(10, {fail: false});

Wrapping Up

This is how easy it is to make sure that your CLI user has the required version of Node.js and your CLI doesn't fail. So go ahead and implement this feature in your Node.js-based CLI as a safety check with cli-check-node module.

Posted by Saad (It's a work in progress: Needs copy editing review by Awais.)