Tuesday, 25 April 2017

Exporting and requiring in Node doesn't work, says class is undefined

I have these three classes:

TypeChecker:

require('./type_error_checker/TypeErrorChecker');
require('./transpiler/Transpiler');

class TypeChecker {
    constructor() {
        console.log("TypeChecker initialised");
    }

    readFile(file) {
        var fs = require("fs");
        var path = require("path");

        var filePath = path.join(__dirname, "readfile.js");

        fs.readFile(filePath, { encoding: "utf-8" }, function(err,data) {
            if (!err) {
                console.log("received data: " + data);
                response.writeHead(200, {"Content-Type": "text/html"});
                response.write(data);
                response.end();
            } else {
                console.log(err);
            }
        });
    }
}

let typeChecker = new TypeChecker();
new TypeErrorChecker();
new Transpiler();

typeChecker.readFile();

TypeErrorChecker:

class TypeErrorChecker {
    constructor() {
        console.log("TypeErrorChecker initialised");
    }
}

module.exports = TypeErrorChecker;

Transpiler:

class Transpiler {
    constructor() {
        console.log("TypeChecker transpiler initialised");
    }
}

module.exports = Transpiler;

When I run the TypeChecker class which requires both these classes (as well as fs and path), I get the following error:

new TypeErrorChecker();
    ^

ReferenceError: TypeErrorChecker is not defined at Object.<anonymous (/Applications/AMPPS/www/TypeCheckerJS_nowp/src/typechecker.js:29:5)
at Module._compile (module.js:573:32)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)
at Module.runMain (module.js:607:10)
at run (bootstrap_node.js:382:7)
at startup (bootstrap_node.js:137:9)
at bootstrap_node.js:497:3

I export the classes properly and try to instantiate them, but this is the error I get. Any idea how to fix this?



via erol_smsr

No comments:

Post a Comment