在Node中导出和要求并不起作用,所以类是未定义的

时间:2017-04-25 11:16:27

标签: javascript node.js module

我有这三个类:

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;

当我运行需要这两个类(以及fs和path)的TypeChecker类时,我收到以下错误:

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

我正确地导出类并尝试实例化它们,但这是我得到的错误。知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您需要声明TypeErrorCheckerTranspiler vars。尝试更新

require('./type_error_checker/TypeErrorChecker');

进入

const TypeErrorChecker = require('./type_error_checker/TypeErrorChecker');

Transpiler

也一样