{
  "name": "my-hello-world-cli",
  "version": "1.0.0",
  "description": "Hello CLI",
  "main": "server.js",
  "bin": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "man" : "./man/doc.1"
}

Execution

#!/usr/bin/env node

question

What will be an output of running server.js?

// server.js
console.log(process.argv)
node server.js hello world

Try to run bash directly with Windows Subsystem for Linux (for Windows 10)

const { spawn } = require('child_process');
const bat = spawn('cmd.exe', ['/c', '"my script.cmd"']);

How to run Node program in Windows?

%USERPROFILE%/AppData/Roaming/npm

When running npm install -g . in Windows, .cmd extension file is generated along by npm to enable .js file execution with Node

oclif run.cmd example

@echo off

node "%~dp0\run" %*

Make the Hello World CLI in Node

mkdir my-hello-world-cli
cd my-hello-world-cli
npm init
# answer npm questions and check package.json content
echo "console.log('Hello CLI')" > server.js
# check if environment works
npm start
# use bin package.json property to point to server.js
# don't forget to add the shebang 
# #!/usr/bin/env node
# in the top of the server.js file
# install cli globally
npm install --global .
# when execute the CLI in the terminal
my-hello-world-cli
# the result should be in the console
# Hello CLI

Read package.json fields - name, version, and description

"name": "my-hello-world-cli",
"version": "1.0.0",
"description": "My First Node.js CLI",

Show help message when user doesn't provide any flags

my-hello-world-cli

Package description
Package version

Usage: 
--help    Help documentation
--version Installed package version

Show version message when user provides --version argument

my-hello-world-cli --version

my-hello-world-cli 1.0.0

spoiler alert

Hello World CLI in Node

JavaScript that scales.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

Any browser. Any host. Any OS. Open source.

ts

Anders Hejlsberg, 2012 @ Microsoft

Tools

Migrate Hello World CLI to TypeScript

# install typescript globally
# or use npx instead
npm install --global typescript
# initialize typescript compiler project configuration file
tsc --init
# rename js file to ts
mv server.js server.ts
# @types/node 
npm install --save-dev @types/node
# compile project to typescript
tsc
# install cli globally
npm install --global .
# try if cli works
my-hello-world-cli

Troubleshooting

Cannot redeclare block-scoped variable 'name'.ts(2451)

By default, TypeScript uses the DOM typings for the global execution environment and the name property exists on the global window scope.

There are two easy ways to avoid this problem:

Change require() to import ... from ....

To import from json module add the resolveJsonModuleTypeScript compiler option.

{
  "compilerOptions": {
    "lib": [
      "es2015"
    ]
  }
}

spoiler alert

Hello World CLI in TypeScript