68 lines
2.1 KiB
JavaScript
68 lines
2.1 KiB
JavaScript
const fs = require("node:fs")
|
|
const path = require("node:path")
|
|
let optionsFile
|
|
|
|
function initOptions($optionFile) {
|
|
optionsFile = $optionFile
|
|
const gameDir = path.parse($optionFile).dir
|
|
if (!fs.existsSync(gameDir)) {
|
|
try {
|
|
fs.mkdirSync(gameDir)
|
|
} catch (error) {
|
|
throw error
|
|
}
|
|
}
|
|
if (!fs.existsSync($optionFile)) {
|
|
try {
|
|
fs.copyFileSync(path.join(__dirname, "..", "options.txt"), $optionFile)
|
|
} catch (error) {
|
|
throw error
|
|
}
|
|
}
|
|
}
|
|
|
|
function parseOptions() {
|
|
const options = fs.readFileSync(optionsFile, "utf-8").toString().split("\n").filter(line => line.trim() !== "")
|
|
const parsedOptions = {}
|
|
for (let i = 0; i < options.length; i++) {
|
|
const line = options[i].trim()
|
|
const [key, value] = line.split(":")
|
|
if (key && value) {
|
|
const trimmedValue = value.trim().toLowerCase()
|
|
if (trimmedValue === "true" || trimmedValue === "false") {
|
|
parsedOptions[key.trim()] = trimmedValue === "true"
|
|
} else {
|
|
parsedOptions[key.trim()] = isNaN(value) ? value.trim() : parseInt(value, 10)
|
|
}
|
|
}
|
|
}
|
|
return parsedOptions
|
|
}
|
|
|
|
function stringfyOptions(optionsObject) {
|
|
const optionsArray = []
|
|
if (typeof optionsObject !== "object" || optionsObject === null) {
|
|
throw new Error("Invalid options object")
|
|
}
|
|
for (const settingKey in optionsObject) {
|
|
if (Object.prototype.hasOwnProperty.call(optionsObject, settingKey)) {
|
|
const settingValue = optionsObject[settingKey]
|
|
if (typeof settingValue === "object" || typeof settingValue === "function" || typeof settingValue === "symbol") {
|
|
throw new Error(`Invalid value for setting "${settingKey}": ${settingValue}`)
|
|
}
|
|
optionsArray.push(`${settingKey}:${settingValue}`)
|
|
}
|
|
}
|
|
return optionsArray.join("\n")
|
|
}
|
|
|
|
function saveOptions(options) {
|
|
fs.writeFileSync(optionsFile, options, "utf8")
|
|
}
|
|
|
|
module.exports = {
|
|
initOptions,
|
|
saveOptions,
|
|
parseOptions,
|
|
stringfyOptions
|
|
} |