Skip to content

Instantly share code, notes, and snippets.

@BrainCrumbz
Created October 17, 2014 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrainCrumbz/2661f2f45964b6dbfc06 to your computer and use it in GitHub Desktop.
Save BrainCrumbz/2661f2f45964b6dbfc06 to your computer and use it in GitHub Desktop.
CommonJS module used in a ThunderBird add-on
'use strict';
exports.log = log;
exports.dir = dir;
const { components } = require('chrome');
var consoleService = components.classes["@mozilla.org/consoleservice;1"]
.getService(components.interfaces.nsIConsoleService);
const LOG_WITH_DUMP = true;
const LOG_WITH_CONSOLE = false;
const LOG_WITH_ERR_CONSOLE = false;
function log(message) {
if (typeof message === 'undefined') {
message = '<UNDEFINED>';
}
else if (message == null) {
message = '<NULL>';
}
try {
if (LOG_WITH_DUMP) {
dump(message + '\n');
}
if (LOG_WITH_CONSOLE) {
console.log(message);
}
if (LOG_WITH_ERR_CONSOLE) {
consoleService.logStringMessage(message);
}
}
catch (ex) {
dump('Exception while logging: log: ');
dump(ex);
}
}
function dir(hash) {
try {
if (hash == null) log(hash);
var type = toType(hash);
var message = '[' + type + ']';
var count = 0;
if (typeof hash === 'object') {
var loggedProps = [];
/* RIMUOVERE se non utilizzato
var props = Object.keys(hash);
props.forEach(function (prop) {
logProperty(hash, prop, count, loggedProps);
count++;
});
*/
for (var prop in hash) {
logProperty(hash, prop, count, loggedProps);
count++;
}
message += ' { ' + loggedProps.join(', ') + ' }';
}
log(message);
}
catch (ex) {
dump('Exception while logging: dir: ');
dump(ex);
}
}
function logProperty(hash, prop, count, loggedProps) {
var eol = (count % 3 ? '' : '\n');
var value = hash[prop];
var type = toType(value);
var loggedItem = eol + prop + ' [' + type + ']';
if (type != 'function' && type != 'object') {
loggedItem += ': ' + value;
}
loggedProps.push(loggedItem);
}
function toType (obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment