LoginSignup
7
2

More than 5 years have passed since last update.

Nodeでワンライナー

Posted at

Nodeで標準入力を処理するワンライナーがしたいなと思ったので、やってみました。Node5.0.0使用。

基本

$ echo 'test' | node -e "var c='';process.stdin.on('readable',()=>{c+=process.stdin.read()});process.stdin.on('end',()=>{console.log('c='+c)})"
c=test
null

な、長い…
ですが、stdinのreadableイベントとendイベントをなんとかすればワンライナーできることがわかりました。

CSVの1カラム目を切り出す

下記のCSVファイルの1カラム目を切り出したい。

test.csv
col11,col21
col12,col22
$ cat test.csv | node -e "var c='';process.stdin.on('readable',()=>{c+=process.stdin.read()});process.stdin.on('end',()=>{c.split('\n').forEach((e)=>{e.split(',').forEach((e,i)=>{if(i==0){console.log(e)}})})})"
col11
col12
null

Nodeでワンライナーするコツは、自分が今どの括弧の中にいるのかというのを常に把握し続けることだと理解しました。ふえええ…

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2