UNPKG

2.52 kBJavaScriptView Raw
1#!/usr/bin/env node
2process.env.DEBUG = 'app:*';
3const debug = require('debug')('app:screenshot');
4const MAX_POOL_SIZE = require('os').cpus().length;
5const Nightmare = require('nightmare');
6const _ = require('lodash');
7const commander = require('commander');
8const connect = require('connect');
9const getPort = require('get-port');
10const http = require('http');
11const path = require('path');
12const basename = path.basename;
13const extname = path.extname;
14const join = path.join;
15const queue = require('d3-queue').queue;
16const serveStatic = require('serve-static');
17const shelljs = require('shelljs');
18const ls = shelljs.ls;
19const mkdir = shelljs.mkdir;
20const pkg = require('../package.json');
21
22commander
23 .version(pkg.version)
24 .option('-p, --port <port>', 'specify a port number to run on', parseInt)
25 .option('-n, --name <name>', 'specify the name for demos')
26 .parse(process.argv);
27
28// assets
29const src = join(process.cwd(), './demos');
30const dest = join(process.cwd(), './demos/assets/screenshots');
31mkdir('-p', dest);
32
33const app = connect();
34app.use('/', serveStatic(process.cwd()));
35
36const DELAY = 10000;
37
38getPort().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.name) && filename.indexOf(commander.name) === -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) // 16 x 9
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});