-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstudents.js
118 lines (86 loc) · 2.7 KB
/
students.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
var dbPath = 'db.json'
var fs = require('fs')
exports.show = function (callback) {
fs.readFile(dbPath , 'utf8' , function (err , data) {
if (err){
callback(null)
}
callback(null,JSON.parse(data).students)
})
}
exports.add = function ( student , callback) {
fs.readFile(dbPath , 'utf8' , function (err , data) {
if (err){
callback(null)
}
var students = JSON.parse(data).students
student.id = students[students.length - 1].id + 1
students.push(student)
// 把对象数据转换为字符串
var fileData = JSON.stringify({
students: students
})
// 把字符串保存到文件中
fs.writeFile(dbPath, fileData, function (err) {
if (err) {
// 错误就是把错误对象传递给它
return callback(err)
}
// 成功就没错,所以错误对象是 null
callback(null)
})
})
}
exports.editShow = function ( id , callback) {
fs.readFile(dbPath ,'utf8' ,function (err , data) {
if (err){
callback(err)
}
var students = JSON.parse(data).students
var student = students.find(function (item) {
return item.id == id
})
callback(null, student)
})
}
exports.edit = function ( student ,callback) {
fs.readFile(dbPath , 'utf8', function (err , data) {
if (err){
callback(err)
}
student.id = parseInt(student.id)
var students = JSON.parse(data).students
var student1 = students.find(function (item) {
return item.id == student.id
})
for(var key in student1){
student1[key] = student[key]
}
var fileData = JSON.stringify({students:students})
fs.writeFile(dbPath , fileData ,function (err) {
if (err){
return callback(err)
}
callback(null)
})
})
}
exports.delete = function (id , callback) {
fs.readFile(dbPath , 'utf8', function (err , data) {
if (err){
callback(err)
}
var students = JSON.parse(data).students
var index = students.findIndex(function (item) {
return item.id == id
})
students.splice(index,1)
var fileData = JSON.stringify({students:students})
fs.writeFile(dbPath , fileData , function (err) {
if (err){
return callback(err)
}
callback(null)
})
})
}