14
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-05-25

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

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

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

nl.js
(async () => {
  const buffers = [];
  for await (const chunk of process.stdin) buffers.push(chunk);
  const buffer = Buffer.concat(buffers);
  const text = buffer.toString();
  const lines = text.split(/\r?\n/);
  lines.forEach((line, index) => console.log('%d: %s', index + 1, line));
})();

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

(async () => {
  process.stdin.setEncoding('utf8');
  let text = '';
  for await (const chunk of process.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');

const text = stringify(process.stdin);
console.lot('%s', text);

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

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

const { transform } = require('@moneyforward/stream-util');

let count = 0;
for await (const line of process.stdin.pipe(new transform.Lines())) {
  console.log('%d: %s', count++, line);
}

参考

14
9
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
14
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?