Node Global Install Error

53 Views Asked by At

I'm trying to make a Node module that, when installed with -g, will run by a single command from a terminal.

All tutorials show its pretty straightforward, so I don't know what I'm missing. Here's what I've done:

Package.json:

...
"bin": {
  "myapp": "./lib/myapp.js"
},
...

npm publish

npm install -g myapp

I then try to run it globally:

$ myapp

I then get a glob of errors, which honestly looks like it's trying to run a bash script while reading my app, which is a JS file. Here's the output:

$ myapp
.../io.js/v2.0.2/bin/myapp: line 1: $'\r': command not found
.../io.js/v2.0.2/bin/myapp: line 2: /**
.../io.js/v2.0.2/bin/myapp: line 3: package.json: command not found
.../io.js/v2.0.2/bin/myapp: line 4: */
.../io.js/v2.0.2/bin/myapp: line 5: $'\r': command not found
.../io.js/v2.0.2/bin/myapp: line 6: `var _ = require('lodash')
$

See - it looks like its not trying to interpret JS. Here's the header of my JS file it's trying to run:

/**
* Module dependencies
*/

var _ = require('lodash')

Not sure what I'm doing wrong, but I can't find anyone else having this problem online.

2

There are 2 best solutions below

4
On BEST ANSWER

See - it looks like its not trying to interpret JS.

Right, the "binary" should be a shell script. You can still write it in JS, you just have to tell the shell which interpreter to use. E.g. you can add

#!/usr/bin/env node

to the top of the file, which tells the shell to use node to interpret the rest of the script.

0
On

npm adds a symlink to the file you identify so that it appears on your path. So in this instance, it is literally trying to execute the file as it would any script. You need to add a #! line to the file so your shell knows how to execute it.

For example:

#!/usr/bin/env node
/**
* Module dependencies
*/

var _ = require('lodash')

The #! line is especially important on Windows, as npm looks for that and creates the appropriate .bat file wrapper that knows how to run your script within a node environment.