Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Denoで簡単なCLIツールを作ってみる / Try to make a simple CLI tool with Deno

Denoで簡単なCLIツールを作ってみる / Try to make a simple CLI tool with Deno

Denoで簡単なCLIツールを作ってみる
Kanazawa.js もくもく&LT会 #18 2022.02.26

Kentaro Matsushita

February 26, 2022
Tweet

More Decks by Kentaro Matsushita

Other Decks in Programming

Transcript

  1. Denoとは Node.jsの作者であるRyan Dahl氏によって立ち上げられた JavaScriptおよびTypeScriptのランタイム環境 10 Things I Regret About Node.js

    JSConf EU 2018でRyan Dahl氏はNode.jsの設計に関する後悔 を語った Denoはこれらを解決したものとして開発されている
  2. /** * Fisher-Yates algorithm に基づいたシャッフル関数 * 30-seconds-of-code の実装例より * @see

    https://github.com/30-seconds/30-seconds-of-code/blob/master/snippets/shuffle.md */ const shuffle = ([...arr]) => { let m = arr.length while (m) { const i = Math.floor(Math.random() * m--) ;[arr[m], arr[i]] = [arr[i], arr[m]] } return arr } const speaker = [ '_kentaro_m', 'tom-256', 'yu_kgr', ] console.log(shuffle(speaker))
  3. コマンドパース処理 c4spar/deno-cliffyでコマンドが簡単に定義できます。 import { Command } from "https://deno.land/x/[email protected]/command/mod.ts"; import {

    handler } from './handler.ts'; await new Command() .name("shuf") .version("0.1.0") .description("Write a random permutation of the input lines to standard output.") .arguments('[fileName:string]') .action(async (_, fileName: string) => await handler(fileName)) .parse(Deno.args);
  4. ファイル読み取りから結果出力 ファイルと標準入力からのテキスト読み込みに対応しています。 mport { readContents, createFileReader, showResult } from './util.ts';

    type Handler = (fileName: string) => void; export const handler: Handler = async (fileName) => { const isatty = Deno.isatty(Deno.stdin.rid); const reader = isatty ? await createFileReader(fileName) : Deno.stdin; if (reader) { const contents = await readContents(reader).catch(() => Deno.exit(1)); showResult(contents); }
  5. END