-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.js
66 lines (56 loc) · 1.4 KB
/
node.js
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
const { error } = require('console')
const fs = require ('fs')
const filePath = "./tasks.json"
const command = process.argv[2]
const argument = process.argv[3]
const loadTask = () => {
try {
const dataBuffer = fs.readFileSync(filePath) // fs.readFileSync(filePath , 'utf-
const dataJSON = dataBuffer.toString();
return JSON.parse(dataJSON)
} catch (error) {
return []
}
}
const savetask = (tasks) => {
const dataJSON = JSON.stringify(tasks)
fs.writeFileSync(filePath , dataJSON)
}
//Typing CMD 'init' /'add'
const addTask = (task) => {
const tasks = loadTask()
tasks.push(task)
savetask(tasks)
console.log(`${task} added to the list`);
}
//Typing CMD 'list'
const listTask = () => {
const tasks = loadTask()
tasks.forEach((task , index) => {
console.log(`${index+1}.>> ${task}`);
})
}
//Typing CMD 'remove'
const deleteTask = () => {
const tasks = loadTask()
const index = parseInt(argument)-1
if (index >= tasks.length || index < 0){
console.log("Invalid index");
return
}
const task = tasks.splice(index,1)
savetask(tasks)
console.log(`${task} this command removed from the list`);
}
if (command ==="init"){
addTask(argument)
}
else if (command ==="list"){
listTask()
}
else if (command ==="remove"){
deleteTask()
}
else{
console.log("Command not found",error);
}