Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

YAMLから要素を削り取って軽量化するnpmパッケージ作った

Last updated at Posted at 2019-06-23

YAMLから要素を削り取って軽量化するライブラリ作った

YAMLファイルを軽量化するnpmモジュールを作りました。指定した要素を削除または空白にします。

以下に公開してあります。

scraper というのは削り取るというニュアンスの言葉です。
ちゃんと Travis CI のバッジも付けてます!

なにができるのか?

こんな感じのYAMLファイルがあるとします。

sample:
  hoge: これは消したい
  fuga: これは空白にしたい
  hogehoge:
    hoge: これも消したい
    fuga: これも空白にしたい
    hogera: これはこのまま
  piyopiyo:
    piyo: これの親を消したい

↑のYAMLに対し、以下のようなことができます。

  • key が hoge の要素はいらないから削除する
  • key が fuga の要素はいるけど、value はいらないから空白に置換する
  • key が piyo の要素の親要素はいらないから削除する

処理結果として、以下の文字列を出力します。

sample:
  fuga: ''
  hogehoge:
    fuga: ''
    hogera: これはこのまま

不必要な要素を削り取って、だいぶYAMLファイルが軽くなりました!
階層のどこにあっても見つけだして削り取ります!

なぜ作った?

普段 Swagger を使って、WebAPIのドキュメントサイトを作っています。
このSwaggerファイルをAmazon API Gatewayにインポートしたところ、容量制限のエラーが発生しました。
このエラーを回避するために、不要な要素を削り取るライブラリを作りました。

インストール方法

本ライブラリの仕様にはNode.jsが必要です。

Node.jsがインストール済みであれば、以下のコマンドでインストールできます。

npm install yaml-scraper

サンプルコード

先ほどの処理のサンプルコードは以下の通りです。

// ライブラリを追加
const fs = require('fs');
const scraper = require('yaml-scraper');

// YAMLファイルを読み込み
const input = fs.readFileSync('./sample.yaml', 'utf8');

// hogeを削除、fugaを空白に置換、piyoの親を削除
const output = scraper(input)
  .delete('hoge')
  .empty('fuga')
  .deleteParent('piyo')
  .toString();

// 結果を表示
console.log(output);

御覧の通り、 delete, empty, deleteParent はメソッドチェーンとして提供しています。

さいごに

開発するにあたり、以下の記事を参考にしました。
とてもわかりやすい記事ありがとうございました。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?