forked from krvikash35/nodejs-download-upload-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
87 lines (78 loc) · 2.25 KB
/
server.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const http = require('http');
const fs = require('fs');
const path = require('path');
let port = process.argv[2] || 3000;
const httpServer = http.createServer(requestHandler);
httpServer.listen(port, () => {console.log('server is listening on port '+ port)});
function requestHandler(req, res){
if(req.url === '/'){
sendIndexHtml(res);
}else if( req.url === '/list'){
sendListOfUploadedFiles(res);
}else if( /\/download\/[^\/]+$/.test(req.url)){
sendUploadedFile(req.url, res);
}else if( /\/upload\/[^\/]+$/.test(req.url) ){
saveUploadedFile(req, res)
}else{
sendInvalidRequest(res);
}
}
function sendIndexHtml(res){
let indexFile = path.join(__dirname, 'index.html');
fs.readFile(indexFile, (err, content) => {
if(err){
res.writeHead(404, {'Content-Type': 'text'});
res.write('File Not Found!');
res.end();
}else{
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(content);
res.end();
}
})
}
function sendListOfUploadedFiles(res){
let uploadDir = path.join(__dirname, 'download');
fs.readdir(uploadDir, (err, files) => {
if(err){
console.log(err);
res.writeHead(400, {'Content-Type': 'application/json'});
res.write(JSON.stringify(err.message));
res.end();
}else{
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(files));
res.end();
}
})
}
function sendUploadedFile(url, res){
let file = path.join(__dirname, url);
fs.readFile(file, (err, content) => {
if(err){
res.writeHead(404, {'Content-Type': 'text'});
res.write('File Not Found!');
res.end();
}else{
res.writeHead(200, {'Content-Type': 'application/octet-stream'});
res.write(content);
res.end();
}
})
}
function saveUploadedFile(req, res){
console.log('saving uploaded file');
let fileName = path.basename(req.url);
let file = path.join(__dirname, 'download', fileName)
req.pipe(fs.createWriteStream(file));
req.on('end', () => {
res.writeHead(200, {'Content-Type': 'text'});
res.write('uploaded succesfully');
res.end();
})
}
function sendInvalidRequest(res){
res.writeHead(400, {'Content-Type': 'application/json'});
res.write('Invalid Request');
res.end();
}