Skip to content

Instantly share code, notes, and snippets.

@artisonian
Last active Mar 23, 2020
Embed
What would you like to do?
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