17xande
17xande

Reputation: 2803

Pipe strings into Deno from CLI

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?

Upvotes: 5

Views: 657

Answers (1)

17xande
17xande

Reputation: 2803

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)
}

Upvotes: 3

Related Questions