VOOZH about

URL: https://qiita.com/_mk2/items/cda64628faab29de74d4

⇱ Nodeでワンライナー #Node.js - Qiita


👁 Image
7

Go to list of users who liked

2

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

More than 5 years have passed since last update.

@_mk2(_ _)

Nodeでワンライナー

7
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

Go to list of users who liked

2
0

Go to list of comments

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

Go to list of users who liked

2