UNPKG

1.85 kBJavaScriptView Raw
1var spawn = require ('child_process').spawn,
2 fs = require ('fs'),
3 task = require ('./base'),
4 util = require ('util');
5
6/**
7 * Run shell script
8 */
9
10var shellTask = module.exports = function (config) {
11 this.init (config);
12};
13
14util.inherits(shellTask, task);
15
16util.extend(shellTask.prototype, {
17 /**
18 * Run shell command
19 *
20 * @param {Object} env - environment, parameters passed as environment to shell
21 * @param {String} commandString - command for shell
22 * @param {Boolean} [strictEnv=false] - don't copy env from process.env
23 * @param {Boolean} [splitStrings=false] - split strings at output
24 * @param {String} [result=output] - what result you need? you can choose between `output`, `exitCode` and `success`
25 * @api public
26 */
27 run: function () {
28 var self = this;
29 var env = {};
30 if (!this.strictEnv) {
31 for (var k in process.env) {
32 env[k] = process.env[k];
33 }
34 }
35 for (k in self.env) {
36 env[k] = self.env[k];
37 }
38
39 var shellOutput = '';
40 var shell = spawn('/bin/sh', ['-c', this.commandString], {
41 env: env, stdio: ['pipe', 'pipe', 2]
42 });
43
44 shell.stdout.on('data', function (data) {
45 shellOutput += data;
46 });
47
48 shell.on('close', function (code) {
49 if (self.result == "exitCode") {
50 self.completed (code);
51 return;
52 }
53 if (code !== 0) {
54 console.log('shell process exited with code ' + code);
55 self.failed (); // this is for both results: success and output
56 return;
57 } else if (self.result == "success") {
58 self.completed(true);
59 return;
60 }
61 if (self.splitStrings) {
62 var dataForHandler = shellOutput.replace("\r", "").split("\n")
63 //dataForHandler.pop();
64 self.completed (dataForHandler);
65 } else {
66 self.completed (shellOutput);
67 };
68 });
69 //child.stdout.on('data', function(data) { process.stdout.write(data); });
70 }
71});
72
73module.exports = shellTask;