20

when I run package.json bin command , give me syntax error near unexpected token(' ` .

package.json:

 "bin": {
    "grabfilenames": "./index.js"
 }

npm link:

/usr/local/bin/grabfilenames -> /usr/local/lib/node_modules/grabfilename/index.js                                                                                                                                                                               
/usr/local/lib/node_modules/grabfilename -> /Users/dulin/workspace/grabfilename  

when I run my cli:

grabfilenames -p /Users/dulin/workspace/learn-jquery

give me an error:

/usr/local/bin/grabfilenames: line 1: syntax error near unexpected token `('
/usr/local/bin/grabfilenames: line 1: `const fs = require('fs');'

How to solve it? Thanks!

1 Answer 1

36

The documentation states that:

On install, npm will symlink that file into prefix/bin for global installs, or ./node_modules/.bin/ for local installs.

This means that npm does nothing special to your file and expect it to be executable on unix. Your bin file can be a perl script, a compiled C program, a shell script, a Ruby script or even a node.js javascript app.

Therefore what causes your app to run is not npm. It is your OS. So your script must be executable (as I said, it can even be a compiled binary).

On unix, to automatically execute a script with the correct interpreter you need to have a sh-bang as the first line in the file. For node.js I generally use this line:

#! /usr/bin/env node

You can generally just use:

#! /whatever/path/to/node

but depending on the OS or even distro node.js may be installed at different locations. So /usr/bin/env is a program that loads your default environment variables which includes $PATH that will allow the shell to automatically find where node.js is installed.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't know how this would work on Windows. It should work on bash shell on Windows.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.