1 // Copyright 2013 The Obvious Corporation.
4 * @fileoverview Helpers made available via require('phantomjs') once package is
9 var path = require('path')
10 var spawn = require('child_process').spawn
11 var Promise = require('es6-promise').Promise
15 * Where the phantom binary can be found.
19 var location = require('./location')
20 exports.path = path.resolve(__dirname, location.location)
21 exports.platform = location.platform
22 exports.arch = location.arch
24 // Must be running inside install script.
30 * The version of phantomjs installed by this package.
33 exports.version = '2.1.1'
37 * Returns a clean path that helps avoid `which` finding bin files installed
38 * by NPM for this repo.
39 * @param {string} path
42 exports.cleanPath = function (path) {
44 .replace(/:[^:]*node_modules[^:]*/g, '')
45 .replace(/(^|:)\.\/bin(\:|$)/g, ':')
51 // Make sure the binary is executable. For some reason doing this inside
52 // install does not work correctly, likely due to some NPM step.
55 // avoid touching the binary if it's already got the correct permissions
56 var st = fs.statSync(exports.path)
57 var mode = st.mode | parseInt('0555', 8)
58 if (mode !== st.mode) {
59 fs.chmodSync(exports.path, mode)
62 // Just ignore error if we don't have permission.
63 // We did our best. Likely because phantomjs was already installed.
68 * Executes a script or just runs PhantomJS
70 exports.exec = function () {
71 var args = Array.prototype.slice.call(arguments)
72 return spawn(exports.path, args)
76 * Runs PhantomJS with provided options
78 * // handy with WebDriver
79 * phantomjs.run('--webdriver=4444').then(program => {
83 * @returns {Promise} the process of PhantomJS
85 exports.run = function () {
87 return new Promise(function (resolve, reject) {
89 var program = exports.exec.apply(null, args)
92 program.stdout.on('data', function () {
93 // This detects PhantomJS instance get ready.
98 program.stderr.on('data', function (data) {
99 stderr = stderr + data.toString('utf8')
101 program.on('error', function (err) {
106 program.on('exit', function (code) {
110 // PhantomJS doesn't use exit codes correctly :(
111 if (stderr.indexOf('Error:') == 0) {
112 reject(new Error(stderr))
117 reject(new Error('Exit code: ' + code))