首页 > 解决方案 > 类型错误:notes.push 不是函数

问题描述

我正在运行一段简单的代码,如下所示。

基本上我想读取'notes-data.json'中已经存在的数据,然后附加它。

node notes.js
console.log('Starting notes.js');

const fs =  require('fs');

var addNote = (title, body) => {
    var notesString = fs.readFileSync('playground/notes-data.json');
    var notes;
    notes = JSON.parse(notesString);
    var note = {
        title,
        body
    };
    notes.push(note);
    fs.writeFileSync('playground/notes-data.json', JSON.stringify(note));

};

addNote("Hi", "There");

module.exports = {
    addNote: addNote
};

预期:当我运行这个程序时,它必须添加“你好”。

实际:收到以下错误。

(base) prakashp:newproject2 prakashp$ node notes.js 
Starting notes.js
/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13
    notes.push(note);
          ^

TypeError: notes.push is not a function
    at addNote (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13:11)
    at Object.<anonymous> (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:18:1)
    at Module._compile (internal/modules/cjs/loader.js:721:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
    at executeUserCode (internal/bootstrap/node.js:499:15)
    at startMainThreadExecution (internal/bootstrap/node.js:436:3)

如果我评论以下行,我不会收到任何错误。

notes = JSON.parse(notesString);

请帮忙。

标签: node.js

解决方案


你的 json 文件应该有一个数组。这是您尝试在repl现场运行的工作代码。在 JSON Parse 之后,您的变量需要是一个数组,以便您可以push在其上使用方法。

我还发现了另一个错误,而不是保存note到您的 json 文件中,您应该保存notes. 因为您将再次将对象覆盖到文件中,并且会导致应用程序再次崩溃。使用下面的行。

fs.writeFileSync('playground/notes-data.json', JSON.stringify(notes));

示例代码


推荐阅读