Reputation: 6963
Node Noob here...experimenting with Exports and Require...
I have a Javascript file named GoogleHomePage.js that contains this code:
var GoogleHomePage = function (){
module.exports.Home = function () {
var homepage = "http://www.google.com";
browser.get(homepage);
}
}
I then want to use require from another file named FileB.js like this:
var g = require("./GoogleHomePage.js");
g.Home();
When g.Home() is run, I get Undefined... Yet, when I look at g in the debugger, I can see that it has a function named Home...
If I type in g.Home in console window it shows me the function code...
How do I get g.Home() to execute? Is this happening because there is no g object e.g. var x = new g() or would it be var x = new GoogleHomePage()?
Upvotes: 0
Views: 46
Reputation: 206
Instead of
var GoogleHomePage = function (){
module.exports.Home = function () {
var homepage = "http://www.google.com";
browser.get(homepage);
}
}
you want
module.exports = function () {
var homepage = "http://www.google.com";
browser.get(homepage);
}
module
is a variable local to the module in question, and exports
is a property of that object. The function GoogleHomePage
never gets called in your code, so your assignment never runs.
When you require the module, just do
var g = require('./GoogleHomePage');
g();
The .js
is unnecessary.
Upvotes: 1
Reputation: 14419
You are wrapping your export in a function and it is not going to work right. Try this instead:
GoogleHomePage.js:
module.exports = function() {
var homepage = "http://www.google.com";
browser.get(homepage);
}
FileB.js
var googleHomePage = require("./GoogleHomePage.js");
googleHomePage();
So export the function directly -- there is no need to wrap it in that odd var GoogleHomePage = function (){ ... }
construct.
If you want to export multiple things in GoogleHomePage
, you can export an object with properties like so:
GoogleHomePage.js:
module.exports = {
Home: function() {
var homepage = "http://www.google.com";
browser.get(homepage);
},
SomethingElse: function() {
// ...
}
};
Then FileB.js would look like:
var googleHomePage = require("./GoogleHomePage.js");
googleHomePage.Home();
Or you could do:
var home = require("./GoogleHomePage.js").Home;
home();
Upvotes: 1