Creating a CLI tool with NODEJS

Asked

Viewed 96 times

2

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

and carried out the following steps:

I created a folder and inside it in the terminal

npm init--yes

with that I generated the package.json in this folder I created a bin folder and inside it an index.js file

after that I arranged package.json so that it becomes index.js as a executable by 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);

at the terminal I circled:

npm link
forecast

to transform into executable and forecast is what I defined in package.json

I opened the cmd went in the folder at the place where you have package.json and rodei forecast test and error. says that forecast is an invalid command, where I am missing?

1 answer

2


Has 2 things strange in its code, which may be the problem.

First your syntax shebang seems wrong to me (I’m not sure):

#! /usr/bin/env node

It should probably be without space after the #! (shebang):

#!/usr/bin/env node

The second is that it seems that you are using Windows, I do not know 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 don’t even need the --yes:

npm init

Browser other questions tagged

You are not signed in. Login or sign up in order to post.