Skip to content

Instantly share code, notes, and snippets.

@artisonian
Last active March 23, 2020 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artisonian/7e1098069eca7a767813e5a41b67e083 to your computer and use it in GitHub Desktop.
Save artisonian/7e1098069eca7a767813e5a41b67e083 to your computer and use it in GitHub Desktop.
How to read lines in Deno
import { readLines } from "https://deno.land/std@v0.36.0/io/mod.ts";
import { parse } from "https://deno.land/std@v0.36.0/flags/mod.ts";
import { basename } from "https://deno.land/std@v0.36.0/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