This repository was archived by the owner on Dec 19, 2023. It is now read-only.
forked from moorthi07/marscode
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
107 lines (93 loc) · 3.55 KB
/
index.js
File metadata and controls
107 lines (93 loc) · 3.55 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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
'use strict'
var http = require('http'),
fs = require('fs'),
querystring = require('querystring'),
validExtensions = {
"css": "text/css",
"js": "application/javascript",
"html": "text/html",
"png": "image/png"
};
var requestListener = function (request, response) {
var path = process.cwd();
var delay = (0.5 + (Math.random() / 2)) * 100;
request.url = request.url.replace(/(\.\.)/g, '');
if (request.url.indexOf('/api') === 0) {
path += querystring.unescape(request.url).slice(4).replace(/(\.\.)/g, '');
var pathStat = fs.lstatSync(path);
console.log('reqbody', request.body);
if (request.method == "GET") {
sendDir();
} else if (request.method == "POST") {
if (pathStat.isFile()) {
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
console.log('body......', body);
fs.writeFile(path, body, function (err) {
if (err) throw err;
console.log("It's saved");
});
});
response.end("Saved....");
}
} else {
response.end("Undefined request .");
}
function sendDir() {
if (pathStat.isDirectory()) {
fs.readdir(path, function (err, map) {
if (!err) {
var directories = map.filter(function (dirPath) {
return fs.lstatSync(path + '/' + dirPath).isDirectory() && dirPath.indexOf('.') !== 0;
}),
files = map.filter(function (filePath) {
return fs.lstatSync(path + '/' + filePath).isFile() && filePath.indexOf('.') !== 0;
});
response.writeHead(200, {
'Content-Type': 'application/json'
});
response.write(JSON.stringify({
'diretories': directories,
'files': files
}));
response.end();
} else {
response.wrteHead(400);
response.end(err);
}
});
} else {
try {
response.writeHead(200, {
'Content-Type': 'application/octet-stream'
});
response.write(fs.readFileSync(path));
response.end();
} catch (e) {
response.writeHead(500);
response.end();
}
}
}
} else {
var file = 'public' + (request.url == '/' ? '/index.html' : request.url),
ext = file.split('.').pop(),
contentType = validExtensions[ext] || 'application/octet-stream';
if (fs.existsSync(file)) {
response.writeHead(200, {
'Content-Type': contentType
});
response.write(fs.readFileSync(file));
response.end();
} else {
response.writeHead(400);
response.end();
}
}
};
var server = http.createServer(requestListener);
server.listen(8080);
console.log('Sever listen on localhost:8080');