Creating a CLI tool with NODEJS

2

I'm learning how to create a Command-Line Interface Applications (CLI) tool

and performed the following steps:

I created a folder and inside it in the terminal rodei

npm init--yes

In this folder, I created the package.json in this folder. I created a bin folder and inside it an index.js file

After that I have arranged package.json so that it makes index.js as an executable with the command forecast

{
  "name": "tableless-cli",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bin": {
    "forecast": "./bin/index.js"
  }
}

I put this code in index.js

#! /usr/bin/env node
  var https = require('https')
  var arguments = process.argv.splice(2, process.argv.length -1).join(' ')
  console.log(arguments);

In the terminal I ran:

npm link
forecast

to turn into executable and forecast was what I defined in package.json

I opened the cmd folder in the place where it has the package.json and rode error and test test. says forecast is an invalid command, where am I wrong?

    
asked by anonymous 17.05.2018 / 22:15

1 answer

2

You have 2 things in your code that might be the problem.

First her syntax shebang seems to me wrong (not sure):

#! /usr/bin/env node

Probably should be no space after #! (shebang):

#!/usr/bin/env node

The second is that it seems that you are using Windows, I can not tell if this is the same process or if it is automated or not, but it is almost certain that the "compiler" will generate a .cmd (or .bat )

Note that to install I think the command is wrong:

npm init--yes

Should be:

npm init --yes

Or maybe you do not even need --yes :

npm init
    
17.05.2018 / 22:30