AI PROMPTS · 루프 생성 전략
Node.js 자동화 병합 스크립트
루프 생성된 개별 JSON 파일들을 하나의 JS 파일로 병합하는 Node.js 스크립트입니다.
루프 생성 전략
핵심 설명
루프 생성된 개별 JSON 파일들을 하나의 JS 파일로 병합하는 Node.js 스크립트입니다.
Node.js 18+
// scripts/merge.js
// 사용법: node scripts/merge.js kotlin 33 82
const fs = require('fs');
const path = require('path');
const [, , lang, startStr, endStr] = process.argv;
const start = parseInt(startStr);
const end = parseInt(endStr);
// 기존 파일 읽기
const existingPath = path.join('data', `${lang}.js`);
let existing = fs.readFileSync(existingPath, 'utf8');
// items 배열의 닫는 ] 위치 찾기
const insertPos = existing.lastIndexOf(']; // end items');
if (insertPos === -1) {
console.error('❌ items 배열 끝 위치를 찾을 수 없습니다');
process.exit(1);
}
const newItems = [];
for (let num = start; num <= end; num++) {
const padded = String(num).padStart(3, '0');
const tmpPath = path.join('data', `${lang}_${padded}.tmp.json`);
if (!fs.existsSync(tmpPath)) {
console.warn(`⚠️ 없는 파일: ${tmpPath}`);
continue;
}
try {
const item = JSON.parse(fs.readFileSync(tmpPath, 'utf8'));
// 필수 필드 검증
const required = ['id','cat','diff','title','desc','code','lang','tip','mistake'];
const missing = required.filter(f => !item[f]);
if (missing.length > 0) {
console.warn(`⚠️ 누락 필드 [${padded}]: ${missing.join(', ')}`);
continue;
}
newItems.push(item);
console.log(` ✅ ${lang}-${padded} 병합 완료`);
} catch (e) {
console.error(`❌ JSON 파싱 실패 [${padded}]: ${e.message}`);
}
}
// JS 객체 직렬화 (JSON이 아닌 JS 리터럴)
const serialized = newItems
.map(item => {
const tags = JSON.stringify(item.tags || []);
return `
{
id: '${item.id}', cat: '${item.cat}', diff: '${item.diff}',
title: '${item.title.replace(/'/g, "\\'")}',
desc: \`${item.desc}\`,
code: \`${item.code}\`,
lang: '${item.lang}',
tip: '${(item.tip||'').replace(/'/g, "\\'")}',
mistake: '${(item.mistake||'').replace(/'/g, "\\'")}',
tags: ${tags},
}`;
})
.join(',\n');
// 파일에 삽입
const updated = existing.slice(0, insertPos) +
serialized + ',\n ' +
existing.slice(insertPos);
fs.writeFileSync(existingPath, updated, 'utf8');
console.log(`\n✅ ${newItems.length}개 항목 병합 완료: ${existingPath}`);
// tmp 파일 정리
for (let num = start; num <= end; num++) {
const padded = String(num).padStart(3, '0');
const tmpPath = path.join('data', `${lang}_${padded}.tmp.json`);
if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath);
}
console.log('🧹 임시 파일 정리 완료');Continue Learning
AI Prompts 학습을 이어가세요
총 20개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.