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) {
18 var util = require("util");
19 var events = require("events");
20 var debuglength = RED.settings.debugMaxLength||1000;
21 var useColors = false;
22 // util.inspect.styles.boolean = "red";
24 function DebugNode(n) {
25 RED.nodes.createNode(this,n);
27 this.complete = n.complete;
28 this.console = n.console;
29 this.active = (n.active == null)||n.active;
32 this.on("input",function(msg) {
33 if (this.complete == "true") { // debug complete msg object
34 if (this.console == "true") {
35 node.log("\n"+util.inspect(msg, {colors:useColors, depth:10}));
38 sendDebug({id:this.id,name:this.name,topic:msg.topic,msg:msg,_path:msg._path});
40 } else { // debug just the msg.payload
41 if (this.console == "true") {
42 if (typeof msg.payload === "string") {
43 node.log((msg.payload.indexOf("\n") != -1 ? "\n" : "") + msg.payload);
45 else if (typeof msg.payload === "object") { node.log("\n"+util.inspect(msg.payload, {colors:useColors, depth:10})); }
46 else { node.log(util.inspect(msg.payload, {colors:useColors})); }
49 sendDebug({id:this.id,name:this.name,topic:msg.topic,msg:msg.payload,_path:msg._path});
55 RED.nodes.registerType("debug",DebugNode);
57 function sendDebug(msg) {
58 if (msg.msg instanceof Error) {
59 msg.msg = msg.msg.toString();
60 } else if (msg.msg instanceof Buffer) {
61 msg.msg = "(Buffer) "+msg.msg.toString('hex');
62 } else if (typeof msg.msg === 'object') {
65 if (util.isArray(msg.msg)) { ty = "(Array) "; }
66 msg.msg = ty + JSON.stringify(msg.msg, function(key, value) {
67 if (typeof value === 'object' && value !== null) {
68 if (seen.indexOf(value) !== -1) { return "[circular]"; }
74 } else if (typeof msg.msg === "boolean") {
75 msg.msg = "(boolean) "+msg.msg.toString();
76 } else if (msg.msg === 0) {
78 } else if (msg.msg == null) {
79 msg.msg = "(undefined)";
82 if (msg.msg.length > debuglength) {
83 msg.msg = msg.msg.substr(0,debuglength) +" ....";
86 RED.comms.publish("debug",msg);
89 DebugNode.logHandler = new events.EventEmitter();
90 DebugNode.logHandler.on("log",function(msg) {
91 if (msg.level == "warn" || msg.level == "error") {
95 RED.log.addHandler(DebugNode.logHandler);
97 RED.httpAdmin.post("/debug/:id/:state", function(req,res) {
98 var node = RED.nodes.getNode(req.params.id);
99 var state = req.params.state;
101 if (state === "enable") {
104 } else if (state === "disable") {