Javascript/Node.js
Node.js - Yaml to Object
Flashback
2025. 5. 2. 20:56
728x90
반응형
javascript에서 yaml파일을 읽어들이려면 js-yaml이라는 npm 모듈을 설치해야 한다.
yarn add js-yaml
npm install js-yaml
모듈 설치 후, 로컬에 설치되어 있는 yaml파일을 불러오거나 cdn 등에 올라가있는 외부 yaml파일을 불러와 사용할 수 있다.
const fs = require('fs');
const yaml = require('js-yaml');
const fileContents = fs.readFileSync('yaml file path', 'utf8')
const data = yaml.load(fileContents)
console.log(data) // yaml file data
로컬에 있는 경우는 fs.readFileSync로 yaml파일을 읽어들인 후에 yaml.load()로 텍스트 문자열을 자바스크립트 객체로 변환시킨다. 이후에 콘솔에 출력하면 yaml파일의 내용이 객체 형식으로 변환되어 출력된다.
외부 yaml파일을 불러오려면 async await 를 사용해야 한다. async await를 사용하여 응답 본문을 문자열로 읽어 들인 후에 yaml.load()를 사용하여 객체 형식으로 변환시켜 출력한다.
import yaml from 'js-yaml'
async function getYamlData() {
const url = 'yaml file path'
const data = await fetch(url)
const dataText = await data.text()
const yamlData = yaml.load(dataText)
console.log(yamlData) // yaml file data
}
getYamlData()
참고 사이트:
https://www.npmjs.com/package/js-yaml
js-yaml
YAML 1.2 parser and serializer. Latest version: 4.1.0, last published: 4 years ago. Start using js-yaml in your project by running `npm i js-yaml`. There are 21125 other projects in the npm registry using js-yaml.
www.npmjs.com
728x90
반응형