几天前,我创建了一个 shell 脚本来根据用户从菜单中选择的内容构建不同的应用程序(React、Vite-React、Vite-Vue、Next.js 和 Django)。
它真的很好,但想尝试用node.js
. 结果目前“正常”工作,但虽然它产生了所需的最终结果,但它有一些限制,我想知道如何排序:
当脚本完成其工作时,用户没有任何反馈。这是因为我同步运行命令。这对用户来说不是很好,他们可能认为脚本刚刚停止。我很想显示一个微调器或简单地将当前进程回显到终端,喜欢
yarn
或npm
做。该脚本目前仅适用于 MacOs/Linux,因为它依赖于
Homebrew
安装几个包 (jq
和pipenv
)。我还没有看到如何使它也“对 Windows 友好”!
例如,这个installDjango()
函数同步运行所有命令:(因此阻塞终端直到完成。我很想知道如何显示所有命令的终端输出,或者至少是一些微调器,让用户知道安装正在进行:
import chalk from "chalk";
import { spawnSync } from "child_process";
import { sync as commandExists } from "command-exists";
import shell from "shelljs";
import { brewInstall, pipenvInstall } from "./utils.js";
const installDjango = (name) => {
if (!commandExists("brew")) {
brewInstall();
}
if (!commandExists("pipenv")) {
pipenvInstall();
}
shell.echo(chalk.cyan(`Installing ${name}. Please hold...`));
shell.mkdir(name);
shell.cd(`./${name}`);
spawnSync("gh", ["repo", "clone", "GBrachetta/boilerplate-django", "."]);
spawnSync("rm", ["-rf", ".git"]);
spawnSync("pipenv", ["install"]);
spawnSync("pipenv", ["install", "--dev"]);
spawnSync("pipenv", [
"run",
"python",
"manage.py",
"rename",
"boilerplate",
name,
]);
spawnSync("git", ["init"]);
spawnSync("git", ["add", "."]);
spawnSync("git", ["commit", "-m", "'Initial commit'"]);
spawnSync("code", ["."]);
};
export default installDjango;
以下是引用的两个函数:
import chalk from "chalk";
import { spawn } from "child_process";
import { Spinner } from "cli-spinner";
import shell from "shelljs";
const spinner = new Spinner("%s");
spinner.setSpinnerString(18);
export const brewInstall = () => {
shell.echo(chalk.cyan("Brew does not exist. Installing..."));
const brewInstall = spawn("/bin/bash", [
"-c",
"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)",
]);
brewInstall.stdout;
};
export const pipenvInstall = () => {
shell.echo(chalk.cyan("Pipenv does not exist. Installing..."));
const pipenvInstall = (command, onSuccess) => {
return new Promise((resolve, reject) => {
const process = spawn(command, { shell: true });
spinner.start();
process.on("exit", () => {
spinner.stop();
});
});
};
const pipenvI = async () => {
await pipenvInstall("brew install pipenv");
};
pipenvI();
};
如果您想查看完整包以了解更多上下文,请参阅repo 的链接。
非常欢迎所有建议和批评(这是我的第一个 node.js 脚本)!