diff --git a/src/stdlib/child-process.coffee b/src/stdlib/child-process.coffee new file mode 100644 index 000000000..511e92c0b --- /dev/null +++ b/src/stdlib/child-process.coffee @@ -0,0 +1,50 @@ +# node.js child-process +# http://nodejs.org/docs/v0.6.3/api/child_processes.html + +_ = require 'underscore' + +module.exports = + exec: (command, options, callback) -> + callback = options if _.isFunction options + + # make a task + task = OSX.NSTask.alloc.init + + # 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() \ No newline at end of file diff --git a/test/child_process_test.coffee b/test/child_process_test.coffee new file mode 100644 index 000000000..de556290f --- /dev/null +++ b/test/child_process_test.coffee @@ -0,0 +1,14 @@ +assert = require 'assert' +ChildProcess = require 'child-process' + +ChildProcess.exec "echo hello", (error, stdout, stderr) -> + assert.equal "hello", stdout.trim() + assert.equal null, error + +ChildProcess.exec "derp hello", (error, stdout, stderr) -> + assert.equal "/bin/bash: derp: command not found", stderr.trim() + assert.ok error + assert.equal 127, error.code + +ChildProcess.exec "coffee -e 'console.log 1+1'", (error, stdout, stderr) -> + assert.equal "2", stdout.trim() \ No newline at end of file