-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
54 lines (52 loc) · 1.67 KB
/
Copy pathserver.js
File metadata and controls
54 lines (52 loc) · 1.67 KB
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
53
54
const { createServer } = require("http");
const { stat, createReadStream, createWriteStream } = require("fs");
const { promisify } = require("util");
const multiparty = require("multiparty");
const file = "./test.mp3";
const fileInfo = promisify(stat);
const responseWithContent = async (req, res) => {
const { size } = await fileInfo(file);
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(200, {
"Content-Range": `bytes ${start}-${end}/${size}`,
"Accept-Ranges": "bytes",
"Content-Length": end - start + 1,
"Content-Type": "audio/mp3"
});
createReadStream(file, { start, end }).pipe(res);
} else {
res.writeHead(200, {
"Content-Type": "audio/mp3",
"Content-Length": size
});
createReadStream(file).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 === "/audio") {
responseWithContent(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(3000, () => console.log("Server is running on port 3000"));