Answer the question
In order to leave comments, you need to log in
To what extent was the task completed correctly, what should be corrected?
There was a task to process "GET", "POST", "DELETE" requests.
Wrote. It seems like everything even works. But it is clear that there are 100,500 shortcomings.
Can you please tell me what should be added / corrected in the code?curl http://localhost:8080/page/index.html
curl -X DELETE http://localhost:8080/page/index.html
curl -d "Hello world" http://localhost:8080/page/index.html
// app.js
let http = require("http");
let fs = require("fs");
let handler = require("./handler");
new http.createServer(handler).listen(8080);
// handler.js
let url = require("url");
let fs = require("fs");
let config = require("config");
let path = require("path");
module.exports = (req, res) => {
let urlParsed = url.parse(req.url);
let pathname = urlParsed.pathname;
let filePath = path.join(config.publicRoot, pathname);
if (!filePath.startsWith(config.publicRoot + path.sep)) {
res.statusCode = 400;
res.end("Bye bye silly hacker!");
}
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code == "ENOENT") {
res.statusCode = 404;
res.end("404");
} else {
res.statusCode = 500;
res.end("Server Error")
}
}
if (req.method == "GET") {
let file = new fs.ReadStream(filePath);
file.pipe(res);
file.on("error", err => {
res.statusCode = 500;
res.end("Server error");
console.error(err);
});
res.on("close", () => {
file.destroy();
});
}
if (req.method == "POST") {
let file = new fs.createWriteStream(filePath);
req.pipe(file);
res.end();
}
if (req.method == "DELETE") {
try {
fs.unlink(filePath, err => {
if (err) {
throw err;
}
res.statusCode = 200;
res.end("File was removed");
});
} catch (err) {
if (err.code == "ENOENT") {
res.statusCode = 404;
res.end("File not found");
} else {
res.statusCode = 500;
res.end("Error on removing file");
}
}
}
});
};
// config.js
let path = require("path");
module.exports = {
projectRoot: process.cwd(),
publicRoot: process.cwd() + path.sep + "public"
};
Answer the question
In order to leave comments, you need to log in
Well, for starters, split it into files so that each has one handler left and add a simple router that does this.
The next step is to make the request processing as a chain of middleware, in general, according to your wording of the task, it is completely unclear what exactly they wanted from you. What kind of job is this?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question