-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfdp_server.js
99 lines (87 loc) · 2.66 KB
/
fdp_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
88
89
90
91
92
93
94
95
96
97
98
99
const http = require('http')
const formidable = require('formidable')
const fs = require('fs')
const mkdirp = require('mkdirp')
const yauzl = require("yauzl")
const path = require('path')
const rimraf = require('rimraf')
const port = parseInt(process.argv[2]) || 2333
const errorHandler = (res, err) => {
console.log((new Date()).toGMTString(), '[ERROR]', err.toString())
res.writeHead(500, {
'Content-Type': 'text/plain'
})
res.end(err.toString())
}
const fileHandler = (res, filePath, to) => {
yauzl.open(path.normalize(filePath), { lazyEntries: true }, (err, zipfile) => {
if (err) {
throw err
}
zipfile.on('close', () => {
console.log((new Date()).toGMTString(), '[INFO]', 'Unzip completed, rmoving zip file.')
fs.unlink(filePath, err => {
if (err) return errorHandler(res, err)
console.log((new Date()).toGMTString(), '[WARNING]', 'Cannot remove uploaded file at:', filePath)
res.writeHead(200, {
'Content-Type': 'text/plain'
})
res.end('0')
})
})
unzipFile(zipfile, to)
})
}
const unzipFile = (zipfile, to) => {
zipfile.readEntry()
zipfile.on('entry', entry => {
let entryPath = path.resolve(to, entry.fileName)
mkdirp(path.dirname(entryPath), 0777, err => {
if (err) {
throw err
}
zipfile.openReadStream(entry, (err, readStream) => {
if (err) {
throw err
}
readStream.on('end', () => {
zipfile.readEntry()
})
let writeStream = fs.createWriteStream(entryPath)
readStream.pipe(writeStream)
})
})
})
}
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, {
'Content-Type': 'text/html'
})
res.end('Deploy server is ready')
} else if (req.url === '/deploy' && req.method.toLowerCase() === 'post') {
let form = new formidable.IncomingForm()
form.on('error', err => {
console.log((new Date()).toGMTString(), '[FATAL]', 'Error occurs during transfer process:', err.toString())
})
form.parse(req, (err, fields, files) => {
if (err) {
errorHandler(res, err)
} else {
let to = path.dirname(fields.to)
console.log((new Date()).toGMTString(), '[INFO]', 'Zip file is uploaded and ready for deployment')
rimraf(to, () => {
console.log((new Date()).toGMTString(), '[INFO]', 'Directory', to, 'is clean now')
try {
fileHandler(res, files.file.path, to)
} catch (err) {
errorHandler(res, err)
}
})
}
})
}
})
server.listen(port, () => {
console.log('Deploy server listen on:', port)
})