目录-入口-由此开始-大纲-总览-概括-枢纽-指导-指引-总领 [father::元笔记汇总]
安装
npm i yaml
基本概念
节点
- yaml每一项都是一个节点(NodeBase)
- 每个节点都有一些配置项
- yaml每一项都可以有子项,对应子节点
节点类型
- Scalar(标量):字符串和数字
- YAMLSeq:数组
- Pair:键值对
- YAMLMap:对象
按节点解析
- pareseDocument(字符串)可以把字符串解析为解析结果
解析
parse(),parseDocument(),parseAllDocuments(),new Composer(), andnew Document()
编码
stringify()anddoc.toString()
语法
节点配置项
通用节点
注释
comment?: string和commentBefore?: string顾名思义,注释
位置
range:三个元素的数组第一个元素为节点在原字符串中的起始位置,第二个元素为值的结束位置,第三个元素为节点的结束位置 示例:
let yaml = `
keys: ['qql1',[666,233],'qql3','qql4']
tags: [nice]
`
let g = doc.get('keys')
let range = g.range
let slice = yaml.slice(range[0], range[2])
console.log(slice)
// ['qql1',[666,233],'qql3','qql4']数组节点
flow: 布尔值数组是否用[]包围
创建节点
- 通过Pari,YAMLSeq,Scalar…类的构造函数
添加节点
child::添加节点
编码配置项
lineWidth
默认值: 80
Maximum line width (set to 0 to disable folding). This is a soft limit, as only double-quoted semantics allow for inserting a line break in the middle of a word.
注意:
- 此项一般设置为0, 不然非常容易导致编码出来的格式混乱
minContentWidth
默认值: 20
Minimum line width for highly-indented content (set to 0 to disable).
完整文档
官方文档
实例
import { parseDocument } from "../node_modules/yaml/dist/public-api"
let yaml = `
keys: ['qql1',[666,233],'qql3','qql4']
tags: [nice]
`
let doc = parseDocument(yaml)
let h = doc.has('keys')//true
let g = doc.get('keys')
let g2 = doc.getIn(['keys', 1])
let j = doc.toJS()
console.log(j)
// { keys: [ 'qql1', [ 666, 233 ], 'qql3', 'qql4' ], tags: [ 'nice' ] }
//@ts-ignore
let tags = doc.createNode(['long', 'short'])
doc.set('tags', tags)
console.dir(tags)
// YAMLSeq {
// items: [ Scalar { value: 'long' }, Scalar { value: 'short' } ]
// }
//@ts-ignore
tags.items[1].commentBefore = 'yes'
//@ts-ignore
g.flow = false
console.dir(g2)
// YAMLSeq {
// items: [
// Scalar { value: 666, range: [Array], source: '666', type: 'PLAIN' },
// Scalar { value: 233, range: [Array], source: '233', type: 'PLAIN' }
// ],
// flow: true,
// range: [ 15, 24, 24 ]
// }
let s = doc.toString()
console.log(s)
// keys:
// - 'qql1'
// - [ 666, 233 ]
// - 'qql3'
// - 'qql4'
// tags:
// - long
// #yes
// - short