温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-02 10:55:28 阅读:598 作者:jonson_jackson 栏目:开发技术
前端开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

原始文件

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');}

nodes.js

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协议 许可协议。转载请注明出处!

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

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×