Node.js command line tool opens in notepad instead

2019-07-20 09:15发布

I try to create a simple node.js command line tool to get around this concept. I am following this tutorial. Using npm init, I have created a project named lb-model-discovery. This is the content of the package.json

{
  "name": "lb-model-discovery",
  "version": "1.0.0",
  "description": "loopback model discovery command line tool",
  "main": "index.js",
  "bin" :{
      "lb-discover":"./index.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "seya obey",
  "license": "ISC"
}

And this is the (very simple) content of the index.js at the root of the project:

console.log('hello world');

After that I executed this command from within the folder (as suggested by the above tutorial):

npm install -g

This correctly install my tool as a global node command line module. Going into the global repository of node modules in my system (windows), I can see that this is the file created in the npm folder: lb-discover.cmd. And here is its content:

@"%~dp0\node_modules\lb-model-discovery\index.js"   %*

But now when I run my new tool from the command line prompt:

$ lb-discover

instead of displaying a "Hello world" message in the console, it opens notepad instead and merely display the content of the index.js file.

What am I doing wrong? How can I execute my custom node.js command line?

Any help would be greatly appreciated.

2条回答
祖国的老花朵
2楼-- · 2019-07-20 09:52

Add #!/usr/bin/env node to the first line of lb-model-discovery/index.js. Then install the package again.

This script will be generated

@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe"  "%~dp0\node_modules\lb-model-discovery\index.js" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node  "%~dp0\node_modules\lb-model-discovery\index.js" %*
)

instead of

@"%~dp0\node_modules\lb-model-discovery\index.js"   %*

Source: https://blog.npmjs.org/post/118810260230/building-a-simple-command-line-tool-with-npm

查看更多
走好不送
3楼-- · 2019-07-20 09:53

I was able to fix this issue by modifying the content of the lb-discover.cmd from this :

@"%~dp0\node_modules\lb-model-discovery\index.js"   %*

to this:

@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe"  "%~dp0\node_modules\lb-model-discovery\index.js" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node  "%~dp0\node_modules\lb-model-discovery\index.js" %*
)

My question is why executing npm install -g in the first place, generated the wrong script?

查看更多
登录 后发表回答