运行 index.js 之前的可执行文件

Running an executable before index.js

我已经写了一个需要在index.js之前执行的文件,因为它使用commander来要求用户将信息传递给索引文件。我把它放在一个 bin 目录中,但我不确定如何制作它 运行。我可以 cd 进入目录和 运行 node <file_name> 并将所需的值传递给它,它 运行 很好(当我导出索引并将其导入文件和在最后调用它)但是没有办法用更简单的命令将它添加到 package.json 到 运行 中吗?

可执行文件:

#!/usr/bin/env node

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

program
 .version('0.0.1')
 .option('-k, --key <key>')
 .option('-s, --secret <secret>')
 .option('-i, --id <id>')
 .parse(process.argv);
 
let key = program.key;
let secret = program.secret;
let publicId = program.id;

index(key, secret, publicId);

当 Node.js 脚本应该 运行 作为可执行文件时,它被指定为 package.json bin option:

To use this, supply a bin field in your package.json which is a map of command name to local file name. On install, npm will symlink that file into prefix/bin for global installs, or ./node_modules/.bin/ for local installs.

它可以位于 src 或其他地方:

{
  ...
  "bin" : { "foo" : "src/bin.js" },
  ...
}