forked from amir20/phantomjs-node
-
Notifications
You must be signed in to change notification settings - Fork 2
/
phantom.coffee
66 lines (49 loc) · 1.55 KB
/
phantom.coffee
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
dnode = require 'dnode'
express = require 'express'
child = require 'child_process'
phanta = []
startPhantomProcess = (port, args) ->
ps = child.spawn 'phantomjs', args.concat [
# '-g'
# 'ApplePersistence'
# '-bool'
# 'no'
__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/
return if data.toString('utf8').match /ApplePersistence=YES/
console.warn "phantom stderr: #{data}"
ps
process.on 'exit', ->
phantom.exit() for phantom in phanta
# 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, args...) ->
page._evaluate.apply page, [fn.toString(), args...]
cb page
module.exports =
create: (args..., cb) ->
app = express()
app.use express.static __dirname
appServer = app.listen()
server = dnode()
phantom = null
ps = startPhantomProcess appServer.address().port, args
ps.on 'exit', (code) ->
appServer.close()
phanta = (p for p in phanta when p isnt phantom)
io =
log: null,
'client store expiration': 0
server.listen appServer, {io}, (obj, conn) ->
phantom = conn.remote
wrap phantom
phanta.push phantom
cb? phantom