Vineet Kosaraju
Vineet Kosaraju

Reputation: 5840

node.js coffeescript - issues with requiring modules

I'm having another issue with node.js, this time I cannot get my javascript code to recognize that a coffeescript module's class has functions.

In my main file, main.js I have the following code:

require('./node_modules/coffee-script/lib/coffee-script/coffee-script');
var Utils = require('./test');
console.log(typeof Utils);
console.log(Utils);
console.log(typeof Utils.myFunction);

And in my module, test.coffe, I have the following code:

class MyModule

  myFunction : () ->
    console.log("debugging hello world!")

module.exports = MyModule

Here is the output when I run node main.js :

function
[Function: MyModule]
undefined

My question is, why is my main file loading the correct module, but why is it unable to access the function? What am I doing wrong, whether it be with the coffeescript syntax, or with how I am requiring my module? Let me know if I should clarify my question.

Thanks,

Vineet

Upvotes: 4

Views: 1411

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

myFunction is an instance method, so it won't be accessible directly from the class.

If you want it as a class (or static) method, prefix the name with @ to refer to the class:

class MyModule

  @myFunction : () ->
    # ...

You can also export an Object if the intention is for all methods to be static:

module.exports =

  myFunction: () ->
    # ...

Otherwise, you'll need to create an instance, either in main:

var utils = new Utils();
console.log(typeof utils.myFunction);

Or, as the export object:

module.exports = new Utils

Upvotes: 6

Related Questions