-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotes.js
More file actions
102 lines (86 loc) · 2.45 KB
/
Copy pathNotes.js
File metadata and controls
102 lines (86 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//Notes functions are defined here
const fs = require('fs')
require('validator')
const color = require('chalk')
//getting notes from file
const getNotes = () => {
try {
const notesBuffer = fs.readFileSync('notes.json')
jsonNotes = notesBuffer.toString()
return JSON.parse(jsonNotes)
} catch (e) {
return []
}
}
//adding notes to the file
const addNotes = (title, body) => {
try {
const notes = getNotes()
// check whether a duplicate note exist or not
const duplicateNote = notes.filter((note) => note.title === title)
if (duplicateNote.length !== 0) {
console.log(color.red('the title ' + title + ' already exists'))
} else {
notes.push({
title: title,
body: body
})
saveNotes(notes)
console.log(color.green("Note successfully added!!"))
}
} catch (e) {
console.log(e)
}
}
// Remove a note from the file
const removeNotes = (title) => {
try {
notes = getNotes()
const notesToKeep = notes.filter((note) => note.title !== title)
if (notes.length > notesToKeep.length) {
saveNotes(notesToKeep)
console.log(color.green("Note successfully removed!!"))
} else {
console.log(color.red.inverse('Note not found'))
}
} catch (e) {
console.log(color.red("Error removing the notes."))
}
}
// List all the notes
const listNotes = () => {
const notes = getNotes()
try {
console.log(color.green("Your Notes: "))
notes.forEach((note) => {
console.log(color.blue(note.title))
});
} catch (e) {
console.log(color.red("An error occured: \n" + e))
}
}
// Save notes to the file
const saveNotes = (notes) => {
jsonNotes = JSON.stringify(notes)
//write into the file
fs.writeFileSync('notes.json', jsonNotes)
return true
}
// Read notes based on the title
const readNote = (title) => {
const notes = getNotes()
const desiredNote = notes.find((note) => note.title === title)
if (desiredNote) {
console.log(color.blue.inverse(desiredNote.title) + "\n\n")
console.log(color.white(desiredNote.body))
} else {
console.log(color.red("No Notes found!!"))
}
}
module.exports = {
addnote: addNotes,
getnote: getNotes,
removenote: removeNotes,
listnote: listNotes,
readnote: readNote
}