1
0
CompleteNodeJS/notes-app/notes.js

61 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-08-11 18:15:16 +00:00
const fs = require('fs');
const chalk = require('chalk');
const getNotes = function() {
return 'Your notes...'
}
const addNote = function(title, body) {
const notes = loadNotes();
const duplicateNotes = notes.filter(function(note) {
return note.title === title;
});
if (duplicateNotes.length === 0) {
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!'));
}
}
const removeNote = function(title) {
const notes = loadNotes();
const notesToKeep = notes.filter(function(note) {
return note.title !== title;
});
if (notes.length > notesToKeep.length) {
console.log(chalk.bgGreen.bold('Note removed!'));
saveNotes(notesToKeep);
} else {
console.log(chalk.bgRed.bold('No note found!'));
}
}
const saveNotes = function(notes) {
const dataJSON = JSON.stringify(notes);
fs.writeFileSync('notes.json', dataJSON);
}
const loadNotes = function() {
try {
const dataBuffer = fs.readFileSync('notes.json');
const dataJSON = dataBuffer.toString();
return JSON.parse(dataJSON);
} catch (e) {
return [];
}
}
module.exports = {
getNotes: getNotes,
addNote: addNote,
removeNote: removeNote
}