launchTestController.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * Controller for the test launching page (the waiting page, after the user submited a test on the index page)
  3. */
  4. var async = require('async');
  5. var fs = require ('fs');
  6. var launchTestController = function(req, res, testQueue) {
  7. 'use strict';
  8. // Generate test id
  9. var testId = (Date.now()*1000 + Math.round(Math.random()*1000)).toString(36);
  10. var resultsPath = 'results/' + testId;
  11. var phantomasResultsPath = resultsPath + '/results.json';
  12. var url = req.body.url;
  13. if (url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0) {
  14. url = 'http://' + url;
  15. }
  16. var options = {};
  17. if (req.body.timeout) {
  18. options.timeout = req.body.timeout;
  19. }
  20. async.waterfall([
  21. function htmlTemplate(callback) {
  22. fs.readFile('./app/node_views/launchTest.html', {encoding: 'utf8'}, callback);
  23. },
  24. function sendResponse(html, callback) {
  25. html = html.replace('%%TEST_URL%%', url);
  26. html = html.replace('%%TEST_ID%%', testId);
  27. res.setHeader('Content-Type', 'text/html');
  28. res.send(html);
  29. callback();
  30. },
  31. function createFolder(callback) {
  32. // Create results folder
  33. fs.mkdir(resultsPath, callback);
  34. },
  35. function executePhantomas(callback) {
  36. console.log('Adding test ' + testId + ' on ' + url + ' to the queue');
  37. var task = {
  38. testId: testId,
  39. url: url,
  40. options: options
  41. };
  42. testQueue.push(task, callback);
  43. },
  44. function writeResults(json, resultsObject, callback) {
  45. console.log('Saving Phantomas results file to ' + phantomasResultsPath);
  46. fs.writeFile(phantomasResultsPath, JSON.stringify(json, null, 4), callback);
  47. }
  48. ], function(err) {
  49. if (err) {
  50. console.log('An error occured while launching the phantomas test : ', err);
  51. fs.writeFile(phantomasResultsPath, JSON.stringify({url: url, error: err}, null, 4), function(err) {
  52. if (err) {
  53. console.log('Could not even write an error message on file ' + phantomasResultsPath);
  54. console.log(err);
  55. }
  56. });
  57. } else {
  58. testQueue.testComplete(testId);
  59. }
  60. });
  61. };
  62. module.exports = launchTestController;