Node.js纯记事本应用notes.js报错TypeError: notes.push is not a function求助
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:
- You return before parsing: The
return fs.readFileSync(...)line exits the function immediately, so theJSON.parsecode never runs. This meansfetchNotesreturns raw file content (a string or Buffer) instead of an array. - Undefined variable:
notesStringisn't defined anywhere—you never assign the result offs.readFileSyncto 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
catchblock returns an empty array—sonotesinaddNotewill always be an array, andnotes.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

