从 CLI 将字符串传输到 Deno

17x*_*nde 5 command-line-interface deno

如何将文件的内容通过管道传输到 Deno 脚本中进行处理?

例如:
cat names.txt | deno run deno-script.ts

cat names.txt | deno-script.ts

在node.js中我们可以执行以下操作:

#!/usr/local/bin/node
// The shebang above lets us run the script directly,
// without needing to include `node` before the script name.

const stdin = process.openStdin();

stdin.on('data', chunk => {
  const lines = chunk.toString().split('\n');
  lines.forEach(line => {
    // process each line...
    console.log(line);
  })
})
Run Code Online (Sandbox Code Playgroud)

Deno 的标准输入有点不同,这个答案展示了如何使用缓冲区将一块标准输入放入内存并开始处理。
逐行读取和处理数据的最佳方法是什么?

17x*_*nde 3

Deno 标准库中的readLines函数非常适合此目的。

#!/usr/bin/env -S deno run
// The shebang above lets us run the script directly,
// without needing to include `deno run` before the script name.

import { readLines } from 'https://deno.land/std/io/buffer.ts'

for await (const l of readLines(Deno.stdin)) {
  // process each line...
  console.log(l)
}
Run Code Online (Sandbox Code Playgroud)