diff --git a/lib/store.js b/lib/store.js index 661b4b2..8ed2423 100644 --- a/lib/store.js +++ b/lib/store.js @@ -6,8 +6,13 @@ const FILE = path.join(__dirname, "..", "notes.json"); function load() { try { return JSON.parse(fs.readFileSync(FILE, "utf8")); - } catch { - return { nextId: 1, notes: [] }; + } catch (e) { + // Only treat ENOENT (file not found) as OK + if (e.code === 'ENOENT') { + return { nextId: 1, notes: [] }; + } + // Re-throw other errors (corruption, permissions, etc) + throw e; } } @@ -45,4 +50,15 @@ function search(term) { return matches(load().notes, term); } -module.exports = { all, add, remove, search, matches }; +function edit(id, text) { + const data = load(); + const note = data.notes.find((n) => n.id === id); + if (!note){ + return false; + } + note.text = text; + save(data); + return true; +} + +module.exports = { all, add, remove, search, matches, edit }; diff --git a/notes.js b/notes.js index df64a18..20a93f9 100644 --- a/notes.js +++ b/notes.js @@ -39,6 +39,18 @@ function main() { } break; } + case "edit": { + const id = Number(rest[0]); + const text = rest.slice(1).join(" ").trim(); + const ok = store.edit(id, text); + if (ok){ + console.log(`Updated note #${id}`); + } + else{ + console.log("Note #${id} not found"); + } + break; + } case "delete": { const id = Number(rest[0]); const ok = store.remove(id); @@ -46,7 +58,7 @@ function main() { break; } default: - console.log("Commands: add | list | search | delete "); + console.log("Commands: add | list | search | edit | delete "); console.log(`(Session locks after ${config.SESSION_TIMEOUT_MINUTES} minutes of inactivity.)`); } }