Advertisement
bai_onzi

file-reader.js

Jul 8th, 2023
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* eslint-disable linebreak-style */
  2. /* eslint-disable no-unused-vars */
  3. /* eslint-disable linebreak-style */
  4. /* eslint-disable consistent-return */
  5. /* eslint-disable no-shadow */
  6. import fs from 'fs';
  7. import { dirname, join } from 'path';
  8. import { fileURLToPath } from 'url';
  9.  
  10. const __dirname = dirname(fileURLToPath(import.meta.url));
  11.  
  12. console.log(__dirname);
  13.  
  14. export class FileHandler {
  15.   read(filename = '') {
  16.     filename = join(__dirname, '..', filename);
  17.  
  18.     fs.readFile('src/data/tasks.all.json', { encoding: 'utf-8' }, (err, data) => {
  19.       if (err) {
  20.         return console.error(err.message);
  21.       }
  22.  
  23.       const allTasks = JSON.parse(data);
  24.       const idTask = allTasks.tasks.map(task => [task.id, task.name, task.status]);
  25.    
  26.       for (let i = 0; i < idTask.length; i++) {
  27.         if (idTask[i].includes('done')) {
  28.           fs.writeFile('src/data/tasks.done.json', JSON.stringify(idTask[i]), { encoding: 'utf-8' }, (err) => {
  29.             if (err) {
  30.               return console.error(`Something went wrong... ${err.message}`);
  31.             }
  32.           });
  33.         }else{
  34.           fs.writeFile('src/data/tasks.pending.json', JSON.stringify(idTask[i]), { encoding: 'utf-8' }, (err) => {
  35.             if (err) {
  36.               return console.error(`Something went wrong... ${err.message}`);
  37.             }
  38.           });
  39.         }
  40.       }
  41.       console.log('Tasks were sorted')
  42.     });
  43.   }
  44.   write(filename = '', data = '') {
  45.     filename = join(__dirname, '..', filename);
  46.    
  47.     fs.writeFile('src/data/tasks.all.json', JSON.stringify(data), { encoding: 'utf-8' }, (err) => {
  48.       if (err) {
  49.         return console.error(`Error with adding data ${err.message}`)
  50.       }
  51.       console.log(`New task was added in src/data/tasks.all.json!`)
  52.     })
  53.   }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement