1
0
CompleteNodeJS/notes-app/notes.js

75 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-08-11 18:15:16 +00:00
const fs = require('fs');
const chalk = require('chalk');
2019-08-11 18:56:43 +00:00
const addNote = (title, body) => {
2019-08-11 18:15:16 +00:00
const notes = loadNotes();
2019-08-11 19:35:09 +00:00
const duplicateNote = notes.find((note) => note.title === title);
2019-08-11 18:15:16 +00:00
2019-08-11 19:35:09 +00:00
if (!duplicateNote) {
2019-08-11 18:15:16 +00:00
notes.push({
title: title,
body: body
});
saveNotes(notes);
console.log(chalk.bgGreen.bold('New note added!'));
} else {
console.log(chalk.bgRed.bold('Note title taken!'));
}
}
2019-08-11 18:56:43 +00:00
const removeNote = (title) => {
2019-08-11 18:15:16 +00:00
const notes = loadNotes();
2019-08-11 18:56:43 +00:00
const notesToKeep = notes.filter((note) => note.title !== title);
2019-08-11 18:15:16 +00:00
if (notes.length > notesToKeep.length) {
console.log(chalk.bgGreen.bold('Note removed!'));
saveNotes(notesToKeep);
} else {
console.log(chalk.bgRed.bold('No note found!'));
}
}
2019-08-11 19:17:40 +00:00
const listNotes = () => {
const notes = loadNotes();
console.log(chalk.cyan.underline('Your notes:'));
notes.forEach((note) => {
console.log(note.title);
});
}
2019-08-11 18:56:43 +00:00
const saveNotes = (notes) => {
2019-08-11 18:15:16 +00:00
const dataJSON = JSON.stringify(notes);
fs.writeFileSync('notes.json', dataJSON);
}
2019-08-11 19:35:09 +00:00
const readNote = (title) => {
const notes = loadNotes();
const note = notes.find((note) => note.title === title);
if (note) {
console.log(chalk.cyan.underline(note.title));
console.log(note.body);
} else {
console.log(chalk.bgRed.bold('No note found!'));
}
}
2019-08-11 18:56:43 +00:00
const loadNotes = () => {
2019-08-11 18:15:16 +00:00
try {
const dataBuffer = fs.readFileSync('notes.json');
const dataJSON = dataBuffer.toString();
return JSON.parse(dataJSON);
} catch (e) {
return [];
}
}
module.exports = {
addNote: addNote,
2019-08-11 19:17:40 +00:00
removeNote: removeNote,
2019-08-11 19:35:09 +00:00
listNotes: listNotes,
readNote: readNote
2019-08-11 18:15:16 +00:00
}