The following code comes from an academic example, its intention is to load a page that exists in the file system:
const sendErrorResponse = res => {
res.writeHead(httpStatus.NOT_FOUND, {"Content-Type": "text/html"});
res.write("<h1>FILE NOT FOUND</h1>");
res.end();
};
const customReadFile = (file_path, res) => {
if (fs.existsSync(file_path)){
fs.readFile(file_path, (error, data) => {
if (error) {
sendErrorResponse(res);
return;
}
res.write(data);
res.end;
})
} else {
sendErrorResponse(res)
}
};
const port = 3000,
http = require("http"),
httpStatus = require("http-status-codes"),
fs = require("fs");
http.createServer((req, res)=> {
let url = req.url;
console.log(`Requested url: ${url}`);
if (url.indexOf(".html") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "text/html"});
customReadFile(`./views${url}`, res);
} else if (url.indexOf(".js") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "text/javascript"});
customReadFile(`./public/js${url}`, res);
} else if (url.indexOf(".css") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "text/css"});
customReadFile(`./public/css${url}`, res);
} else if (url.indexOf(".png") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "image/png"});
customReadFile(`./public/images${url}`, res);
} else {
sendErrorResponse(res);
}
})
.listen(port);
console.log(`The server has started and is listening on port: ${port}`);
The issue is that when rendered the page in the browser (chrome), the loading icon in the tab keeps refreshing like waiting for a resource.
Can you tell me, what is causing this?
CodePudding user response:
In customReadFile
function you are not calling res.end
, just add ()
to fix it.