Stuart Pearman
Stuart Pearman

Reputation: 139

npm link causes javascript syntax errors

I'm trying to set up a simple CLI with node. When I run npm link and try my command, I get syntax errors logged to the console for perfectly valid JS.

Code

Command Line

$ holla

Output:

/usr/local/bin/holla: line 1: syntax error near unexpected token `'hello''
/usr/local/bin/holla: line 1: `console.log('hello')'

Here is my package.json:

{
  "name": "npm-cli-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "bin": {
    "holla": "index.js"
  }
}

And here is my index.js:

console.log('hello')

Some extra context

If it helps:

# $PATH variable
/Users/stuartpearman/.rbenv/shims:/Users/stuartpearman/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

# npm global packages
/usr/local/lib/node_modules

Upvotes: 3

Views: 606

Answers (1)

slebetman
slebetman

Reputation: 113896

The bin property expects an executable file. So the holla executable should be a compiled C (or Go or Pascal or anything that creates real machine code) program. If I'm not mistaken as convenience it also accepts shell script and defaults to what you've configured as your user's shell. So the syntax error is not a javascript syntax error but most likely a bash syntax error since console.log('hello') is not valid shell syntax.

Which leads us to the standard solution on unix on how to specify what language your script is in: the sh bang line. Your script should look like this instead:

#! /usr/bin/env node
console.log('hello');

Yes, node.js supports the #! syntax but only if it occurs on the first line of a file.

Upvotes: 3

Related Questions