-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotes.js
More file actions
87 lines (71 loc) · 2.3 KB
/
notes.js
File metadata and controls
87 lines (71 loc) · 2.3 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
// -------------------- IMPORT FS MODULE ---------------------
const fs = require('fs')
// -------------------- IMPORT CHALK MODULE -------------------
const chalk = require('chalk')
// -------------------- GET NOTES -----------------------------
const readNotes = (title) => {
const notes = loadNotes()
const result = notes.find(note => note.title === title)
if (result) {
console.log(`${chalk.bgGreen.red(result.title)}`)
console.log(`${result.body}`)
} else {
console.log(chalk.bgRed("isn't possible find this note"));
}
}
// -------------------- LIST NOTES ----------------------------
const listNotes = () => {
const notes = loadNotes()
console.log(chalk.inverse('Your notes'))
const noteTitles = notes.filter(title => console.log(title.title))
return noteTitles
}
// -------------------- ADD NOTE -----------------------------
const addNote = (title, body) => {
const notes = loadNotes()
const duplicatedNote = notes.find(note => note.title === title)
if (!duplicatedNote) {
notes.push({
title: title,
body: body
})
saveNotes(notes)
console.log(chalk.black.bgGreen('New note added!'))
} else {
console.log(chalk.yellow.inverse("Note title taken!!!!! Choose another title name."))
}
}
// -------------------- DELETE NOTE -----------------------------
const removeNote = (title) => {
const notes = loadNotes();
const findTitle = notes.filter((note) => note.title === title)
if (findTitle.length > 0) {
const newArray = notes.filter((note) => note.title !== title)
saveNotes(newArray)
console.log(chalk.black.bgGreen('Note removed!'))
} else {
console.log(chalk.black.bgRed('No note found!'))
}
}
// --------------------- SAVE NOTES ------------------------------
const saveNotes = (notes) => {
const dataJSON = JSON.stringify(notes)
fs.writeFileSync('notes.json', dataJSON)
}
// -------------------- LOAD NOTES -----------------------------
const loadNotes = () => {
try {
const dataBuffer = fs.readFileSync('notes.json')
const jsonFormat = dataBuffer.toString()
return JSON.parse(jsonFormat)
} catch (e) {
return []
}
}
// -------------------- EXPORT FUNCTIONS -------------------------
module.exports = {
readNotes: readNotes,
addNote: addNote,
removeNote: removeNote,
listNotes: listNotes
}