Reputation: 5712
Yes, this has been asked to death before, but none of these work for me.
I'm getting a TypeError: Config is not a constructor
when calling the Config
constructor. Going through other SO questions and MDN, it appears the usual cause of this error is either shadowing the constructor or calling a non-callable type, but neither of these check out in my project.
This is the call:
var Server = require("./server.js").Server;
var Config = require("./config.js").Config;
new Server(new Config("app/config.json")).run();
In ./config.js
:
var fs = require("fs");
exports.Config = file => {
var json;
if (fs.existsSync(file) && !fs.lstatSync(file).isDirectory()) {
json = JSON.parse(fs.readFileSync(file));
}
else {
throw new ReferenceError("File doesn't exist: can't load config");
}
this.has = key => {
return json.hasOwnProperty(key);
};
this.get = key => {
return json[key] || null;
};
this.set = (key, value, write) => {
json[key] = value;
if (write) {
fs.writeFileSync(file, JSON.stringify(json));
}
};
};
Logging the type of Config
before calling it reveals that it's a Function
, so it's almost certainly the same function as is defined in config.js
. So, why is Node telling me it's not a constructor?
Upvotes: 2
Views: 1752
Reputation: 1074248
So, why is Node telling me it's not a constructor?
Because it's not a constructor. :-) Arrow functions are never constructors, they close over this
and have no prototype
property, and so cannot be used as constructors (which need to have a specific this
set when they're called via new
, and need to have a prototype
property so it can be used to set the [[Prototype]] of the object created via new
).
Either 1. Make it a function
function, or 2. Make it a class
.
Here's the one line change for #1:
exports.Config = function(file) {
Upvotes: 4