Search code examples
javascriptnode.jsnpmnpm-install

CLI tool in an NPM package doesn't execute under Node


I would like to publish a NPM package with a CLI utility in it. In the package.json, I have the following line:

"bin": "index.js"

When I install the package on Windows, a batch file is being generated under Roaming\npm, it's called mypackage.cmd, and the final line goes:

"%dp0%\node_modules\mypackage\index.js" %*

It's not executing the script under Node.js, it's executing the JavaScript file as is - not the desired result. On my dev box, for one, the default association for .js files is Visual Studio Code, not Node. Looking at other modules' generated batch scripts, I see that the final line is different:

"%_prog%" "%dp0%\node_modules\anotherpackage\bin\somescript.js" %*

where _prog is initialized to the Node executable.

I want the bin script to execute explicitly under Node. What is missing in my package (presumably in package.json)?


To reproduce, create a directory. Create the following package.json in it:

{"name": "boo", "version": "1.0.0", "bin": "index.js"}

Create the following index.js in it:

process.exit(0);

Run the following on the command line in that directory:

npm i -g .

Then see the contents of boo.cmd (on Windows):

type %APPDATA%\npm\boo.cmd

And note the lack of _prog on the bottommost line.


Solution

  • Just add #! /usr/bin/env node to the first line of index.js