安装 js-yaml
npm install js-yaml
index.js
let fs = require("fs");let content = fs.readFileSync("text.yaml",{encoding:"utf8"});let yaml = require("js-yaml");let result = yaml.load(content);console.log(JSON.stringify(result, null, 2));console.log(result.fn(1,3));console.log(result.reg.test("test"));console.log(result.undef);
text.yaml
#对象键值对name: xxxhash: { name: Steve, foo: bar } #数组array: - Cat - Dog - Goldfisharray2: [Cat, Dog]array3: - - a - b#符合结构languages: - ruby - [{name: perl,code: 2}] - name: js code: 3 #纯量parent: ~ isSet: truenumber: 12.30date: 1976-07-31#类型转换string: !!str 1int: !!int "2"bool: !!bool "true" fn: !!js/function function(a,b){return a+b;}reg: !!js/regexp /test/undef: !!js/undefined '' #引用defaults: &defaults adapter: postgres host: localhostnewDefault: *defaults development: database: myapp_development <<: *defaults