Skip to content

Commit ff2fa01

Browse files
authored
Merge pull request #145 from westy92/master
Handle spawn errors gracefully.
2 parents 3bf4c68 + b087cde commit ff2fa01

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

lib/pdf.js

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ PDF.prototype.toFile = function PdfToFile (filename, callback) {
8484
}
8585

8686
PDF.prototype.exec = function PdfExec (callback) {
87+
var callbacked = false
8788
var child = childprocess.spawn(this.options.phantomPath, [].concat(this.options.phantomArgs, [this.script]))
8889
var stdout = []
8990
var stderr = []
@@ -105,20 +106,29 @@ PDF.prototype.exec = function PdfExec (callback) {
105106
return child.kill()
106107
})
107108

108-
child.on('exit', function (code) {
109+
function exit (err, data) {
110+
if (callbacked) return
111+
callbacked = true
109112
clearTimeout(timeout)
113+
if (err) return callback(err)
114+
return callback(null, data)
115+
}
116+
117+
child.on('error', exit)
118+
119+
child.on('exit', function (code) {
110120
if (code || stderr.length) {
111121
var err = new Error(Buffer.concat(stderr).toString() || 'html-pdf: Unknown Error')
112-
return callback(err)
122+
return exit(err)
113123
} else {
114124
try {
115125
var buff = Buffer.concat(stdout).toString()
116126
var data = (buff) != null ? buff.trim() : undefined
117127
data = JSON.parse(data)
118128
} catch (err) {
119-
return callback(err)
129+
return exit(err)
120130
}
121-
return callback(null, data)
131+
return exit(null, data)
122132
}
123133
})
124134

test/index.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,24 @@ test('allows custom html and css', function (t) {
114114
})
115115
})
116116

117+
test('allows invalid phantomPath', function (t) {
118+
t.plan(3)
119+
120+
var filename = path.join(__dirname, 'invalid-phantomPath.pdf')
121+
122+
var options = {
123+
phantomPath: '/bad/path/to/phantom'
124+
}
125+
126+
pdf
127+
.create(html, options)
128+
.toFile(filename, function (error, pdf) {
129+
t.assert(error instanceof Error, 'Returns an error')
130+
t.equal(error.code, 'ENOENT', 'Error code is ENOENT')
131+
t.error(pdf, 'PDF does not exist')
132+
})
133+
})
134+
117135
test('allows custom page and footer options', function (t) {
118136
t.plan(3)
119137

0 commit comments

Comments
 (0)