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 是一个专门用来读写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);