| 6 | const path = require('path'); |
| 7 | |
| 8 | function createServer() { |
| 9 | const demoPath = 'test/data/demo'; |
| 10 | |
| 11 | const server = http.createServer(function(req, res) { |
| 12 | try { |
| 13 | if (req.method === 'GET') { |
| 14 | // Ignore query parameters which are used to inject application keys |
| 15 | const urlParts = req.url.split('?'); |
| 16 | if (urlParts[0] === '/') { |
| 17 | req.url = '/index.html'; |
| 18 | } |
| 19 | |
| 20 | if (!fs.existsSync(demoPath + req.url)) { |
| 21 | res.writeHead(404); |
| 22 | res.end(); |
| 23 | return; |
| 24 | } |
| 25 | |
| 26 | const data = fs.readFileSync(demoPath + req.url); |
| 27 | |
| 28 | res.writeHead(200, { |
| 29 | 'Content-Length': data.length, |
| 30 | 'Content-Type': path.extname(req.url) === '.html' ? 'text/html' : 'application/javascript' |
| 31 | }); |
| 32 | res.end(data); |
| 33 | } else { |
| 34 | throw new Error('Unable to handle post requests.'); |
| 35 | } |
| 36 | } catch (err) { |
| 37 | console.error('An error occured handling request.', err); |
| 38 | res.writeHead(404); |
| 39 | res.end('bad request.'); |
| 40 | } |
| 41 | }); |
| 42 | |
| 43 | portfinder.getPort(function(err, port) { |
| 44 | if (err) { |
| 45 | server.port = 50005; |
| 46 | } else { |
| 47 | server.port = port; |
| 48 | } |
| 49 | server.listen(server.port); |
| 50 | }); |
| 51 | |
| 52 | return new Promise(function(resolve) { |
| 53 | server.on('listening', function() { |
| 54 | resolve(server); |
| 55 | }); |
| 56 | }); |
| 57 | } |
| 58 | |
| 59 | module.exports = createServer; |