-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp-server.js
68 lines (51 loc) · 1.78 KB
/
http-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
const { createServer } = require('http');
const path = require('path');
const { spawn } = require('child_process');
const { cpus } = require('os');
const MAX_PARALLEL_PROCESS = cpus().length <= 1 ? 1 : cpus().length / 2
let runningProcess = []
async function runBigProcessInQueue() {
if (runningProcess.length >= MAX_PARALLEL_PROCESS) {
console.log('Queue is full, waiting some process finish...');
const firstResolvedPromise = await Promise.race(runningProcess)
runningProcess = runningProcess.filter((p) => p !== firstResolvedPromise)
return runBigProcessInQueue()
}
console.log('Running process...');
const promise = runBigProcess()
runningProcess.push(promise)
function removePromise() {
console.log('Promise finish, removing from queue...');
runningProcess = runningProcess.filter((p) => p !== promise)
}
let result;
try {
result = await promise;
} catch (error) {
throw error
} finally {
removePromise()
}
return result
}
async function runBigProcess() {
return new Promise((resolve, reject) => {
const subProcess = spawn('node', [
path.resolve(__dirname, 'sub-process.js')
])
subProcess.stdout.on('data', (chunk) => {})
subProcess.stderr.on('data', (chunk) => console.log(chunk.toString()))
subProcess.on('error', reject)
subProcess.on('close', () => {
resolve('resolved')
})
})
}
createServer(async (req, res) => {
if (req.url === '/queue') {
const started = new Date()
await runBigProcessInQueue()
console.log(`this process took: ${new Date() - started}ms`);
}
res.end('ok')
}).listen(5050, () => console.log('server up'));