2012年12月21日 星期五

使用Node接收Shell pipe資料做處理

撰寫command line程式時候,常常需要處理pipe的問題
而Node.js具備命令列執行的特色,可以作為腳本語言的撰寫工具
但是,如何在Node.js處理Shell pipe過來的資料呢?
答案是使用process.openStdin()...
下面是範例片段:

程式碼:[test.js]
#!/usr/bin/env node
var buffer = '';
var stdin = process.openStdin();
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
    buffer += chunk;
});
stdin.on('end', function () {
  console.log(buffer);
});

修改執行權限:

# chmod u+x test.js

測試
# echo HELLO | ./test.js

結果... 自己試試 :D