-
Notifications
You must be signed in to change notification settings - Fork 73
/
server.js
72 lines (64 loc) · 1.94 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
const express = require('express')
const ts = require('typescript')
const fs = require('fs')
const path = require('path')
function listFilesRec(_itemAbs) {
const root = path.join(__dirname, 'static', 'songs')
const itemAbs = _itemAbs || root
const paths = []
const stat = fs.statSync(itemAbs)
if (stat.isDirectory()) {
const items = fs.readdirSync(itemAbs)
items.forEach(it => {
paths.push(...listFilesRec(path.join(itemAbs, it)))
})
} else if (stat.isFile()) {
const itemRel = path.join('/songs', path.relative(root, itemAbs)).replace(/\\/g, '/')
paths.push({
mtime: stat.mtime,
path: itemRel
})
}
return paths
}
function transpileText(text, filename) {
const res = ts.transpileModule(text, {
compilerOptions: {
target: ts.ScriptTarget.ES2017,
module: ts.ModuleKind.AMD,
inlineSourceMap: false
},
reportDiagnostics: false
})
return res.outputText
}
const server = express()
server.get('/listsongs', (req, res) => {
const songs = listFilesRec()
res.send(songs)
})
server.post('/writetextfile', (req, res) => {
const filename = path.join(__dirname, 'static', req.query.path)
let body = []
req
.on('data', chunk => body.push(chunk))
.on('end', () => {
body = Buffer.concat(body).toString()
fs.writeFileSync(filename, body)
res.send('success')
})
})
server.use(express.static('static'))
server.use((req, res) => {
const file = path.join(__dirname, 'static', req.path + '.ts')
if (fs.existsSync(file)) {
const tsdata = fs.readFileSync(file, 'utf-8')
const jsdata = transpileText(tsdata, file)
res.send(jsdata)
} else if(req.path.length <= 1) {
res.redirect('/web/list-of-songs/')
} else {
res.status(404).send('not_found')
}
})
server.listen('80')