Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module exports class Nodes.js

I'm a Nodes.js noob and I'm trying to get my head around module constructs. Thus far I have a module (testMod.js) defined this class construct:

var testModule = {
    input : "",
    testFunc : function() {
        return "You said: " + input;
    }
}

exports.test = testModule;

I attempt to call the testFunc() method thusly:

var test = require("testMod");
test.input = "Hello World";
console.log(test.testFunc);

But I get a TypeError:

TypeError: Object #<Object> has no method 'test'

What the frick am I doing wrong?

like image 983
travega Avatar asked Jan 26 '12 03:01

travega


1 Answers

It's a namespacing issue. Right now:

var test = require("testMod"); // returns module.exports
test.input = "Hello World"; // sets module.exports.input
console.log(test.testFunc); // error, there is no module.exports.testFunc

You could do:

var test = require("testMod"); // returns module.exports
test.test.input = "Hello World"; // sets module.exports.test.input
console.log(test.test.testFunc); // returns function(){ return etc... }

Or, instead of exports.test you could do module.exports = testModule, then:

var test = require("testMod"); // returns module.exports (which is the Object testModule)
test.input = "Hello World"; // sets module.exports.input
console.log(test.testFunc); // returns function(){ return etc... }
like image 157
Daniel Mendel Avatar answered Oct 31 '22 18:10

Daniel Mendel