我在一个notes.json
文件中有一个元素数组,我无法使用该filter
方法删除它们。
这是我从 json 文件中读取注释的方式:
const fs = require("fs");
const path = require("path");
const p = path.join(path.dirname(process.mainModule.filename),"data","notes.json");
// this function help me do fast code
const fastFunction = cb => {fs.readFile(p, (err, data) => {if (err) {return cb([]);} else {return cb(JSON.parse(data));}});};
我fastFunction
在另一个内部使用它removeById
,就像这样:
static removeById(id) {fastFunction(notes => {const deleteNote = notes.filter(n => n.id !== id);fs.writeFile(p, JSON.stringify(deleteNote), err => {if (err) {console.log(`Your Error Is: ${err}`);}});});}
最后,这是我尝试使用该removeById
功能的方式。
// here i used the function
const postDeleteNotes = (req, res, next) => {
const myId = req.body.removeById;Note.removeById(myId);res.redirect("/admin");
};
但是如果我删除笔记并尝试再次获取它们,它仍然存在。
我可能做错了什么?
我在这里找到了一个陌生的解决方案:
我改变这个:
n => n.id !== id
到这个:n => n.id != id
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句