notes.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const fs = require('fs');
  2. const Table = require('cli-table3');
  3. const chalk = require('chalk');
  4. const justify = require('justified');
  5. const fileName = 'notes-data.json';
  6. const printNote = (note) => {
  7. const title = chalk.inverse.bold.red;
  8. const body = chalk.bold.inverse.white;
  9. console.log(title(justify(note.title)));
  10. console.log(body(justify(note.body)));
  11. };
  12. const printNoteList = (notelist) => {
  13. var table = new Table({
  14. head: ['Title', 'Body'],
  15. colWidths: [25, 100]
  16. });
  17. notelist.forEach((note) => table.push([note.title, note.body]))
  18. console.log(table.toString());
  19. };
  20. const fetchNotes = () => {
  21. var notesString;
  22. try {
  23. notesString = fs.readFileSync(fileName);
  24. return JSON.parse(notesString);
  25. } catch (error) {
  26. return [];
  27. }
  28. };
  29. const saveNotes = (notes) => {
  30. fs.writeFileSync(fileName, JSON.stringify(notes));
  31. };
  32. const addNote = (title, body) => {
  33. var notes = fetchNotes(),
  34. note = { title, body };
  35. var duplicateNotes = notes.filter(note => note.title === title);
  36. if (duplicateNotes.length === 0) {
  37. notes.push(note);
  38. saveNotes(notes);
  39. return note;
  40. }
  41. };
  42. const removeNote = (title) => {
  43. var notes = fetchNotes();
  44. var filteredNotes = notes.filter(note => note.title !== title);
  45. saveNotes(filteredNotes);
  46. return notes.length !== filteredNotes.length;
  47. }
  48. const getNote = (title) => {
  49. let notes = fetchNotes();
  50. var note = notes.find(n => n.title === title);
  51. return note;
  52. };
  53. const getAll = () => {
  54. return fetchNotes();
  55. };
  56. module.exports = {
  57. addNote,
  58. getNote,
  59. getAll,
  60. removeNote,
  61. printNote,
  62. printNoteList
  63. };