2

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]

0

1 Answer 1

2

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('')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.