import fs from "node:fs";
import path from "node:path";
import os from "node:os";
const DEFAULT_DATA_DIR = path.join(os.homedir(), ".todo-cli");
const DEFAULT_DATA_FILE = "todos.json";
* Create a store backed by a JSON file.
* @param {object} [opts]
* @param {string} [opts.dataDir] Directory for the data file.
* @param {string} [opts.dataFile] Filename inside the data dir.
*/
export function createStore(opts = {}) {
const dataDir = opts.dataDir ?? DEFAULT_DATA_DIR;
const dataFile = opts.dataFile ?? DEFAULT_DATA_FILE;
const filePath = path.join(dataDir, dataFile);
function ensureDir() {
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
}
function load() {
if (!fs.existsSync(filePath)) return [];
try {
const raw = fs.readFileSync(filePath, "utf8");
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function save(todos) {
ensureDir();
fs.writeFileSync(filePath, JSON.stringify(todos, null, 2), "utf8");
}
return { load, save, filePath };
}