Node.js <class> is not a constructor

I get the "HttpHandlers is not a constructor" error when trying to instantiate this class using "new".

An instance of the class is executed (../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; this.name = "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; 

Calling code:

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

Stacktrace:

 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) 
+10
source share
2 answers

When you assigned this:

 exports.HttpHandlers = HttpHandlers; 

You will need to match this with this:

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

You assign a property to your .HttpHandlers module without assigning the entire module, so if you want this property, you need to reference the property. If you want it to work in a different way, you can change it to this:

 exports = HttpHandlers; 

And then your require() may work the way you do it:

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

I got this error when calling new ClassName(); , and it was called in the ClassName class by the absence of a "module". from module.exports = ClassName

Just in case, if someone else is as stupid as me ...

0
source

All Articles