Develop/Node.js
Node.js yaml 파일 읽고 쓰기
팡연
2024. 1. 21. 17:46
반응형
Node.js 에서 yaml 파일 읽고 쓰려면 간단히 js-yaml 라이브러리를 사용한다
1. install js-yaml
npm install js-yaml --save
2. Read & Write
js-yaml 에서 제공하는 load와 dump 기능을 통해 사용한다.
const yaml = require('js-yaml');
const fs = require('fs');
const url = './config.yaml';
try {
const file = yaml.load(fs.readFileSync(url), 'utf8');
file.clusters[0].cluster.server = '192.168.0.1';
fs.writeFileSync('./new-config.yaml', yaml.dump(file), 'utf8')
} catch (e) {
console.log(e)
}
이렇게 간단하게 적용하면 되긴되나, 배열의 경우 옵션을 주지 않으면 아래와 같이 쓸모없는 indent가 추가된다.
기존 config.yaml
# config.yaml
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: test
server: https://127.0.0.1:6443
변경된 new-config.yaml
# new-config.yaml
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: test
server: 192.168.0.1
name: dev-k8s
3. 이 경우 js-yaml 라이브러리에서 제공하는 noArrayIndent 를 사용하여 해결 가능하다.
const yaml = require('js-yaml');
const fs = require('fs');
const url = './config.yaml';
try {
const file = yaml.load(fs.readFileSync(url), 'utf8');
file.clusters[0].cluster.server = '192.168.0.1';
fs.writeFileSync('./new-config.yaml', yaml.dump(file, {
noArrayIndent: true
}), 'utf8')
} catch (e) {
console.log(e)
}
결과.
# new-config.yaml
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: test
server: 192.168.0.1
name: dev-k8s
반응형