app.js:
12345678910111213141516171819202122 | 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');} |
123456789101112131415161718192021222324252627282930313233343536373839404142 | 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"}] |
12345678910111213141516171819202122232425262728293031323334353637383940414243444546 | 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协议 许可协议。转载请注明出处!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。