如何将数组从一个函数传递给类中的另一个函数?

问题描述 投票:1回答:2

我正在尝试使用Node和Express来建立一个笔记应用程序。现在,保存的所有注释都将覆盖db.json文件中的内容。我正在尝试将db.json中已有的内容推送到一个空数组,推送最新的注释,然后使用该最终数组写入文件。有人对我在这里做错的事情有任何提示吗?谢谢。

  read() {
    return readFileAsync(path.join(__dirname, "db.json"), "utf8");
  }

  write(note) {
    return writeFileAsync(path.join(__dirname, "db.json"), JSON.stringify(note))
  }

  getNotes() {
    return this.read().then(notes => {
      var notesObject = JSON.parse(notes);
    });
  }

  addNote(note) {
    const newNoteArray = [];
    const { title, text } = note;
    if (!title || !text) {
      throw new Error("Note 'title' and 'text' cannot be blank");
    }
    const newNote = { title, text, id: uuidv1() };;
    return this.getNotes()
      .then(notes => {
        newNoteArray.push(notes);;
      })
      .then(newNoteArray.push(newNote))
      .then(this.write(newNoteArray));
  }
javascript node.js express
2个回答
0
投票

没有看到writeFileAsync函数的内容,我无法给出确切的答案,但是问题是您很可能会覆盖文件内容,而不是附加文件内容。 check out this quick tutorial on how to write and append contents to a file


0
投票

尝试一下:

 addNote(note) {

    const { title, text } = note;
    if (!title || !text) {
      throw new Error("Note 'title' and 'text' cannot be blank");
    }
    const newNote = { title, text, id: uuidv1() };
    return this.getNotes()
      .then(notes => {
        const newNoteArray = JSON.parse(notes);
        newNoteArray.push(newNote);
        return this.write(newNoteArray);
      })
  }

麻烦的是,notes是作为参数提供的,但这是文件的未解析内容。因此,您需要将其解析为newNoteArray,然后按下newNote,然后将其写出。

© www.soinside.com 2019 - 2024. All rights reserved.