Deno에 간단한grep 설치

24892 단어 DenoCLItech
새로운 언어를 공부할 때 그 언어로 뭔가를 해봐
(들어본 적은 없지만, 아마도) 데노의 분위기를 잡기 위해 CLI를 해보고 싶어요
※ 데노 테스트를 목적으로 하기 때문에 정상적인 시스템 이외의 상황은 고려하지 않습니다.
제작된 서버측 프로그램과 GUI 앱은 모두 가능하지만, 서버측 개발은 이미 익숙해져서 즐겁게 놀 수 없고, Deno에서는 GUI를 어떻게 해야 좋을지 몰라서 이번에는 CLI를 선택했습니다.
이것이 바로
https://github.com/l-freeze/dgrep

1. 본문에서 Deno 기술

  • 파일 읽기
  • 명령행 매개 변수 처리 방법
  • 표준 출력
  • 2. 제작 명령 후보 고려

    stdinstdout로 간단하고 간단하게
  • cat
  • grep
  • 3. 명령 선택


    cat: 반박
    공식 문서에 샘플 코드가 있으니까.
    https://deno.land/[email protected]/examples/unix_cat
    grep: 적용
    cat의 기각 결정에 따라 삭제법으로grep를 만듭니다

    4. 환경 구축


    Deno 설치
  • Windows 10의 경우
  • powershell7
    scoop install deno
    
  • WSL2의 사람
  • wsl
    asdf plugin-add deno
    asdf install deno 1.16.4
    asdf global deno 1.16.4
    
    설치 확인
    $ deno
    Deno 1.16.4
    exit using ctrl+d or close()
    > Deno.env.toObject();
    
    잘못된 정보가 있으면 설치 절차를 다시 확인하십시오
    VScode 설정
    https://zenn.dev/uki00a/books/effective-deno/viewer/first-step
    여기 순서를 참고하여 설정하다
    (단계를 설정해 주셔서 감사합니다. 지금까지 VScode 설정은 모두 설정되어 있습니다.)
    작업공간이 아니라 전체 VScode 설정을 할 때 설정으로 Deno에게 필요한 것을 확인하세요

    5. 사고방식

    grep --help 명령을 고려한 옵션 기반
    그렇게 말하고 싶었지만 이번에는 일반적인 지령에 간단한 내용을 설치하는 것으로 한정되었다
    옵션
    설명
    -E --extended-regexp
    PATTERNS are extended regular expressions
    -i --ignore-case
    ignore case distinctions in patterns and data
    묵인하고 싶어서--extended-regexp실질egrep -i ./filepath

    6.제작


    테스트 파일 만들기
    위키의 데노의 설명을 인용하여 견본을 만들다
    sample.txt
    概要
    Denoは現代のプログラマのための生産的で安全なスクリプト環境を目指している[5]。Node.jsと同様に、Denoはイベント駆動型アーキテクチャ(英語版)に重点を置いており、非ブロッキングコアIOユーティリティのセットとそのブロッキング版を提供している。DenoはWebサーバの作成や科学計算に利用することができる。発音はデノが近く一般的だが、ディーノと呼ばれることもある。
    
    Node.jsとの比較
    DenoとNode.jsはGoogle ChromeなどのChromiumベースのウェブブラウザで採用されているV8 JavaScriptエンジン上に構築されたランタイム環境である。どちらも内部イベントループがあり、スクリプトと広範なコマンドラインユーティリティを実行するためのコマンドラインインタフェースを提供している。
    
    DenoがNode.jsと異なる主な点は以下の通りである[5]:
    
    CommonJSの代わりに、ES Moduleをデフォルトのモジュールとシステムとして使用する。
    ウェブブラウザと同様に、依存関係 (ローカル及びリモート) を読み込むためにURLを使用する。
    リソースを取得するためのパッケージ管理システムが組み込まれているので、npmは不要である。
    キャッシングメカニズムを備えたスナップショットTypeScriptコンパイラを使用することによるTypeScriptのサポート。
    幅広いWeb APIを実装することによるウェブブラウザとの互換性の向上。
    サンドボックスコードを実行するために、ファイルシステムとネットワークアクセスを制御することができる。
    promise、ES6及びTypeScriptの機能を利用するためにAPIを再設計したこと。
    コアAPIのサイズを最小限にしながら、外部に依存関係の無い大きな標準ライブラリを提供すること。
    特権システムAPIを呼び出しとバインディングの使用のために、メッセージ受け渡しチャネルを使用すること。
    

    설치(1)


    우선 매개 변수 지정 파일을 고려하지 말고 실현해야 한다
    deno
    const readText = await Deno.readTextFile("./sample.txt");
    const regex = /node/i;
    for(const row of readText.split(/\r\n|\r|\n/)){
        if(-1 != row.search(regex)){
            console.log(row);
        }
    }
    

    실행

    deno run --allow-read .\main.ts움직이다
    하지만 생각할 때도 보이지 않는 두 가지 문제
  • 거대한 파일로 사망
  • console.log 사용
  • 설치(2)


    BufReader를 사용하여 대용량 파일 처리
    deno
    import { BufReader,ReadLineResult } from "https://deno.land/[email protected]/io/mod.ts";
    const filepath = "./sample.txt";
    const regex = /node/i;
    const encoder = new TextEncoder();
    const decoder = new TextDecoder();
    const lfUint8 = encoder.encode("\n");
    const stdout = Deno.stdout;
    const file = await Deno.open(filepath, {read: true});
    const bufReader = BufReader.create(file);
    let result: ReadLineResult|null;
    if(Deno.build.os == 'windows'){
        console.log("windowsのエンコードはどないしたらええんや");
    }
    while ( (result = await bufReader.readLine()) != null ) {
        if(-1 != decoder.decode(result.line).search(regex)){
            await stdout.write(result.line);
            await stdout.write(lfUint8);
        }
    }
    file.close();
    
    버퍼에서 읽는 부분에 크기를 지정하면 비슷해요.
    dneo
    const bufReader = BufReader.create(file, 1024);
    
    이때의 줄 바꿈 판정은 사용하지 않는다\n
    dneo
    if(!result.more) {
        //1行読み切った
    }
    
    이렇게 쓰세요.

    실행

    deno run --allow-read main.ts움직이다
    이후에는 -i-E만 해당됩니다.
    Windows는 역시 문자 코드의 문제가 있어서 denoland에서 해결할 수 없을 것 같아서 이 생각을 포기하고 WSL에서 실행했다

    설치(3)


    명령줄 매개 변수의 대응
    명령줄 매개변수Deno.args 및 Standard Libraryflags 사용
    deno
    import {parse} from "https://deno.land/[email protected]/flags/mod.ts";
    
    const filepath = Deno.args[Deno.args.length-1];
    if(filepath == undefined){
        console.log("ダメ");
        Deno.exit();
    }
    console.log(parse(Deno.args, {"--": false}))
    const iFlag = !parse(Deno.args).i ? false : true;
    
    시도해보니 번거로워 보여 사용하기 편한 도서관을 찾고 싶어 Third Party Modules에서 검색argv해보니 ★[email protected]카드가 많이 걸려 있길래 일단 시도해보니
    deno
    import yargs from 'https://deno.land/x/yargs/deno.ts';
    import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts';
    const argv: Arguments  = yargs(Deno.args)
      .usage('dgrep [OPTION]... PATTERNS [FILE]..')
      .command('dgrep', 'deno grep')
      .alias('i', 'ignore-case')
      .describe('i', 'ignore case distinctions in patterns and data')
      .alias('n', 'line-number')
      .describe('n', 'print line number with output lines')
      .alias('h', 'help')
      .boolean(['i', 'n'])
      .default('i', false)
      //.demandOption(['i'])//required
      //.strictCommands()
      .parse();
    
      console.log(argv);
    
    간단하게 처리할 수 있는 것을 확인했기 때문에 추가nフラグ하는 김에 줄 번호도 결과에 표시할 수 있습니다
    deno
    //追加する
    let lineNumber = 0;
    while ( (result = await bufReader.readLine()) != null ) {
        lineNumber++;
    }
    

    7. 설치 완료


    완성물
    https://github.com/l-freeze/dgrep
    코드를 읽으면 알 수 있듯이 소식이 없으면 처리가 끝나는 경우도 있다

    시험해 보다

    deno 검색
    $ deno run --allow-read main.ts deno ./sample.txt
    
    i 옵션deno 검색
    deno run --allow-read main.ts -i deno ./sample.txt
    Denoは現代のプログラマのための生産的で安全なスクリプト環境を目指している[5]。Node.jsと同様に、Denoはイベント駆動型アーキテクチャ(英語版)に重点を置いており、非ブロッキングコアIOユーティリティのセットとそのブロッキング版を提供している。DenoはWebサーバの作成や科学計算に利用することができる。発音はデノが近く一般的だが、ディーノと呼ばれることもある。
    DenoとNode.jsはGoogle ChromeなどのChromiumベースのウェブブラウザで採用されているV8 JavaScriptエンジン上に構築されたランタイム環境である。どちらも内部イベントループがあり、スクリプトと広範なコマンド ラインユーティリティを実行するためのコマンドラインインタフェースを提供している。
    DenoがNode.jsと異なる主な点は以下の通りである[5]:
    
    행 번호 포함 n 옵션 ウェブ 검색
    $ deno run --allow-read main.ts -n "ウェブ" ./sample.txt
    5: DenoとNode.jsはGoogle ChromeなどのChromiumベースのウェブブラウザで採用されているV8 JavaScriptエンジン上に構築されたランタイム環境である。どちらも内部イベントループがあり、スクリプトと広範なコマンドラインユーティリティを実行するためのコマンドラインインタフェースを提供している。
    10: ウェブブラウザと同様に、依存関係 (ローカル及びリモート) を読み込むためにURLを使用する。
    13: 幅広いWeb APIを実装することによるウェブブラウザとの互換性の向上。
    

    8.컴파일


    데노가 없는 환경에서도 작동할 수 있도록 컴파일했습니다.
    wsl
    $ deno compile --allow-read main.ts
    Check file:///path/dgrep/main.ts
    Bundle file:///path/dgrep/main.ts
    Compile file:///path/dgrep/main.ts
    Emit dgrep
    
    wsl
    $ ls
    dgrep  main.ts  sample.txt
    
    되다
    컴파일 파일 파일 크기 84M

    9. 단일 제작 명령 테스트


    일본어를 큰따옴표로 검색하지 않음
    ./dgrep リソース ./sample.txt
    リソースを取得するためのパッケージ管理システムが組み込まれているので、npmは不要である。
    
    in 옵션 세트로 검색
    $ ./dgrep -in script ./sample.txt
    5: DenoとNode.jsはGoogle ChromeなどのChromiumベースのウェブブラウザで採用されているV8 JavaScriptエンジン上に構築されたランタイム環境である。どちらも内部イベントループがあり、スクリプトと広範なコマンドラインユーティリティを実行するためのコマンドラインインタフェースを提供している。
    12: キャッシングメカニズムを備えたスナップショットTypeScriptコンパイラを使用することによるTypeScriptのサポート。
    15: promise、ES6及びTypeScriptの機能を利用するためにAPIを再設計したこと。
    
    정규 표현식으로 검색
    wsl
    $ ./dgrep -in "j........t|common" ./sample.txt
    5: DenoとNode.jsはGoogle ChromeなどのChromiumベースのウェブブラウザで採用されているV8 JavaScriptエンジン上に構築されたランタイム環境である。どちらも内部イベントループがあり、スクリプトと広範なコマンドラインユーティリティを実行するためのコマンドラインインタフェースを提供している。
    9: CommonJSの代わりに、ES Moduleをデフォルトのモジュールとシステムとして使用する。
    

    총결산


    동작이 너무 무거워요.
    너무 크다

    좋은 웹페이지 즐겨찾기