首页 > 解决方案 > 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

标签: node.jsnpm

解决方案


看起来你错过了shebang。index.js 的第一行应该如下所示:

#!/usr/bin/env node

LF此外,如果您关心在不同平台上使用该软件包,该文件应该有行尾以便在 MacOS、Linux 和 Windows 上正确读取。

编辑:我已经测试了你的包(在 Linux 上对我来说同样的错误)。如上所述添加shebang对我有用。

另请参阅:适用于 Node.js 脚本的 hashbang


推荐阅读