spawnとexecの違いがわからんのでちょっと調べた。
Difference between spawn and exec of Node.js child_process
spawnはストリームをexecはバッファーを返す
で、Node.jsのドキュメントを読んでて
spawnをつかった 'ps ax | grep ssh' の例が書いてあったので、これをcoffeescriptで書いた。
ターミナルで普通に動くのでvowsでテストしたら、callbackが返ってくる前に変なオブジェクトが返ってきてなんじゃこりゃ?と。
coffeescriptをjavascriptにコンパイルして読んだら、変なとこにreturnが挿入されてたのであちこちにreturnを入れて勝手にreturnされないようにした。
psax.coffee
util = require('util')
spawn = require('child_process').spawn
psax = (callback) ->
ps = spawn('ps', ['ax'])
grep = spawn('grep', ['ssh'])
d = ""
ps.stdout.on 'data', (data) -> grep.stdin.write(data); return
ps.stderr.on 'data', (data) -> console.log('ps stderr: ' + data); return
ps.on 'exit', (code) ->
console.log('ps process exited with code ' + code) if code isnt 0
grep.stdin.end(); return
grep.stdout.on 'data', (data) -> d += data; return
grep.stderr.on 'data', (data) -> console.log('grep stderr: ' + data); return
grep.on 'exit', (code) ->
console.log('grep process exited with code ' + code) if code isnt 0
return
grep.stdout.on 'end', ->
callback(null, d); return
return
exports.psax = psax
returnを入れて最後に評価した式がかえらなくてしなくていいような記法は用意されてないんだろうか?
>>なんかモナドっぽくて素敵じゃないか。
vowsのテスト。宣言(文字列)の書き方のお作法がまだよくわかってない。should beとかshoud haveはわかるんだけど、whenとかAfterとか使い分けってどうなってんの?
そういうお作法が書いてあるサイトないかなぁ。
vows = require('vows')
assert = require('assert')
sp = require('./psax')
psax = sp.psax
vows.describe('Psax').addBatch({
'A psax': {
topic: -> psax
'should be a function': (px) ->
assert.equal(typeof px, "function")
'After psax function called': {
topic: (psax) -> psax(this.callback)
'callback should return a result': (err,result) ->
assert.isString(result)
}
}
}).export(module)