如何从节点脚本执行时查看bash命令

时间:2016-04-20 01:31:18

标签: node.js bash

我有一个节点应用程序,我正在使用bitbucket的webhook来触发bash脚本来运行一些命令来部署我的应用程序。它工作,但我无法查看正在运行的任何命令(即进程命令echo'd)。我怎样才能做到这一点?

以下是相关代码:

  var shellPath = path.join(__dirname + '../../deploy/deploy.sh');
  var exec = require('child_process').exec;

  function puts(error, stdout, stderr) {
    console.log('stout: ', stdout)
    console.log('error: ', error)
    console.log('stderr: ', stderr)
  }

  exec(shellPath, puts);

deploy.sh -

echo Preparing to Git Fetch
git reset --hard origin/master
echo Preparing to clean
git clean -f
echo Preparing to pull
git pull
echo preparing to pull
npm i --production
echo preparing to restart pm2
pm2 restart client-www
echo Finished deploy

1 个答案:

答案 0 :(得分:0)

您可以将结果输出到如下文件:

var shellPath = path.join(__dirname + '../../deploy/deploy.sh > ./output.log');
var exec = require('child_process').exec;

function puts(error, stdout, stderr) {
  console.log('stout: ', stdout)
  console.log('error: ', error)
  console.log('stderr: ', stderr)
}

exec(shellPath, puts);

并使用它来观看文件和打印输出always-tail

var Tail = require('always-tail');
var fs = require('fs');
var filename = "./output.log";

if (!fs.existsSync(filename)) fs.writeFileSync(filename, "");

var tail = new Tail(filename, '\n');

tail.on('line', function(data) {
  console.log("got line:", data);
});


tail.on('error', function(data) {
  console.log("error:", data);
});

tail.watch();