node.jsnpm

npm bin return me "/usr/local/bin/X: 1: /usr/local/bin/X: Syntax error: "(" unexpected" when calling it


So i'm just trying to create an npm bin who create a file in the current directory.

// ./index.js
const program = require('commander');
const fs = require('fs');
const path = require('path');

program
  .command('c <name> <content>')
  .action((name, content) => {
    fs.writeFile(path.resolve(process.cwd(), name), content, err => err ? console.error(err) : console.log('Success'));
  });

program.parse(process.argv);

This is not because of fs, even if i replace the writeFile by a console.log i still have to same error.

Here's my package.json :

{
  "name": "test-crayzzit",
  "dependencies": {
    "commander": "^2.19.0"
  },
  "bin": {
    "testcc": "./index.js"
  },
  "version": "1.0.3"
}

Everything's work well if i do something like node index.js test.txt hello

But if i install the package with npm : sudo npm i -g test-crayzzit

And do testcc c test.txt hello

It return me an error : /usr/local/bin/testcc: 1: /usr/local/bin/testcc: Syntax error: "(" unexpected

You can try by your self with the package : https://www.npmjs.com/package/test-crayzzit


Solution

  • Looks like you're missing the shebang. The first line of index.js should read as follows:

    #!/usr/bin/env node
    

    Moreover, the file should have LFline endings to be read properly on MacOS, Linux and Windows if you care about using the package on different platforms.

    EDIT: I have tested your package (same error for me on Linux). Adding the shebang as described above works for me.

    See also: Appropriate hashbang for Node.js scripts