I followed this example: Coffeescript and node.js confusion. require instantiates class?, but it doesn't seem to work - the error is TypeError: undefined is not a function
, so I must be doing something wrong. I have a simple coffee-script executable. Here are my steps:
Create a folder structure:
appmq
my_executable
my_class.coffee
package.json
The file contents:
package.json
:
{
"name": "appmq",
"version": "0.0.1",
"description": "xxxxxx",
"repository": "",
"author": "Frank LoVecchio",
"dependencies": {
},
"bin": {"appmq": "./my_executable"}
}
my_executable
:
#!/usr/bin/env coffee
{CommandLineTools} = require './my_class'
cmdTools = new CommandLineTools()
cmdTools.debug()
my_class
:
class CommandLineTools
debug: () ->
console.log('Version: ' + process.version)
console.log('Platform: ' + process.platform)
console.log('Architecture: ' + process.arch)
console.log('NODE_PATH: ' + process.env.NODE_PATH)
module.exports = CommandLineTools
I then install the application via:
sudo npm install -g
Then I run the application (which produces the error I noted above):
appmq
Chris is right in his answer, but it's got nothing to do with whether you have an explicit constructor in your class but rather what you are exporting.
If you want to export a single class like this:
module.exports = CommandLineTools
Then, when you require
, what is returned will be what you assigned to module.exports
above, i.e.:
CommandLineTools = require './my_class'
And this will work. What you are doing, is exporting in the manner described above, but you are using CoffeeScript's destructuring assignment:
{CommandLineTools} = require './my_class'
which compiles to the js:
var CommandLineTools;
CommandLineTools = require('./my_class').CommandLineTools;
Which fails, because the require
call will not return an object with the property CommandLineTools
, but rather CommandLineTools
itself. Now, if you wanted to use the destructuring assigment above, you would have to export CommandLineTools
like this:
exports.CommandLineTools = CommandLineTools
I hope this will shed some light on the matter. Otherwise, ask away in the comments!
You don't have a constructor in your class. Exchange
{CommandLineTool} = require './my_class'
with
CommandLineTool = require './my_class'
or write a (empty) constructor.