Search code examples
node.jsconsole.lognode-modulesclim

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


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?


Solution

  • 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..');