server.js (1985B)
1 /** 2 * This example demonstrates how to run math.js in a child process with limited 3 * execution time. 4 * 5 * Prerequisites: 6 * 7 * npm install express workerpool 8 * 9 * Start the server: 10 * 11 * node ./server.js 12 * 13 * Make a request to the server: 14 * 15 * GET http://localhost:8080/mathjs?expr=sqrt(16) 16 * 17 * Note that the query parameter `expr` should be properly url encoded. 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 // milliseconds 36 37 /** 38 * GET /mathjs?expr=... 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 * Format error messages as string 58 * @param {Error} err 59 * @return {String} message 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 // handle uncaught exceptions so the application cannot crash 70 process.on('uncaughtException', function (err) { 71 console.log('Caught exception: ' + err) 72 console.trace() 73 }) 74 75 // start the server 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 })