Add ChildProcess.exec(cmd, [options])

Uses promises for failure and success states. Takes optional stderr and stdout callbacks for incremental reading.
This commit is contained in:
Corey Johnson
2012-07-10 15:07:28 -07:00
parent 5b2781aec2
commit 2afec5cf53
3 changed files with 142 additions and 43 deletions

View File

@@ -1,50 +1,20 @@
# node.js child-process
# http://nodejs.org/docs/v0.6.3/api/child_processes.html
$ = require 'jquery'
_ = require 'underscore'
module.exports =
exec: (command, options, callback) ->
callback = options if _.isFunction options
class ChildProccess
@exec: (command, options={}) ->
deferred = $.Deferred()
$native.exec command, options, (exitStatus, stdout, stdin) ->
if error != 0
error = new Error("Exec failed (#{exitStatus}) command '#{command}'")
error.exitStatus = exitStatus
deferred.reject(error)
else
deferred.resolve(stdout, stdin)
# make a task
task = OSX.NSTask.alloc.init
deferred
# try to use their login shell
task.setLaunchPath "/bin/bash"
# set stdin to /dev/null
task.setStandardInput OSX.NSFileHandle.fileHandleWithNullDevice
# -l = login shell, -c = command
args = ["-l", "-c", command]
task.setArguments args
# setup stdout and stderr
task.setStandardOutput stdout = OSX.NSPipe.pipe
task.setStandardError stderr = OSX.NSPipe.pipe
stdoutHandle = stdout.fileHandleForReading
stderrHandle = stderr.fileHandleForReading
# begin
task.launch
# read pipes
err = @readHandle stderrHandle
out = @readHandle stdoutHandle
# check for a dirty exit
if not task.isRunning
code = task.terminationStatus
if code > 0
error = new Error
error.code = code
# call callback
callback error, out, err
readHandle: (handle) ->
OSX.NSString.
alloc.
initWithData_encoding(handle.readDataToEndOfFile, OSX.NSUTF8StringEncoding).
toString()