/
appUtil.js
83 lines (59 loc) · 1.68 KB
/
appUtil.js
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
const fs = require('fs')
const chalk = require('chalk')
const success = chalk.green.bold.inverse
const failed = chalk.red.bold.inverse
const addNote = (title, body) => {
const noteArr = loadNote()
const duplicateNote = noteArr.find((note) => note.title === title)
if(!duplicateNote){
noteArr.push({
title: title,
body: body
})
saveNote(noteArr)
console.log(success('Success!! Note Saved Successfully'))
}
else{
console.log(failed('Failed!! Please Enter a new note title'))
}
}
const removeNote = (title) => {
const noteArr = loadNote()
const updatedNote = noteArr.filter(function(theNote){
return theNote.title != title
})
saveNote(updatedNote)
if(noteArr.length === updatedNote.length){
console.log(failed('Failed!! No notes Deleted'))
}else{
console.log(success('Success!! Note deleted'))
}
}
const readNotes = function(title) {
debugger
const noteArray = loadNote()
const myNote = noteArray.find(function(note){
return note.title === title
})
if(myNote){
console.log(success('Success!! The body of the note is: '))
console.log(myNote.body)
}else{
console.log(failed('Failed!! No notes found'))
}
}
const loadNote = () => {
try {
const data = fs.readFileSync('./notes.json').toString()
const noteArray = JSON.parse(data)
return noteArray
}catch{
return []
}
}
const saveNote = (note) => {fs.writeFileSync('./notes.json', JSON.stringify(note))}
module.exports = {
addNote: addNote,
removeNote: removeNote,
readNotes: readNotes
}