Search code examples
javascriptnode.jsnwjs

module.exports function behaves differently than regular function


I have a function:

test = function() { 
         console.log("hello");
         return "goodbye"; 
       }

When I call it, it behaves as expected:

   -> test()   
      hello   
   <- "goodbye"

However if I try to to put this function in a separate file called "tester.js":

module.exports = {
  test: function() { 
      console.log("hello");
      return "goodbye"; 
  }
};

...it does not behave the same way. The console.log statement is not output:

var tester = require('./tester');
-> tester.test()
<- "goodbye"

Even though if I type tester.test and test at the console they look identical.

Why is this and how can I fix it? Note this is a toy example; in my actual code, I am returning an object where I modified object.stdout.on('data', function() {...}) to log to the console.


Solution

  • This appears to be an old "bug" in nwjs wherein required modules receive a different the node version of console rather than the WebKit version.

    The bug is described here: https://github.com/nwjs/nw.js/issues/196

    A workaround suggested by @karlrwjohnson is to pass console as an argument to your module functions.