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

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 ran my cli :

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

tell me about the 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!

+5
source share
1 answer

The documentation states that:

During installation, npm will symbolically refer to this file in the / bin prefix for global installations or. / Node_modules / .bin / for local installations.

This means that npm does nothing special for your file and expects it to run 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 application.

Therefore, the reason for starting your application is not npm. This is your OS. Thus, your script must be executable (as I said, it can even be compiled binary).

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

 #! /usr/bin/env node 

You can simply use:

 #! /whatever/path/to/node 

but depending on the OS or even the distribution, node.js can be installed in different places. Thus, /usr/bin/env is a program that loads the default environment variables, which includes $PATH , which allows the shell to automatically find where node.js. is installed.

+9
source

All Articles