-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha.js
76 lines (65 loc) · 1.68 KB
/
a.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
const fs = require('fs')
const url = require('url')
const http = require('http')
const process = require('process')
const path = require('path')
if( process.argv.length<=2 ){
console.log('usage: node a.js [codedir] [--debug?]')
process.exit(0x1);
}
let codeDir = process.argv[2];
let debugOn = process.argv[3] === "--debug"
codeDir.replace('~', process.env.HOME)
if( debugOn ){
console.log('debugOn', debugOn)
console.log('codeDir', codeDir)
}
function readCode(){
let classifyFile = path.join(codeDir, '.classify.json');
let a = {};
try{
fs.accessSync(classifyFile, fs.constants.R_OK);
a = JSON.parse(fs.readFileSync(classifyFile));
}catch(err){
a = {'-*- code -*-': fs.readdirSync(codeDir)};
}
Object.keys(a).forEach(key => {
a[key] = a[key].map(item => ({
name: item,
text: fs.readFileSync(path.join(codeDir,item)).toString('utf-8')
}));
});
return JSON.stringify(a);
}
const server = http.createServer((req, res) => {
let pathname = url.parse(req.url).pathname
if( debugOn ){
console.log('[debug] connect - pathname: ', pathname)
}
if( pathname === '/code' ){
res.end(readCode())
return ;
}
// 检测请求的主机地址
const isLocalhost = req.headers.host.startsWith('localhost');
if( pathname === '/' ){
if (isLocalhost) {
pathname += 'index2.html';
} else {
pathname += 'index.html';
}
}
pathname = 'public'+pathname;
fs.readFile(pathname, (err, data) => {
if(err){
if( debugOn ){
console.log('[debug]', err.message)
}
res.end('404')
return ;
}
res.end(data)
})
})
console.log('listen on http://0.0.0.0:8080')
server.listen(8080, '0.0.0.0')