0

I'm trying create simple http server using nodejs, I wrote class named FileReader which get object of [file type, file path] as a key value pair.

after initializing using call eg. new FileReader({"html": "./index.html"})

keep show me undefined if I console log it.

I wonder why this happening.

const fs = require("fs");
const http = require("http");

class FileReader {
  html;
  css;
  js;
  constructor(props){
    for(const [key, file] of Object.entries(props)) {
      fs.readFile(file, (err, data) => {
        if(err){
          throw err;
        }
        switch(key){
          case "html":
            this.html = data.toString();
            console.log(this.html) // <- it shows correctly what I aim for
            break;
          case "css":
            this.css = data;
            break;
          case "js":
            this.js = data;
            break;
        }
      })
    }
  }

  
}

const reader = new FileReader({ 
  html: "./index.html",
  css: "./style.css",
  js: "./index.js", 
});
console.log("html: ", reader.html); // <-- undefined
console.log("js: ", reader.js); // <-- undefined
console.log("css: ", reader.css); // <-- undefined
dante
  • 933
  • 4
  • 16
  • 39
  • 1
    Because `readFile` is **asynchronous**. When you log your properties in the code at the end, it hasn't finished its work yet. – T.J. Crowder Mar 11 '21 at 13:09
  • oh I see, I'm not get used to readFile so I confued it's a synchronous. thank you ! – dante Mar 11 '21 at 13:15

0 Answers0