バックグラウンド
場合によっては、ノード上でいくつかのシェル スクリプトを実行する必要があります。スクリプトを読んだ後、おそらくいくつかの方法があります。
- 公式提供API:exec
- 公式提供API:spawn
- サードパーティライブラリ:shelljs
今日は一つずつ試してみましょう
公式提供API:exec
公式ドキュメント
コマンドを実行します:cat *.js bad_file | wc -l
const {
exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${
error}`);
return;
}
console.log(`stdout: ${
stdout}`);
console.log(`stderr: ${
stderr}`);
});
この書き方では、外部入力を受け付けないコマンドを直接実行する場合に注意する必要があります。
コマンドの実行結果はノード コード コンソールを介して出力されます。それ以外の場合は印刷効果がありません。
公式提供API:spawn
次のコマンドを実行します。ls -lh /usr
const {
spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${
data}`);
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${
data}`);
});
ls.on('close', (code) => {
console.log(`子进程退出码:${
code}`);
});
外部コマンドの需要があればこの書き方は避けられますが、書き方が面倒になるのがデメリットです。
サードパーティライブラリ:shelljs
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}