user994165 user994165 - 7 months ago 54
Javascript Question

Node.js <Class> is not a constructor

I'm getting "HttpHandlers is not a constructor" error when trying to instantiate that class using "new".

Class being instantiated (../lib/restifyHandlers/HttpHandlers):

var config = require('config');
module.exports.config = config;

var util = require('util');
var _ = require('underscore');
var EventEmitter = require("events").EventEmitter;

var HttpHandlers = function(eventHandlers) {
var _self = this; = "HttpHandlers";
if (!(this instanceof HttpHandlers)) {
return new HttpHandlers(eventHandlers);

util.inherits(HttpHandlers, EventEmitter);

HttpHandlers.prototype.extractHttpHandlersRequest = function(req, res, next) {
var _self = this;
req.locals = {};
res.locals = {};

module.exports.HttpHandlers = HttpHandlers;

Code making the call:

var HttpHandlers = require('../lib/restifyHandlers/HttpHandlers');
var obj = new HttpHandlers(oneRouteConfig.eventHandlers);


2016-09-10T23:44:41.571-04:00 - [31merror[39m: Sun, 11 Sep 2016 03:44:41 GMT Worker #master: exiting from error: TypeError: HttpHandlers is not a constructor
TypeError: HttpHandlers is not a constructor
at setupRestifyRoute (/usr/apps/das/src/myrepo/nodejs/myapp/lib/router.js:78:14)
at Router.setup_routes (/usr/apps/das/src/myrepo/nodejs/myapp/lib/router.js:40:3)
at /usr/apps/das/src/myrepo/nodejs/myapp/bin/server.js:222:14
at initialize (/usr/apps/das/src/myrepo/nodejs/myapp/bin/server.js:38:9)
at setup_server (/usr/apps/das/src/myrepo/nodejs/myapp/bin/server.js:107:4)
at /usr/apps/das/src/myrepo/nodejs/myapp/bin/server.js:275:4
at /usr/apps/das/src/myrepo/nodejs/myapp/node_modules/temp/lib/temp.js:231:7
at FSReqWrap.oncomplete (fs.js:123:15)


When you assigned this:

exports.HttpHandlers = HttpHandlers;

You would need to match that with this:

var HttpHandlers = require('../lib/restifyHandlers/HttpHandlers').HttpHandlers;

You are assigning a property of your module to be .HttpHandlers, not assigning the whole module so if you want that property, you have to reference the property. If you want it to work the other way, you could change to this:

exports = HttpHandlers;

And, then your require() could work the way you are doing it like this:

var HttpHandlers = require('../lib/restifyHandlers/HttpHandlers');