screenshot.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env node
  2. process.env.DEBUG = 'app:*';
  3. const debug = require('debug')('app:screenshot');
  4. const MAX_POOL_SIZE = require('os').cpus().length;
  5. const Nightmare = require('nightmare');
  6. const _ = require('lodash');
  7. const commander = require('commander');
  8. const connect = require('connect');
  9. const getPort = require('get-port');
  10. const http = require('http');
  11. const path = require('path');
  12. const basename = path.basename;
  13. const extname = path.extname;
  14. const join = path.join;
  15. const queue = require('d3-queue').queue;
  16. const serveStatic = require('serve-static');
  17. const shelljs = require('shelljs');
  18. const ls = shelljs.ls;
  19. const mkdir = shelljs.mkdir;
  20. const pkg = require('../package.json');
  21. commander
  22. .version(pkg.version)
  23. .option('-p, --port <port>', 'specify a port number to run on', parseInt)
  24. .option('-n, --name <name>', 'specify the name for demos')
  25. .parse(process.argv);
  26. // assets
  27. const src = join(process.cwd(), './demos');
  28. const dest = join(process.cwd(), './demos/assets/screenshots');
  29. mkdir('-p', dest);
  30. const app = connect();
  31. app.use('/', serveStatic(process.cwd()));
  32. const DELAY = 10000;
  33. getPort().then(port => {
  34. http.createServer(app).listen(port);
  35. const url = 'http://127.0.0.1:' + port;
  36. debug('server is ready on port ' + port + '! url: ' + url);
  37. const q = queue(MAX_POOL_SIZE > 2 ? MAX_POOL_SIZE - 1 : MAX_POOL_SIZE);
  38. const files = ls(src).filter(filename => (extname(filename) === '.html'));
  39. files.forEach(filename => {
  40. const name = basename(filename, '.html');
  41. if (_.isString(commander.name) && filename.indexOf(commander.name) === -1) {
  42. debug(`>>>>>>>>> skipping because filename not matched: ${name}`);
  43. return;
  44. }
  45. q.defer(callback => {
  46. const t0 = Date.now();
  47. const nightmare = Nightmare({
  48. gotoTimeout: 600000,
  49. show: false
  50. });
  51. const url = `http://127.0.0.1:${port}/demos/${name}.html`;
  52. const target = join(dest, `./${name}.png`);
  53. nightmare.viewport(800, 450) // 16 x 9
  54. .goto(url)
  55. .wait(DELAY)
  56. .screenshot(target, () => {
  57. debug(name + ' took ' + (Date.now() - t0) + ' to take a screenshot.');
  58. callback(null);
  59. })
  60. .end()
  61. .catch(e => {
  62. debug(url);
  63. debug(target);
  64. debug(name + ' failed to take a screenshot: ' + e);
  65. });
  66. });
  67. });
  68. q.awaitAll(error => {
  69. if (error) {
  70. debug(error);
  71. process.exit(1);
  72. }
  73. debug('screenshots are all captured!');
  74. process.exit();
  75. });
  76. });