我目前正在尝试创建一个简单的命令行节点程序,它允许我轻松地为我制作的许多React / Redux应用程序创建样板。我正在使用ShellJS来执行控制台命令(我也尝试过使用Node's child_process。)问题是让cli-spinner与执行终端命令一起工作。这是我的代码:
#! /usr/bin/env node
var shell = require('shelljs');
var userArgs = process.argv.slice(2);
var folderName = userArgs[0];
var Spinner = require('cli-spinner').Spinner;
var depSpin = new Spinner('Installing dependencies.. %s');
depSpin.setSpinnerString(10);
shell.mkdir(folderName);
shell.cd(folderName);
depSpin.start();
// I expect for the spinner to start here (before the execution of the commands.)
shell.exec('npm init -y', {silent: true});
shell.exec('npm install --save babel-core babel-loader babel-preset-es2015 babel-preset-react react-dom react-redux redux webpack', {silent: true});
shell.exec('npm install --save-dev babel-preset-env webpack-dev-server', {silent: true});
depSpin.stop();
// Since ShellJS should run synchronously,
// the spinner should stop right after the last command finishes.
shell.touch('webpack.config.js');
shell.mkdir(['build', 'frontend']);
shell.cd('frontend');
shell.mkdir(['components', 'containers', 'reducers', 'store']);
shell.touch('app.js');
但是在运行程序时,它只是在安装依赖项时挂起而不显示任何内容。它与spinner代码甚至不存在时的情况相同。我也尝试删除depSpin.stop()
,这只会使程序永远挂在微调器上。我觉得这个问题是由使用终端的cli-spinner
和ShellJS
之间的冲突引起的。
答案 0 :(得分:2)
我可以使用child_process
的{{1}}来完成此效果。我必须创建一个spawn
并运行与child_process.spawn
连接的所有命令。这将控制台输出释放为&&
输出。然后,当子进程退出以停止微调器时,我做了一个事件处理程序。
cli-spinner
答案 1 :(得分:1)
基于Owens的回答,我自己制作了一个帮助程序方法,可使用与常规shelljs命令内联的Spinner内联命令来运行长命令;
const Spinner = require('cli-spinner').Spinner;
const spinner = new Spinner('installing.. %s');
spinner.setSpinnerString('|/-\\');
var spawn = require('child_process').spawn;
const longCommand = (command, onSuccess) => {
return new Promise((resolve, reject) => {
var process = spawn(command, { shell: true });
spinner.start();
process.on('exit', () => {
spinner.stop();
onSuccess();
resolve();
})
})
}
const npmInstall = async () => {
await longCommand("npm install", () => console.log(`NPM modules installed! `))
// Other stuff
shell.mkdir('new')
}
npmInstall()