Check if a module exists, if so replace console with it, otherwise not. Not working, console gets undefined

361 views Asked by At

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?

2

There are 2 answers

0
JohnnyHK On BEST ANSWER

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..');
1
mscdex On

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.