1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | const path = require('path')
|
20 |
|
21 | let express
|
22 | let workerpool
|
23 | try {
|
24 | express = require('express')
|
25 | workerpool = require('workerpool')
|
26 | } catch (err) {
|
27 | console.log('Error: To run this example, install express and workerpool first via:\n\n' +
|
28 | ' npm install express workerpool\n')
|
29 | process.exit()
|
30 | }
|
31 |
|
32 | const app = express()
|
33 | const pool = workerpool.pool(path.join(__dirname, '/math_worker.js'))
|
34 |
|
35 | const TIMEOUT = 10000
|
36 |
|
37 |
|
38 |
|
39 |
|
40 | app.get('/mathjs', function (req, res) {
|
41 | const expr = req.query.expr
|
42 | if (expr === undefined) {
|
43 | return res.status(400).send('Error: Required query parameter "expr" missing in url.')
|
44 | }
|
45 |
|
46 | pool.exec('evaluate', [expr])
|
47 | .timeout(TIMEOUT)
|
48 | .then(function (result) {
|
49 | res.send(result)
|
50 | })
|
51 | .catch(function (err) {
|
52 | res.status(400).send(formatError(err))
|
53 | })
|
54 | })
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 | function formatError (err) {
|
62 | if (err instanceof workerpool.Promise.TimeoutError) {
|
63 | return 'TimeoutError: Evaluation exceeded maximum duration of ' + TIMEOUT / 1000 + ' seconds'
|
64 | } else {
|
65 | return err.toString()
|
66 | }
|
67 | }
|
68 |
|
69 |
|
70 | process.on('uncaughtException', function (err) {
|
71 | console.log('Caught exception: ' + err)
|
72 | console.trace()
|
73 | })
|
74 |
|
75 |
|
76 | const PORT = process.env.PORT || 8080
|
77 | app.listen(PORT, function () {
|
78 | console.log('Listening at http://localhost:' + PORT)
|
79 | console.log('Example request:\n GET http://localhost:' + PORT + '/mathjs?expr=sqrt(16)')
|
80 | })
|