NPM酷庫045:js-yaml,讀寫YAML

NPM酷庫,天天兩分鐘,瞭解一個流行NPM庫。·node

在NPM酷庫044中,咱們瞭解到了相對於JSON格式更加易於編寫和維護的JSON5,今天咱們繼續學習另一個更加簡單易讀的數據格式YAML。git

下方就是一個YAML數據示例:github

---

receipt:     Oz-Ware Purchase Invoice
date:        2012-08-06
customer:  #對象
    given:   Dorothy
    family:  Gale

items:  # 對象數組
    - part_no:   A4786
      descrip:   Water Bucket (Filled)
      price:     1.47
      quantity:  4

    - part_no:   E1628
      descrip:   High Heeled "Ruby" Slippers
      size:      8
      price:     133.7
      quantity:  1

bill-to:  &id001 # 錨點標記 id001
    street: |  # 多行字符串
            123 Tornado Alley
            Suite 16
    city:   East Centerville
    state:  KS

ship-to:  *id001 # 引用錨點標記id001的數據

specialDelivery:  > # 多行字符串
    Follow the Yellow Brick
    Road to the Emerald City.
    Pay no attention to the
    man behind the curtain.
    
...

YAML格式可以和JSON格式互相轉換,YAML格式相對於JSON更加易於人類編寫和理解,因此更適合替代JSON用來編寫配置文件。數組

js-yaml

js-yaml 是一個專門用來讀寫YAML格式數據的庫,他能夠將JS對象轉換成YAML字符串,也能夠將YAML字符串轉換爲JS對象。學習

const yaml = require('js-yaml');
const fs = require('fs');

let obj = yaml.safeLoad(fs.readFileSync('example.yml', 'utf8'));

let str = yaml.safeDump(obj);

參考資料

http://yaml.orgui

https://zh.wikipedia.org/wiki...code

https://github.com/nodeca/js-...對象

相關文章
相關標籤/搜索