process.stdin
はfor 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-util
のstringify
を使えば、ごく簡潔に文字列にできます。
const{stringify}=require('@moneyforward/stream-util');consttext=stringify(process.stdin);console.lot('%s',text);
行ごとに逐次処理するならtransform.Lines
@moneyforward/stream-util
のtransform.Lines
を使えば、行ごとにループして逐次処理が簡潔にできます。
const{transform}=require('@moneyforward/stream-util');letcount=0;forawait(constlineofprocess.stdin.pipe(newtransform.Lines()){console.log('%d: %s',count++,line);}