5

How can I pipe the contents of a file into a Deno script for processing?

EG:
cat names.txt | deno run deno-script.ts
OR
cat names.txt | deno-script.ts

In node.js we can do the following:

#!/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);
  })
})

Deno's stdin is a bit different, this answer shows how I can use a buffer to use a chunk of stdin into memory and start processing.
What's the best way to read and process the data line by line?

17xande
  • 2,430
  • 1
  • 24
  • 33

1 Answers1

3

The readLines function from the Deno standard library is great for this.

#!/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)
}
wobsoriano
  • 12,348
  • 24
  • 92
  • 162
17xande
  • 2,430
  • 1
  • 24
  • 33
  • 1
    Note that `readLines` splits on `\r\n` in addition to `\n`, so if for some reason you actually want to split on LF only (per the code in your question), you'll need to use another method. – jsejcksn Jul 22 '21 at 14:58
  • I hadn't considered that. For the purposes of what I'm trying to do, it's actually better that it splits on both `\r\n` and `\n`. Thanks for pointing that out. – 17xande Jul 22 '21 at 15:31