yaml文件解析:nodejs篇

本文使用 nodejs 的 yamljs 库对 yaml 文件进行解析。

安装

直接使用 npm i yamljs 即可安装。

测试

yaml 配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# yaml测试样例
# null 或 NULL 为关键字,不能写

# 名称
# 字符串
name: conf file

# 版本
# 如按浮点,2.0会转换成2
# 如按字符串,保留原样
version: 2.0

# 布尔类,转换为1或0
need: true

# 时间
time: 2020-10-03T09:21:13

empty: nul

# 对象
# 加双引号会转义\n,即会换行
my:
name: late \n lee
name1: "late \n lee"
age: 99

# 块
text: |
hello
world!

# 数组
fruit:
- apple
- apple1
- apple2
- apple3
- apple4
- apple5

# 多级数组
multi:
sta:
- 110 210 ddd 99
- 133 135 1 2 1588 1509
- 310-410
- 333-444

该示例基本涵盖了大部分的 yaml 格式。包括:字符串,数值、数组、多级map。

测试代码

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
npm i yamljs
执行:nodejs test.js
*/

YAML = require('yamljs');
function main()
{
// 固定配置文件名 TODO:容错处理
nativeObject = YAML.load('config.yaml');

jsonstr = JSON.stringify(nativeObject);
theJson = JSON.parse(jsonstr, null);

console.log("alljson: ", theJson);
console.log("name: ", theJson.name);
console.log("version: ", theJson.version);

console.log("empty: ", theJson.empty); // nodejs 可处理null值
console.log("time: ", theJson.time);

console.log("name: ", theJson.my.name);
console.log("name1: ", theJson.my.name1);
console.log("age: ", theJson.my.age);

console.log("text: ", theJson.text);

theText = "";
// 数组,遍历
theJson.multi.sta.forEach(function(v, _, _){
theText += v + '\n';
});
console.log("sta ", theText);

// 是否需要显示提交日志
if (theJson.need == true)
{
console.log("need...");
}
}

// call main
main();

输出结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
$ node test.js
alljson: { name: 'conf file',
version: 2,
need: true,
time: '2020-10-03T09:21:13.000Z',
empty: 'nul',
my: { name: 'late \\n lee', name1: 'late \n lee', age: 99 },
text: 'hello\nworld!\n',
fruit:
[ 'apple', 'apple1', 'apple2', 'apple3', 'apple4', 'apple5' ],
multi:
{ sta:
[ '110 210 ddd 99',
'133 135 1 2 1588 1509',
'310-410',
'333-444' ] } }
name: conf file
version: 2
empty: nul
time: 2020-10-03T09:21:13.000Z
name: late \n lee
name1: late
lee
age: 99
text: hello
world!

bad: undefined
sta 110 210 ddd 99
133 135 1 2 1588 1509
310-410
333-444

need...

结果说明

1、可以看到,解析后的 theJson 变量,就是整个配置文件的 json,可以直接使用其中的字段。
2、使用 yamljs 解析时,参数的值可以为 null 或 NULL。这点与 yaml-cpp 库不一样。
3、如果字段不存在时,得到的结果为 undefined,并不会出现段错误。这点与 yaml-cpp 库也不一样。