Permalink
Browse files

handle 'exit' AND 'close' events on child process

  • Loading branch information...
1 parent 15ec26f commit d1be63c9ece41d4357f7dfc5e83aa386c50e7605 @rvagg committed Dec 13, 2012
Showing with 30 additions and 15 deletions.
  1. +21 −12 index.js
  2. +2 −2 package.json
  3. +7 −1 test/test.js
View
@@ -9,6 +9,20 @@ var spawn = require('child_process').spawn
, fromString = function(exec, code, callback) {
var stdout = []
, stderr = ''
+ , ec = 0
+ , exitClose = function () {
+ if (++ec < 2) return
+
+ var buf = new Buffer(stdout.reduce(function (p, c) { return p + c.length }, 0))
+ , i = 0
+
+ stdout.forEach(function(s) {
+ s.copy(buf, i, 0, s.length)
+ i += s.length
+ })
+
+ callback(null, buf)
+ }
exec.stdout.on('data', function(data) {
stdout.push(data)
@@ -19,18 +33,13 @@ var spawn = require('child_process').spawn
})
exec.on('exit', function (code) {
- if (code !== 0) return callback('Error: ' + stderr)
-
- var buf = new Buffer(stdout.reduce(function (p, c) { return p + c.length }, 0))
- , i = 0
-
- stdout.forEach(function(s) {
- s.copy(buf, i, 0, s.length)
- i += s.length
- })
-
- callback(null, buf)
+ if (code !== 0) {
+ ec = -1
+ return callback('Error: ' + stderr)
+ }
+ exitClose()
})
+ exec.on('close', exitClose)
exec.stdin.write(code)
exec.stdin.end()
@@ -89,4 +98,4 @@ var spawn = require('child_process').spawn
: fromStream(exec)
}
-module.exports = pygmentize
+module.exports = pygmentize
View
@@ -1,6 +1,6 @@
{
"name": "pygmentize-bundled"
- , "version": "1.0.0"
+ , "version": "1.0.1"
, "description": "A simple wrapper around Python's Pygments code formatter, with Pygments bundled"
, "main": "index.js"
, "scripts": {
@@ -25,4 +25,4 @@
, "devDependencies": {
"stream-equal": ">= 0.0.1"
}
-}
+}
View
@@ -2,6 +2,7 @@ var assert = require('assert')
, pygments = require('../')
, fs = require('fs')
, streamEqual = require('stream-equal')
+ , timeout
, cases = [
{
@@ -23,6 +24,7 @@ cases.forEach(function (c) {
assert.equal(err, null)
result = result.toString().replace(/\n/g, '')
assert.equal(result, c.output)
+ clearTimeout(timeout)
})
})
@@ -39,4 +41,8 @@ fileOut.on("close", function() {
if(err) throw err
assert.equal(equal, true)
})
-})
+})
+
+timeout = setTimeout(function () {
+ assert(false, 'Callback not called!')
+}, 500)

0 comments on commit d1be63c

Please sign in to comment.