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 |
|
22 | commander
|
23 | .version(pkg.version)
|
24 | .option('-p, --port <port>', 'specify a port number to run on', parseInt)
|
25 | .option('-f, --filter <filter>', 'specify the name filter for demos')
|
26 | .parse(process.argv);
|
27 |
|
28 |
|
29 | const src = join(process.cwd(), './demos');
|
30 | const dest = join(process.cwd(), './demos/assets/screenshots');
|
31 | mkdir('-p', dest);
|
32 |
|
33 | const app = connect();
|
34 | app.use('/', serveStatic(process.cwd()));
|
35 |
|
36 | const DELAY = 6000;
|
37 |
|
38 | getPort().then(port => {
|
39 | http.createServer(app).listen(port);
|
40 | const url = 'http://127.0.0.1:' + port;
|
41 | debug('server is ready on port ' + port + '! url: ' + url);
|
42 |
|
43 | const q = queue(MAX_POOL_SIZE > 2 ? MAX_POOL_SIZE - 1 : MAX_POOL_SIZE);
|
44 | const files = ls(src).filter(filename => (extname(filename) === '.html'));
|
45 | files.forEach(filename => {
|
46 | const name = basename(filename, '.html');
|
47 | if (_.isString(commander.filter) && filename.indexOf(commander.filter) === -1) {
|
48 | debug(`>>>>>>>>> skipping because filename not matched: ${name}`);
|
49 | return;
|
50 | }
|
51 | q.defer(callback => {
|
52 | const t0 = Date.now();
|
53 | const nightmare = Nightmare({
|
54 | gotoTimeout: 600000,
|
55 | show: false
|
56 | });
|
57 | const url = `http://127.0.0.1:${port}/demos/${name}.html`;
|
58 | const target = join(dest, `./${name}.png`);
|
59 | nightmare.viewport(800, 450)
|
60 | .goto(url)
|
61 | .wait(DELAY)
|
62 | .screenshot(target, () => {
|
63 | debug(name + ' took ' + (Date.now() - t0) + ' to take a screenshot.');
|
64 | callback(null);
|
65 | })
|
66 | .end()
|
67 | .catch(e => {
|
68 | debug(url);
|
69 | debug(target);
|
70 | debug(name + ' failed to take a screenshot: ' + e);
|
71 | });
|
72 | });
|
73 | });
|
74 | q.awaitAll(error => {
|
75 | if (error) {
|
76 | debug(error);
|
77 | process.exit(1);
|
78 | }
|
79 | debug('screenshots are all captured!');
|
80 | process.exit();
|
81 | });
|
82 | });
|