Home > OS >  Why does this code throw a reference error?
Why does this code throw a reference error?

Time:03-29

So i tried using the file system with the http server, first i tried using anonymous callback functions and it ran, then i tried using named callback functions.

What i expected it to happen is to write from the html page to the server:

const FileSystem = require("fs")
const Http = require("http")

function ManageServer(req, res) {
  FileSystem.readFile("index.html", ReadFileFunc)
}

function ReadFileFunc(err, data) {
  res.writeHead(200, {"Content-Type" : "text/html"})
  res.write(data)
  return res.end()
}

const server = Http.createServer(ManageServer).listen(8080)

setTimeout(() => {
  server.close()
}, 10000)

but instead of doing that it threw a reference error saying that res is not defined.

CodePudding user response:

You can't reach res from within ReadFileFunc() as it's a function argument for a different function that isn't a parent function so you can't reach it. You can either move ReadFileFunc() inside of ManageServer or you can pass res to ReadFileFunc.

Option 1: Move ReadFileFunc code inside of ManageServer

function ManageServer(req, res) {
  FileSystem.readFile("index.html", (err, data) => {
      if (err) {
          console.log(err);
          res.statusCode = 500;
          res.end();
          return;
      }
      res.writeHead(200, {"Content-Type" : "text/html"});
      res.write(data);
      res.end();
  });
}

Option 2: Pass res to ReadFileFunc

function ManageServer(req, res) {
  FileSystem.readFile("index.html", (err, data) => {
     ReadFileFunc(err, data, res);
  });
}

function ReadFileFunc(err, data, res) {
  if (err) {
      console.log(err);
      res.statusCode = 500;
      res.end();
      return;
  }
  res.writeHead(200, {"Content-Type" : "text/html"})
  res.write(data);
  res.end();
}
  • Related