简体   繁体   中英

Node Global Install Error

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.

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. Eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM