Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 863
Stuart Pearman Avatar asked May 23 '26 04:05

Stuart Pearman


1 Answers

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.

like image 63
slebetman Avatar answered May 24 '26 17:05

slebetman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!