I have 3 different files called: app.js, ServerManager.js and Users.js.
To start everything, I run app.js which runs my ServerManager.
Running ServerManager in App.js:
var ServerManager = require('./modules/ServerManager.js');
var serverManager = new ServerManager({
app: app,
path: __dirname
});
Then serverManager is called and I can do stuff in there, then I'm trying to send stuff to Users.js from ServerManager but it seems like it doesn't work.
ServerManager.js
var config = require('../config.js');
var express = require('express');
var colors = require('colors');
var DatabaseManager = require('../modules/DatabaseManager.js');
var RouteManager = require('../modules/RouteManager.js');
var Users = require('../data/users.js');
module.exports = function(options){
return new ServerManager(options);
}
var ServerManager = function (options) {
var self = this;
this.app = options.app;
this.options = options;
this.dbManager = new DatabaseManager();
this.dbManager.use();
this.RoutesManager = new RouteManager(this.app);
this.RoutesManager.use();
this.usersManager = new Users(this);
}
ServerManager.prototype.getDatabase = function () {
return this.dbManager();
}
Users.js - Marked in code what it can't find.
module.exports = function (ServerManager) {
return new Users(ServerManager);
};
var Users = function (ServerManager) {
var self = this;
this.serverManager = ServerManager;
};
Users.prototype.createUser = function (username, email, password) {
this.serverManager.getDatabase(); <--- Can't find getDatabase()
};
I think that you should change your Users.js code to:
// This is the Users object
// and this function is its constructor
// that can create users instances
var Users = function (ServerManager) {
var self = this; this.serverManager = ServerManager;
};
// We define a method for the user object
Users.prototype.createUser = function (username, email, password) {
this.serverManager.getDatabase();
};
// We export the user object
module.exports = Users;
Now the then you do
var Users = require('../data/users.js');
you get the User object.
And so, you can do new Users(...).
The same thing has to be done for the ServerManager.
If you want to use your code as it is, you don't have to use the new keyword on the imported object.
Related
I keep getting this message saying Newpage is not a constructor i have racked my brains out for the past 5 hours trying to resolve this issue and no progress i have looked at the following sites
How to call a function in another function in protractor
'TypeError: undefined is not a function' using Protractor
Maybe it is something simple i don't know. All I am trying to do is call a function form my page object file. Still no success any help would be appreciated.
my code:
var newPage = require('./newPage.js');
describe('Get Payroll Information', function() {
beforeAll(function(){
var newPageObj = new newPage();
});
var EC = protractor.ExpectedConditions;
var status;
var clientid, weeknum, pdate;
it('Get CycleStatus, Paydate, Weeknumber, Clientid - completed', function () {
const fs = require('fs');
const cycle = $('#cycleStatusID'); // cycle status
const client = $('#clientID'); // clientid
const week = $('#companyIdBar_weekId'); // week number
const payDate = $('#companyIdBar_processDateId');
//------------Get PayDate --------------------------------
.then(() => {
payDate.isPresent().then(function(present){
if(present){
payDate.getText().then(function(text){
pDate = text;
console.log('paydate (' + pDate + ') is displayed');
});
} else {
console.log('pay date not present');
//return;// breaks for loop like (break)
}
})
})
.then(() => {
writeValueToFile(cycleStatus,clientID,weekNum,pDate);
})
.then(() => {
newPageObj.goBack();
console.log('return to support');
});
});// master then promise
});//spec function
Protractor console message
newPage.js Code:
newPage = function(){
function goBack(){
var returnbtn = $('#returnToADPClick');
var search1 = ($$('input[id="toolbarQuickSearch"]').get(0));
returnbtn.click();
browser.wait(EC.elementToBeClickable(search1),20,000);
};
};
module.exports = new newPage();
changed to module.exports = new newPage; // this work now i get
Your newPage.js is exporting an object, not a function/class/constructor. Change the module.exports to just newPage like this:
newPage = function(){
function goBack(){
var returnbtn = $('#returnToADPClick');
var search1 = ($$('input[id="toolbarQuickSearch"]').get(0));
returnbtn.click();
browser.wait(EC.elementToBeClickable(search1),20,000);
};
};
module.exports = newPage;
Failed: newPageObj Object not defined
This is because of the scope of the newPageObj variable - currently it is only defined in the scope of beforeAll. Declare your variable at the higher level:
var newPage = require('./newPage.js');
var newPageObj;
describe('Get Payroll Information', function() {
beforeAll(function() {
newPageObj = new newPage();
});
// ...
});
Can someone please explain what the correct way is to have multiple objects inherit from a parent and have their own prototype functions? I'm trying to do this in nodeJS.
I have these files.
ParserA_file
var ParentParser = require('ParentParser_file');
module.exports = ParserA;
ParserA.prototype = Object.create(ParentParser.prototype);
ParserA.prototype.constructor = ParserA;
ParserA.prototype = ParentParser.prototype;
function ParserA(controller, file) {
ParentParser.call(this, controller, file);
this.controller.log('init --- INIT \'parser_A\' parser');
this.date_regex = /([0-9]{1,2})?([A-Z]{3})?([0-9]{2})? ?([0-9]{2}:[0-9]{2})/;
this.date_regex_numeric = /(([0-9]{1,2})([0-9]{2})([0-9]{2}))? ?([0-9]{2}:[0-9]{2})?/;
this.date_format = 'DDMMMYY HH:mm';
}
ParserA.prototype.startParse = function() {
console.log('Starting parse for A');
}
ParserB_file
var ParentParser = require('ParentParser_file');
module.exports = ParserB;
ParserB.prototype = Object.create(ParentParser.prototype);
ParserB.prototype.constructor = ParserB;
ParserB.prototype = ParentParser.prototype;
function ParserB(controller, file) {
ParentParser.call(this, controller, file);
this.controller.log('init --- INIT \'parser_B\' parser');
this.date_regex = /([0-9]{1,2})?([A-Z]{3})?([0-9]{2})? ?([0-9]{2}:[0-9]{2})/;
this.date_regex_numeric = /(([0-9]{1,2})([0-9]{2})([0-9]{2}))? ?([0-9]{2}:[0-9]{2})?/;
this.date_format = 'DDMMMYY HH:mm';
}
ParserB.prototype.startParse = function() {
console.log('Starting parse for B');
}
ParentParser_file
ParentParser = function(controller, file) {
if (!controller) {
throw (new Error('Tried to create a Parser without a controller. Failing now'));
return;
}
if (!file ) {
throw (new Error('Tried to create a Parser without a file. Failing now'));
return;
}
this.controller = null;
this.file = null;
}
module.exports = ParentParser;
Now I require them both in my node app
var ParserA = require('ParserA_file');
var ParserB = require('ParserB_file');
Now, when only one parser is loaded the there is no problem, however, loading them both into my node app and starting parser A
var parser = new ParserA(this, file);
parser.startParse()
returns
init --- INIT 'parser_B' parser'
Now for the question, how come ParserB's function startParse overwrites the startParse from ParserA?
That's because they refer to the same prototype object.
ParserA.prototype = ParentParser.prototype;
...
ParserB.prototype = ParentParser.prototype;
ParserA.prototype === ParserB.prototype; // true
Remove those two lines (which are overwriting the two lines above them anyway) and you'll be good to go.
I have two files in helpers folder, one is EventHelper.js and UserEvent.js,
helpers/EventHelper.js
function EventHelper() {
this.onEventCreated = function(err, e) {...}
this.isExisting = function(id) {...}
}
module.exports = new EventHelper();
helpers/UserEvent.js
var EventHelper1 = require('./EventHelper')
var EventHelper2 = require('./EventHelper.js')
function UserEvent() {
this.fireEvent = function(req, res) {
var EventHelper3 = require('./EventHelper');
...
EventHelper1.onEventCreated(err, e);
EventHelper2.onEventCreated(err, e);
EventHepler3.onEventCreated(err, e);
}
};
module.exports = new UserEvent();
controllers/EventController.js
var EventHelper = require('../helpers/EventHelper')
var UserEvent = require('../helpers/UserEvent');
var EventController = {
fireEvent: function(req, res) {
if(EventHelper.isExisting(req.params.id)) UserEvent.fireEvent(req, res)
...
}
}
EventHelper1 and EventHelper2 in UserEvent.js are always empty(having {}), where as EventHelper3 is being initialised properly and able to refer object's methods properly. I have referred this EventHelper.js in different controllers folder(EventController.js) globally and it was getting populated properly. I am not sure if I am missing something here
You're missing some semicolons:
function EventHelper() {
this.onEventCreated = function(err, e) {...}
this.isExisting = function(id) {...}
}**;**
module.exports = new EventHelper();
For instance after adding this one, I got the EventHelper within your Controller, which I haven't gotten before.
Furthermore (I guess it's just and typo here and not in your actual code, since then you couldn't get an instance for it), it's:
EventHelper3.onEventCreated(err,e);
and not `
EventHepler3.onEventCreated(err,e);
So to sum up, the following is now working for me:
// EventHelper.js
function EventHelper() {
this.onEventCreated = function(err, e) {
console.log('testCreate');
};
this.isExisting = function(id) {
console.log('testExists' + id);
return true;
};
};
module.exports = new EventHelper();
// UserEvent.js
var EventHelper1 = require('./EventHelper.js');
var EventHelper2 = require('./EventHelper.js');
function UserEvent() {
this.fireEvent = function(req, res) {
console.log(req + res);
var EventHelper3 = require('./EventHelper');
EventHelper1.onEventCreated(req, res);
EventHelper2.onEventCreated(req, res);
EventHelper3.onEventCreated(req, res);
};
};
module.exports = new UserEvent();
// EventController.js
var EventHelper = require('../helpers/EventHelper.js');
var UserEvent = require('../helpers/UserEvent.js');
var EventController = {
fireEvent: function(req, res) {
if(EventHelper.isExisting(1)) UserEvent.fireEvent(req, res);
};
}
EventController.fireEvent("1","2");
Withe the following output:
testExists1
12
testCreate
testCreate
testCreate
I hope that I could help you!
I am recently learning express.js. The code below is copied from the router lib of express.js.
var proto = module.exports = function(options) {
options = options || {};
function router(req, res, next) {
router.handle(req, res, next);
}
// mixin Router class functions
router.__proto__ = proto;
router.params = {};
router._params = [];
router.caseSensitive = options.caseSensitive;
router.strict = options.strict;
router.stack = [];
return router;
};
My question is what is returned if I call
var Router = require('./router');
var _router = new Router(...);
What is _router? Is it the function router(req, res, next)? If yes, can I call _router(req, res, next);?
If I am wrong, could someone please explain what does the code do?
If yes, why don't they just do it like:
var proto = module.exports = function(options) {
options = options || {};
var router = {};
// mixin Router class functions
router.__proto__ = proto;
router.params = {};
router._params = [];
router.caseSensitive = options.caseSensitive;
router.strict = options.strict;
router.stack = [];
return router;
};
For your first question:
var Router = require('./router');
var _router = new Router(...);
var Router is a object of created by the function router(req, res, next), and your var router is a new object of Router. In javascript almost everything is an object. You can read more here.
If they use your aproach they won't have a constructor. And they use the constructor to do router.handle(req, res, next); I don't know why they need the handle, you can study more the code or ask the developers. But you probably can use the var router new Router(req,res,next); if you know what the params do.
In the following code I'm expecting console.log to output the data that is passed along with the custom emitter 'output' but that's not occurring. From what I can tell Looper.prototype.output is called properly from withing the server handler but it's not responding to the emitter 'output' event that's defined in Looper.prototype.run. Why isn't my output event handler recognizing these events?
var express = require('express');
var http = require('http');
var spawn = require('child_process').spawn;
var util = require('util');
var fs = require('fs');
var EventEmitter = require("events").EventEmitter;
var sys = require("sys");
function Looper(req) {
this.req = req;
EventEmitter.call(this);
}
sys.inherits(Looper, EventEmitter);
Looper.prototype.run = function() {
var cmd = spawn('./flow',[this.req]); // <-- script that outputs req every second
cmd.stdout.setEncoding('utf8');
cmd.stdout.on('data', function(data) {
this.emit('output',data);
});
}
Looper.prototype.output = function(callback) {
this.on('output', function(data) {
return callback(data.trim());
});
}
var looper = new Looper('blah');
looper.run();
var app = express();
var webServer = http.createServer(app);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.send(
"<h1>hello world</h1>"
);
looper.output(function(res) {
console.log('blah');
console.log(res);
});
});
webServer.listen(3000);
Looper.prototype.run = function() {
var cmd = spawn('./flow',[this.req]); // <-- script that outputs req every second
cmd.stdout.setEncoding('utf8');
cmd.stdout.on('data', function(data) {
this.emit('output',data);
// ^ not what you think it is.
});
}
I think that this is not what you think it is in that callback. You need to capture the value of this outside of the callback first.
Looper.prototype.run = function() {
var self = this; // save this
var cmd = spawn('./flow',[this.req]); // <-- script that outputs req every second
cmd.stdout.setEncoding('utf8');
cmd.stdout.on('data', function(data) {
self.emit('output',data); // use previously saved value of this
});
}
Otherwise, this would default to the global object, and when the global object emits an event, noone is listening to it.