nodejs渐入佳境[9]-保存节点到json文件

原始文件

app.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const yargs = require('yargs');
const nodes = require('./nodes.js')
console.log('Start app.');

console.log(process.argv);

console.log('yargs',yargs.argv);
const argv = yargs.argv;
var command = process.argv[2];

if(command==='add'){
 nodes.addNote(argv.title,argv.body);
}else if(command === 'list'){
 nodes.getAll();

}else if(command =='read'){
 nodes.getNote(argv.title);
}else if(command=='remove'){
 nodes.removeNote(argv.title);
}else{
 console.log('command not find');
}

nodes.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
console.log('start nodes.js');
const fs = require('fs');
var addNote = (title,body)=>{
 var notes = [];
 var note = {
     title,
     body
 };

 try{
   //读取json文件,读出来是string
   var notesString = fs.readFileSync('notes-data.json');
   // string转换为json对象
   notes = JSON.parse(notesString);
 }catch(e){

 }
 //增加
 notes.push(note);
 //保存
 fs.writeFileSync('notes-data.json',JSON.stringify(notes));
}

var getAll = ()=>{
console.log('Get All notes');
};

var getNote = (title)=>{

 console.log('getting note',title);
};

var removeNote = (title)=>{
 console.log('Removing note',title);
};

module.exports = {
   addNote,
   getAll,
   getNote,
   removeNote
};

打开控制台,在当前目录下输入:

1
> node app.js add --title="buy book2" --body="jonson"

将节点添加到notes-data.json文件中.

再次输入:

1
> node app.js add --title="buy book2" --body="jonson"

notes-data.json:

1
[{"title":"buy book2","body":"jonson"},{"title":"buy book2","body":"jonson"}]

改进 不添加重复的节点

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
console.log('start nodes.js');
const fs = require('fs');
var addNote = (title,body)=>{
 var notes = [];
 var note = {
     title,
     body
 };

 try{
   var notesString = fs.readFileSync('notes-data.json');
   notes = JSON.parse(notesString);
 }catch(e){

 }

 //筛选出相同的节点
 var duplicateNotes = notes.filter((note)=>note.title===title);
 //没有相同的节点
 if(duplicateNotes.length ===0){
   notes.push(note);
   fs.writeFileSync('notes-data.json',JSON.stringify(notes));
 }


}

var getAll = ()=>{
console.log('Get All notes');
};

var getNote = (title)=>{

 console.log('getting note',title);
};

var removeNote = (title)=>{
 console.log('Removing note',title);
};

module.exports = {
   addNote,
   getAll,
   getNote,
   removeNote
};

再次输入不会添加节点:

1
> node app.js add --title="buy book2" --body="jonson"

image.png

猜你喜欢

转载自blog.51cto.com/13784902/2324494