Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
2  
Try require('coffee-script'); rather than using a full path. Stuff in node_modules is automatically picked up automatically. –  sakkaku Jul 18 at 17:24

1 Answer

up vote 5 down vote accepted

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
share|improve this answer
 
Wow, thanks for the quick reply! This fixed it :] I can't accept it yet, but I will once the waiting period is over. –  Bucco Jul 18 at 17:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.