Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

Node.js 12+なら標準入力が超簡単に読める

$
0
0

process.stdinfor await...ofでループできる

Node.js 12からstream.Readableが非同期反復オブジェクト(Async Iterable)になりました。

当然process.stdinもAsync Iterableなので、for await...of文でループできます。

nl.js
(async()=>{constbuffers=[];forawait(constchunkofprocess.stdin)buffers.push(chunk);constbuffer=Buffer.concat(buffers);consttext=buffer.toString();constlines=text.split(/\r?\n/);lines.forEach((line,index)=>console.log('%d: %s',index+1,line));})();

補足ですが、文字エンコーディングを指定したい場合は、事前にsetEncoding(encoding)で設定します。

(async()=>{process.stdin.setEncoding('utf8');lettext='';forawait(constchunkofprocess.stdin)text+=chunk;console.log('%s',text);})();

@moneyforward/stream-utilを使えば、さらに簡潔に

@moneyforward/stream-utilを使うと、さらに簡潔になります。

まずは、インストールを。

npm install @moneyforward/stream-util

テキストとして一括取得するならstringify

@moneyforward/stream-utilstringifyを使えば、ごく簡潔に文字列にできます。

const{stringify}=require('@moneyforward/stream-util');consttext=stringify(process.stdin);console.lot('%s',text);

行ごとに逐次処理するならtransform.Lines

@moneyforward/stream-utiltransform.Linesを使えば、行ごとにループして逐次処理が簡潔にできます。

const{transform}=require('@moneyforward/stream-util');letcount=0;forawait(constlineofprocess.stdin.pipe(newtransform.Lines()){console.log('%d: %s',count++,line);}

参考


Viewing all articles
Browse latest Browse all 8691

Trending Articles