0

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

shadowspawn
  • 3,039
  • 22
  • 26
Anatole Lucet
  • 1,603
  • 3
  • 24
  • 43

1 Answers1

1

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

Marcus
  • 1,097
  • 11
  • 21
  • Thanks a lot ! It also work for me, but what did you mean when you say : _the file should have `LF` line endings to be read properly_ ? – Anatole Lucet Mar 29 '19 at 13:15
  • Forget about this one. With earlier versions of Node.js there were issues with executable scripts on MacOS if the file had been published on Windows. So the general advice was to convert the file to `LF` line endings before publishing it. However, since npm@5.4.0 this is no longer an issue as this version added auto-conversion. See also https://stackoverflow.com/questions/30344858/node-script-executable-not-working-on-mac-env-node-r-no-such-file-or-directo – Marcus Mar 29 '19 at 13:20