js에서 ini 파일 사용하기

KyungUp·2024년 12월 13일
0
import { getiniFile, updateIniFile } from './utils.js'

or

import utils from './utils.js'
// utils.js

import 'fse' from 'fs-extra'

/**
 * ini 파일을 JSON 객체로 변환
 * @param {String} content
 */
function parseIni(content) {
  const result = {}
  let currentSection = null

  const lines = content.split(/\r?\n/)
  for (const line of lines) {
    const trimmedLine = line.trim()
    if (!trimmedLine || trimmedLine.startsWith(';') || trimmedLine.startsWith('#')) {
      continue
    }

    if (trimmedLine.startsWith('[') && trimmedLine.endsWith(']')) {
      currentSection = trimmedLine.slice(1, -1).trim()
      result[currentSection] = {}
    } else if (currentSection) {
      const [key, value] = trimmedLine.split('=').map((part) => part.trim())
      if (key && value) {
        result[currentSection][key] = value
      }
    }
  }

  return result
}


/**
 * ini 파일 내용 업데이트 함수
 * @param {Object} ini
 * @property {String} ini.section
 * @property {String} ini.key
 * @property {String} ini.value
 * @property {Object} ini.defaultContent
 */
export async function updateIniFile(ini) {
  try {
    const { section = '', key = '', value = '', defaultContent = {} } = ini

    let parsedContent = {}
    if (await fse.pathExists(파일경로)) {
      const iniContent = fse.readFileSync(파일경로, 'utf8')
      parsedContent = parseIni(iniContent)
    }

    for (const [defaultSection, keys] of Object.entries(defaultContent)) {
      if (!parsedContent[defaultSection]) {
        parsedContent[defaultSection] = {}
      }

      for (const [defaultKey, defaultValue] of Object.entries(keys)) {
        if (!parsedContent[defaultSection][defaultKey]) {
          parsedContent[defaultSection][defaultKey] = defaultValue
        }
      }
    }

    if (section && key && value !== undefined) {
      if (!parsedContent[section]) {
        parsedContent[section] = {}
      }

      parsedContent[section][key] = value
    }

    const updatedContent = Object.entries(parsedContent).map(([sec, keys]) => {
      const sectionContent = Object.entries(keys).map(([k, v]) => `${k}=${v}`).join('\n')
      return `[${sec}]\n${sectionContent}`
    }).join('\n\n')

    await fse.writeFile(파일경로, updatedContent)
    return updatedContent
  } catch (err) {
    throw err
  }
}

/**
* ini 파일 데이터 불러오기
*/
export async function getiniFile() {
  const defaultContent = {
    email: {
      test: 'test@test.com'
    },
    phone: {
      test: '010-1010-1010'
    },
    address: {
      test: 'Seoul'
    }
  }

  try {
    if (!(await fse.pathExists(파일경로))) {
      const content = Object.entries(defaultContent).map(([section, keys]) => {
        const sectionContent = Object.entries(keys).map(([key, value]) => `${key}=${value}`).join('\n')
        return `[${section}]\n${sectionContent}`
      }).join('\n\n')

      await fse.ensureDir(파일경로폴더)
      await fse.writeFile(파일경로, content)
    }

    const updatedContent = await updateIniFile({ section: '', key: '', value: '', defaultContent: defaultContent })
    console.log(parseIni(updatedContent))
  } catch (err) {
    throw err
  }
}

export default {
	getiniFile,
    updateIniFile
}
profile
poe2 가즈아!

0개의 댓글