Skip to content

Instantly share code, notes, and snippets.

@rjbudzynski
Created March 19, 2024 20:01
Show Gist options
  • Save rjbudzynski/3d93a49235f9a0ea9be7207a5d8908a9 to your computer and use it in GitHub Desktop.
Save rjbudzynski/3d93a49235f9a0ea9be7207a5d8908a9 to your computer and use it in GitHub Desktop.
/*
* fileinput.ts
*/
import { TextLineStream } from 'https://deno.land/std/streams/mod.ts'
const readableToLines = async function* (
readable: ReadableStream,
encoding = 'utf-8',
): AsyncIterable<string> {
const lines = readable
.pipeThrough(new TextDecoderStream(encoding))
.pipeThrough(new TextLineStream())
for await (const line of lines) {
yield line
}
}
export const input = async function* (
args: string[] = Deno.args,
encoding = 'utf-8',
): AsyncIterable<string> {
if (!args.length) {
const lines = readableToLines(Deno.stdin.readable, encoding)
for await (const line of lines) {
yield line
}
}
for (const filename of args) {
const file = await Deno.open(filename)
const lines = readableToLines(file.readable, encoding)
for await (const line of lines) {
yield line
}
}
}
if (import.meta.main) {
const lines = input()
let lineno = 0
for await (const line of lines) {
console.log(`${++lineno}: ${line}`)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment