forked from amir20/phantomjs-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphantom.coffee
More file actions
85 lines (63 loc) · 2.48 KB
/
phantom.coffee
File metadata and controls
85 lines (63 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
dnode = require 'dnode'
http = require 'http'
shoe = require 'shoe'
child = require 'child_process'
# the list of phantomjs RPC wrapper
phanta = []
# @Description: starts and returns a child process running phantomjs
# @param: port:int
# @args: args:object
# @return: ps:object
startPhantomProcess = (binary, port, args) ->
ps = child.spawn binary, args.concat [__dirname+'/shim.js', port]
ps.stdout.on 'data', (data) -> console.log "phantom stdout: #{data}"
ps.stderr.on 'data', (data) ->
return if data.toString('utf8').match /No such method.*socketSentData/ #Stupid, stupid QTWebKit
console.warn "phantom stderr: #{data}"
ps.on 'exit', (code, signal) ->
console.assert not signal?, "signal killed phantomjs: #{signal}"
console.assert code is 0, "abnormal phantomjs exit code: #{code}"
ps
# @Description: kills off all phantom processes within spawned by this parent process when it is exits
process.on 'exit', ->
phantom.exit() for phantom in phanta
# @Description: We need this because dnode does magic clever stuff with functions, but we want the function to make it intact to phantom
wrap = (ph) ->
ph._createPage = ph.createPage
ph.createPage = (cb) ->
ph._createPage (page) ->
page._evaluate = page.evaluate
page.evaluate = (fn, cb, args...) -> page._evaluate.apply(page, [fn.toString(), cb].concat(args))
cb page
module.exports =
create: ->
args = []
options = {}
for arg in arguments
switch typeof arg
when 'function' then cb = arg
when 'string' then args.push arg
when 'object' then options = arg
options.binary ?= 'phantomjs'
options.port ?= 12300
phantom = null
httpServer = http.createServer()
httpServer.listen options.port
httpServer.on 'listening', () ->
ps = startPhantomProcess options.binary, options.port, args
# @Description: when the background phantomjs child process exits or crashes
# removes the current dNode phantomjs RPC wrapper from the list of phantomjs RPC wrapper
ps.on 'exit', (code) ->
httpServer.close()
if phantom
phantom && phantom.onExit && phantom.onExit() # calls the onExit method if it exist
phanta = (p for p in phanta when p isnt phantom)
sock = shoe (stream) ->
d = dnode()
d.on 'remote', (phantom) ->
wrap phantom
phanta.push phantom
cb? phantom
d.pipe stream
stream.pipe d
sock.install httpServer, '/dnode'