ReferenceError: DocumentReader is not defined NODE JS

问题: i have this class called DocumentReader in a "/lib/DocumentReader.js" i tried to export it using module.exports = DocumentReader; and i have another file called main.js tha...

问题:

i have this class called DocumentReader in a "/lib/DocumentReader.js" i tried to export it using module.exports = DocumentReader; and i have another file called main.js that i'm trying to use this file in it but when ever i do this

var doc = require("./lib/DocumentReader.js");
var docr = new DocumentReader("");

i get this error ReferenceError: DocumentReader is not defined

this is the class in DocumentReader.js

var fs = require("fs");
class DocumentReader{
    constructor (filepath){
        this.filepath = filepath;
    }

     readfile(){

        fs.readFile(this.filepath,function(err,data){
                if(err) throw err;

            console.log(data);
        });
    }

}

i tried looking for similiar errors or cases like this but i didn't find them

when i print the value of doc i get this [Function: DocumentReader]


回答1:

When you require something you need to call new on the variable that it was assigned to via require. DocumentReader doesn't exist because you haven't declared DocumentReader in your file requiring lib/DocumentReader.

module.exports only exports the reference to class DocumentReader which is a function with the name DocumentReader. This is why when you use console.log(doc) you're still seeing [Function: DocumentReader] printed out.

const DocumentReader = require('./lib/DocumentReader')
const docr = new DocumentReader('')
  • 发表于 2019-01-02 21:03
  • 阅读 ( 361 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除