1 | 'use strict';
|
2 | var fs = require('fs');
|
3 | var path = require('path');
|
4 | var tmp = require('tmp');
|
5 | var phantom = require('phantom');
|
6 |
|
7 | exports.read = function(cb, file) {
|
8 | var p = path.join(__dirname, 'data', file || 'demo.js');
|
9 |
|
10 | fs.readFile(p, {
|
11 | encoding: 'utf-8'
|
12 | }, function(err, data) {
|
13 | if(err) {
|
14 | return console.error(err);
|
15 | }
|
16 |
|
17 | cb(data);
|
18 | });
|
19 | };
|
20 |
|
21 | exports.runInPhantom = function(code, consoleCb) {
|
22 | tmp.file(function(err, path, fd) {
|
23 | if(err) {
|
24 | return console.error(err);
|
25 | }
|
26 |
|
27 | fs.writeFile(path, code, function(err) {
|
28 | if(err) {
|
29 | return console.error(err);
|
30 | }
|
31 |
|
32 | phantom.create(function(ph) {
|
33 | ph.createPage(function(page) {
|
34 | page.onConsoleMessage(consoleCb);
|
35 |
|
36 | page.onError(function(msg, trace) {
|
37 | console.error(msg, trace);
|
38 | });
|
39 |
|
40 | page.injectJs(path, function(ok) {
|
41 | if(!ok) {
|
42 | return console.error('Failed to inject js');
|
43 | }
|
44 |
|
45 | ph.exit();
|
46 | });
|
47 | });
|
48 | });
|
49 | });
|
50 | });
|
51 | };
|