原始文件
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 |
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){ } 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" |
- 本文链接: https://dreamerjonson.com/2018/11/13/node-9-保存节点/
- 版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!
郑建勋(jonson)区块链工程师 & Web工程师
灾难总是接踵而至,这正是世间的常理。你以为只要哭诉一下,就会有谁来救你吗?如果失败了,就只能说明我不过是如此程度的男人。