You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js纯记事本应用notes.js报错TypeError: notes.push is not a function求助

Fixing TypeError: notes.push is not a function in Your Node.js Note App

Hey there, let's tackle that error you're seeing in your notes app. The root cause is a bug in your fetchNotes function—let's break it down and fix it step by step.

What's Going Wrong?

Look at your current fetchNotes code:

var fetchNotes = () => {
 try{
 // this part will allow us to keep adding notes without
 // removing whats already there
 return fs.readFileSync('notes-data.json');
 notes = JSON.parse(notesString);
 }catch(e){
 return [];
 }
};

There are two critical issues here:

  1. You return before parsing: The return fs.readFileSync(...) line exits the function immediately, so the JSON.parse code never runs. This means fetchNotes returns raw file content (a string or Buffer) instead of an array.
  2. Undefined variable: notesString isn't defined anywhere—you never assign the result of fs.readFileSync to it.

When addNote calls fetchNotes(), it gets a non-array value, so trying to run notes.push(note) throws the "not a function" error.

The Fixed fetchNotes Function

Replace your fetchNotes with this corrected version:

var fetchNotes = () => {
 try{
 // Read the file content and store it in a variable
 const notesString = fs.readFileSync('notes-data.json');
 // Parse the string into a JavaScript array and return it
 return JSON.parse(notesString);
 }catch(e){
 // If the file doesn't exist or is invalid, return an empty array
 return [];
 }
};

Why This Works

  • Now we first read the file content into notesString, then parse it into an array before returning it.
  • If the file doesn't exist (or has invalid JSON), the catch block returns an empty array—so notes in addNote will always be an array, and notes.push() will work as expected.

Quick Bonus Fix

I noticed in your app.js you call notes.removeNotes(argv.title , argv.body);, but your removeNotes function only accepts a title parameter. You might want to update either the function definition or the call to match, to avoid confusion later.

内容的提问来源于stack exchange,提问作者Mohamed Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:15:03