I am writing an agnostic logging mechanism that works inside the browser and in nodejs (e.g. console.debug is missing in nodejs).
// UMD with no dependencies
(function(global, factory) {
if (typeof module === 'object') {
module.exports = factory();
// GLOBAL IS NOT WHAT I WOULD EXPECT, YOU?
global.console = factory();
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
global.console = factory();
}
})(this, function() {
function logger() {};
return logger;
});
I stumbled upon 2 differences I cannot explain:
As expected, for the browser case the variable 'global' has the value of window. However, with Nodejs 'global' is just a simple object and not the global variable of Nodejs. Is this intended? One could execute the module using '.call' to preserve the corresponding context for the browser and Nodejs. As this is a common accepted UMD pattern, I was doubting if it is a bad idea to modify the global variable in Nodejs, which takes me to next question.
Inside the browser it is possible to overwrite the global console function by passing over my custom object to the console property. One could have back the old behaviour by restoring the reference to the original object. This is not possible in Nodejs, it fails when I am trying to pass my own logger object to global.console. Strange enough, that I did not find any useful documentation in the web...
Hope to get some clarifications!