2 * Copyright 2013 IBM Corp.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 module.exports = function(RED) {
19 var spawn = require('child_process').spawn;
20 var exec = require('child_process').exec;
22 function ExecNode(n) {
23 RED.nodes.createNode(this,n);
24 this.cmd = n.command.trim();
25 this.append = n.append.trim() || "";
26 this.useSpawn = n.useSpawn;
29 this.on("input", function(msg) {
30 node.status({fill:"blue",shape:"dot"});
31 if (this.useSpawn === true) {
32 // make the extra args into an array
33 // then prepend with the msg.payload
34 if (typeof(msg.payload !== "string")) { msg.payload = msg.payload.toString(); }
36 if (node.append.length > 0) { arg = node.append.split(","); }
37 if (msg.payload.trim() !== "") { arg.unshift(msg.payload); }
38 node.log(node.cmd+" ["+arg+"]");
39 if (node.cmd.indexOf(" ") == -1) {
40 var ex = spawn(node.cmd,arg);
41 ex.stdout.on('data', function (data) {
42 //console.log('[exec] stdout: ' + data);
43 msg.payload = data.toString();
44 node.send([msg,null,null]);
46 ex.stderr.on('data', function (data) {
47 //console.log('[exec] stderr: ' + data);
48 msg.payload = data.toString();
49 node.send([null,msg,null]);
51 ex.on('close', function (code) {
52 //console.log('[exec] result: ' + code);
55 node.send([null,null,msg]);
57 ex.on('error', function (code) {
61 else { node.error("Spawn command must be just the command - no spaces or extra parameters"); }
64 var cl = node.cmd+" "+msg.payload+" "+node.append;
66 var child = exec(cl, function (error, stdout, stderr) {
68 var msg2 = {payload:stderr};
70 //console.log('[exec] stdout: ' + stdout);
71 //console.log('[exec] stderr: ' + stderr);
73 msg3 = {payload:error};
74 //console.log('[exec] error: ' + error);
77 node.send([msg,msg2,msg3]);
83 RED.nodes.registerType("exec",ExecNode);