simple-properties-db
Version:
A simple file-based key-value properties database for Node.js
114 lines (92 loc) • 3.63 kB
JavaScript
const fs = require('fs');
const path = require('path');
class SimplePropertiesDB {
constructor(dbPath, options = {}) {
const absPath = path.isAbsolute(dbPath) ? dbPath : path.join(process.cwd(), dbPath);
this.DB_FILE_PATH = path.join(absPath, "db.properties");
// Extract the directory part of the path
const dir = path.dirname(this.DB_FILE_PATH);
// Ensure the directory exists
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Then safely create the file
if (!fs.existsSync(this.DB_FILE_PATH)) {
fs.writeFileSync(this.DB_FILE_PATH, '');
}
}
// Enhanced: parse string, number, boolean, and JSON object/array
_parseValue(value) {
if (value === "true") return true;
if (value === "false") return false;
if (value === "") return value;
if (!isNaN(value)) return parseFloat(value);
// Try to parse as JSON if it looks like an object or array
if (
typeof value === "string" &&
((value.startsWith("{") && value.endsWith("}")) ||
(value.startsWith("[") && value.endsWith("]")))
) {
try {
return JSON.parse(value);
} catch (e) {
// Not valid JSON, return as string
}
}
return value;
}
_loadData() {
const data = fs.readFileSync(this.DB_FILE_PATH, "utf8");
const lines = data.split("\n")
.filter(line => line.trim() !== "")
.filter(line => line.startsWith("#") || line.includes("="))
const originLines = [];
const parsedData = {};
lines.forEach(line => {
const isComment = line.startsWith("#");
if (isComment) {
originLines.push({type: "comment", value: line});
return;
}
//get key and value
const [key, ...valueArr] = line.split("=");
const value = valueArr.join("=").trim();
originLines.push({type: "property", key, value});
parsedData[key] = this._parseValue(value);
})
return {originLines, parsedData};
}
get(key) {
const {parsedData} = this._loadData();
return parsedData[key];
}
getAll() {
const {parsedData} = this._loadData();
return parsedData;
}
set(key, value) {
const {originLines} = this._loadData();
// If value is an object or array, stringify it
let storeValue = value;
if (
(typeof value === "object" && value !== null) ||
Array.isArray(value)
) {
storeValue = JSON.stringify(value);
}
const target = originLines.find(line => line.type === "property" && line.key === key);
if (target) {
target.value = storeValue;
} else {
originLines.push({type: "property", key, value: storeValue});
}
const data = originLines.map(line => line.type === "comment" ? line.value : `${line.key}=${line.value}`).join("\n");
fs.writeFileSync(this.DB_FILE_PATH, data);
}
delete(key) {
const {originLines} = this._loadData();
const data = originLines.filter(line => line.type === "property" && line.key !== key).join("\n");
fs.writeFileSync(this.DB_FILE_PATH, data);
}
}
module.exports = SimplePropertiesDB;