-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
52 lines (50 loc) · 1.71 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const { createServer } = require("http");
const { stat, createReadStream, createWriteStream } = require("fs");
const { promisify } = require("util");
const fileName = "../../AdvancedStreams/stream/powder-day.mp4";
const fileInfo = promisify(stat);
const multiparty = require("multiparty");
const responseWithVideo = async (req, res) => {
const { size } = await fileInfo(fileName);
const range = req.headers.range;
if (range) {
let [start, end] = range.replace(/bytes=/, "").split("-");
start = parseInt(start, 10);
end = end ? parseInt(end, 10) : size - 1;
res.writeHead(206, {
"Content-Range": `bytes ${start}-${end}/${size}`,
"Content-Ranges": "bytes",
"Content-Length": end - start + 1,
"Content-Type": "video/mp4",
});
createReadStream(fileName, { start, end }).pipe(res);
} else {
res.writeHead(200, {
"Content-Length": size,
"Content-Type": "video/mp4",
});
createReadStream(fileName).pipe(res);
}
};
createServer((req, res) => {
if (req.method === "POST") {
let form = new multiparty.Form();
form.on("part", (part) => {
part.pipe(createWriteStream(`./${part.filename}`)).on("close", () => {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(`<h1> File uploaded: ${part.filename}</h1>`);
});
});
form.parse(req);
} else if (req.url === "/video") {
responseWithVideo(req, res);
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(`
<form enctype="multipart/form-data" method="POST" action="/"
<input type="file" name="upload-file"/>
<button>Upload File</button>
</form>
`);
}
}).listen(3001, () => console.log("server is running - 3001"));