NodeJs注意应用程序删除功能不起作用?

时间:2018-03-18 10:18:38

标签: arrays node.js

我正在构建一个Nodejs Note应用程序,我对此非常新,所以这里删除功能不起作用,删除数组中的所有内容,我只想删除标题 app.js和note.js有两个文件。

这是app.js文件的内容

if (command === "add") {
    var note = notes.addNote(argv.title, argv.body);
    if (note) {
        console.log("Note created");
        console.log("__");
        console.log(`Title: ${note.title}`);
        console.log(`Body: ${note.body}`);
    } else {
        console.log("The title has already exist")
    }
} else if (command === "delete") {
    var noteRemoved = notes.delNote(argv.title)
    var message = noteRemoved ? "Note has been removed" : "Note not found";
    console.log(message)
}

这里是note.js内容

var fetchNotes = function () {
    try {
        var noteString = fs.readFileSync("notes-data.json")
        return JSON.parse(noteString);
    } catch (e) {
        return [];
    }
};

var saveNotes = function (notes) {
    fs.writeFileSync("notes-data.json", JSON.stringify(notes));
};

var addNote = function (title, body) {
    var notes = fetchNotes();
    var note = {
        title,
        body
    };

    var duplicateNotes = notes.filter(function (note) {
        return note.title === title;

    });

    if (duplicateNotes.length === 0) {
        notes.push(note);
        saveNotes(notes);
        return note;
    };
}

var delNote = function (title) {
    var notes = fetchNotes();
    var filteredNotes = notes.filter(function (note) {
        note.title !== title;
    });
    saveNotes(filteredNotes);
    return notes.length !== filteredNotes.length
}

2 个答案:

答案 0 :(得分:2)

你错过了delNote过滤函数中的return语句

var filteredNotes = notes.filter(function (note) {
    return note.title !== title;
});

或者我们可以使用es6语法:

const filteredNotes = notes.filter(note => note.title !== title);

答案 1 :(得分:1)

您需要在delNote函数中添加return note.title !== title;