Pretty Print object - Node.js Object

Node.js examples for Object:Object Operation

Description

Pretty Print object

Demo Code


function pp(obj) {
  log(prettyPrint(obj));/*from  w  ww. ja  va 2  s .  c  om*/
}

function prettyPrint(obj) {
  var toString = Object.prototype.toString, newLine = "\n", space = " ", tab = 4, buffer = "",
  // Second argument is indent
  indent = arguments[1] || 0,
  // For better performance, Cache indentStr for a given indent.
  indentStr = (function(n) {
    var str = "";
    while (n--) {
      str += space;
    }
    return str;
  })(indent);

  if (!obj || (typeof obj != "object" && typeof obj != "function")) {
    // any non-object ( Boolean, String, Number), null, undefined, NaN
    buffer += obj;
  } else if (toString.call(obj) == "[object Date]") {
    buffer += "[Date] " + obj;
  } else if (toString.call(obj) == "[object RegExp") {
    buffer += "[RegExp] " + obj;
  } else if (toString.call(obj) == "[object Function]") {
    buffer += "[Function] " + obj;
  } else if (toString.call(obj) == "[object Array]") {
    var idx = 0, len = obj.length;
    buffer += "[" + newLine;
    while (idx < len) {
      buffer += [ indentStr, idx, ": ",
          prettyPrint(obj[idx], indent + tab) ].join("");
      buffer += "\n";
      idx++;
    }
    buffer += indentStr + "]";
  } else { // Handle Object
    var prop;
    buffer += "{" + newLine;
    for (prop in obj) {
      buffer += [ indentStr, prop, ": ",
          prettyPrint(obj[prop], indent + tab) ].join("");
      buffer += newLine;
    }
    buffer += indentStr + "}";
  }

  return buffer;
}

Related Tutorials