Reputation: 1077
I'd like to create a module in node.js, that includes a couple of functions.
I'd also need a common object for all of the functions to use.
I tried the following syntax, but it doesn't seem to work:
module.exports = function(obj) {
func1: function(...) {
},
func2: function(...) {
}
}
Where obj
is the common object I want the functions to use.
Upvotes: 0
Views: 753
Reputation: 63589
You're trying to use object syntax within a function. So either get your function to return
your functions, or just use an object instead and export that. To pass in an argument you'll need something like an init
function.
var obj = {
init: function (name) {
this.name = name;
return this;
},
func1: function () {
console.log('Hallo ' + this.name);
return this;
},
func2: function () {
console.log('Goodbye ' + this.name);
return this;
}
};
module.exports = obj;
And then just import it within another file using the init
method. Note the use of return this
- this allows your methods to be chained.
var variable = require('./getVariable'); // David
var obj = require('./testfile').init(variable);
obj.func1(); // Hallo David
obj.func2(); // Goodbye David
Upvotes: 1
Reputation: 15417
You need to return your functions object:
module.exports = function(obj) {
return {
func1: function(...) {
},
func2: function(...) {
}
};
};
Usage:
var commonObj = { foo: 'bar' };
var myModule = require('./my-module')(commonObj);
Upvotes: 3
Reputation: 4151
module.exports
is simply the object that is returned by a require
call.
You could just:
var commonObj = require('myObj');
module.exports = {
func1: function(commonObj) {...},
func2: function(commonObj) {...}
};
Upvotes: 1