-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
66 lines (56 loc) · 2 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
// // source: https://github.com/thlorenz/dev-null
// var util = require('util')
// , stream = require('stream')
// , Writable = stream.Writable
// , setImmediate = setImmediate || function (fn) { setTimeout(fn, 0) }
// util.inherits(DevNull, Writable)
// function DevNull (opts) {
// if (!(this instanceof DevNull)) return new DevNull(opts)
// opts = opts || {}
// Writable.call(this, opts)
// }
// DevNull.prototype._write = function (chunk, encoding, cb) {
// setImmediate(cb)
// }
// // -- DevNull End --
const http = require('http')
const server = http.createServer()
const fs = require('fs')
const path = require('path')
server.on('request', async (req, res) => {
console.log('{SERVER} Incoming request', req.url, new Date())
try {
req.socket.on('end', function () {
console.log('{SERVER} SOCKET END: other end of the socket sends a FIN packet')
})
req.socket.on('timeout', function () {
console.log('{SERVER} SOCKET TIMEOUT')
})
req.socket.on('error', function (error) {
console.log('{SERVER} SOCKET ERROR: ' + JSON.stringify(error))
})
req.socket.on('close', function (had_error) {
console.log('{SERVER} SOCKET CLOSED. IT WAS ERROR: ' + had_error)
})
// Write to /dev/null instead
// const writeStream = DevNull()
const writeStream = fs.createWriteStream(path.join(__dirname, 'temp-upload'))
const promise = new Promise((resolve, reject) => {
req.on('end', resolve)
req.on('error', reject)
})
req.pipe(writeStream)
await promise
res.end('OK')
console.log('{SERVER} Request ended', req.url, new Date())
} catch (err) {
res.writeHead(500)
res.end(err.message)
}
})
// NOTE: enable this on node 12.19.0 and the client request will run successfully
// server.on('timeout', () => {
// console.log('{SERVER} timeout')
// })
console.log(`Running on node ${process.version}`)
server.listen(8081).on('listening', () => { console.log('{SERVER} Listening on port', server.address().port) })