命令行应用
Node.js 构建命令行程序
#!/usr/bin/env node
const chalk = require("chalk");
const program = require("commander");
program
.version("0.1.0")
.option("-p, --peppers", "Add peppers")
.option("-P, --pineapple", "Add pineapple")
.option("-b, --bbq-sauce", "Add bbq sauce")
.option(
"-c, --cheese [type]",
"Add the specified type of cheese [marble]",
"marble"
)
.parse(process.argv);
console.log("you ordered a pizza with:");
if (program.peppers) console.log(chalk.blue(" - peppers"));
if (program.pineapple) console.log(" - pineapple");
if (program.bbqSauce) console.log(" - bbq");
console.log(" - %s cheese", program.cheese);
使用 pkg 将命令行程序打包为不依赖与外部 Node.js 的本地程序:
cross-env PKG_CACHE_PATH=D:\SDK\Node\pkg\ pkg -t node8-win -o index.exe index.js
可以在 pkg-fetch 下载本地依赖。
const init = require("./server/init");
require("yargs") // eslint-disable-line no-unused-expressions
.usage("Usage: node $0 <cmd> [args]")
.command({
command: "start",
alias: ["boot", "init"],
desc: "Start Wiki.js process",
handler: argv => {
init.startDetect();
}
})
.command({
command: "stop",
alias: ["quit", "exit"],
desc: "Stop Wiki.js process",
handler: argv => {
init.stop();
}
})
.command({
command: "restart",
alias: ["reload"],
desc: "Restart Wiki.js process",
handler: argv => {
init.restart();
}
})
.command({
command: "configure [port]",
alias: ["config", "conf", "cfg", "setup"],
desc: "Configure Wiki.js using the web-based setup wizard",
builder: yargs => yargs.default("port", 3000),
handler: argv => {
init.configure(argv.port);
}
})
.recommendCommands()
.demandCommand(1, "You must provide one of the accepted commands above.")
.help()
.version()
.epilogue("Read the docs at https://wiki.requarks.io").argv;