Last active
March 23, 2020 17:19
-
-
Save artisonian/7e1098069eca7a767813e5a41b67e083 to your computer and use it in GitHub Desktop.
How to read lines in Deno
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { readLines } from "https://deno.land/[email protected]/io/mod.ts"; | |
import { parse } from "https://deno.land/[email protected]/flags/mod.ts"; | |
import { basename } from "https://deno.land/[email protected]/path/mod.ts"; | |
export {}; | |
if (import.meta.main) { | |
const args = parse(Deno.args, { | |
boolean: ["h"], | |
alias: { | |
h: ["help"] | |
} | |
}); | |
if (args.h) { | |
printUsage(); | |
Deno.exit(0); | |
} | |
const [filename] = args._; | |
if (!filename) { | |
printUsage(); | |
Deno.exit(1); | |
} | |
const file = filename === "-" | |
? Deno.stdin | |
: await Deno.open(String(filename)); | |
let lineCount = 0; | |
for await (const line of readLines(file)) { | |
// do something with `line` | |
lineCount += 1; | |
} | |
file.close(); | |
console.log(`${lineCount} lines read.`); | |
function printUsage() { | |
console.error( | |
`Usage: deno --allow-read ${basename(import.meta.url)} <filename>` | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment