1

I'm using clim and I replace the console object with it. But I only want to replace it if the module exists.

try {
    var console = require('clim')();
} catch(err) {}
console.log('checking..');

If the module doesn't exists it makes the console undefined.

Strangely, saving the console object and replacing doesn't work either

var console_backup = console;
try {
    var console = require('clim')();
} catch(err) {
    if (err) var console = console_backup;
}
console.log('checking..');

Still throws error (console goes undefined) when clim doesn't exist.

http://runnable.com/U8vlFEpIYtkiV2N9/24850946-console-for-node-js

How to make work replacing the console with clim only when it exists?

laggingreflex
  • 32,948
  • 35
  • 141
  • 196

2 Answers2

1

Your second attempt is close, but you need to explicitly identity that you want to reference the global console when setting console_backup or it will reference the hoisted, local console variable, even though you haven't declared it yet:

var console_backup = global.console;
try {
    var console = require('clim')();
} catch(err) {
    if (err) var console = console_backup;
}
console.log('checking..');

or simplify it to:

try {
    var console = require('clim')();
} catch(err) {
    if (err) console = global.console;
}
console.log('checking..');
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
0

You can't overwrite the global console like that. The var console is just creating a local variable that shadows the global console, not even global.console = ... will work.

You could overwrite console.log, etc. individually or overwrite process.stdout.write (what console.log uses internally) which would allow you to hook into stdout writing at a lower level. This would also catch anyone else that may use process.stdout.write directly.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • I don't want to overwrite. Just want to create a local `console` variable if `clim` exists, just like it does when it *does* exist. Unfortunately it's still getting overwritten anyways with `undefined` object. – laggingreflex Jul 20 '14 at 13:46