1. 程式人生 > >nodejs漸入佳境[9]-儲存節點到json檔案

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