NodeJS调用console.log(`${note.title}`)报undefined及空标题防覆盖问题
Hey there, let’s work through your two issues step by step:
1. Fixing the undefined Error in console.log(${note.title})
This error pops up because the note object you’re passing to logNote isn’t properly initialized, or your function is returning undefined instead of a valid note. Here’s how to resolve it:
Validate the note before logging
In yourapp.jsadd command logic, check if the note exists before callinglogNote. IfaddNotereturnsundefined(like when the title is invalid or duplicate), skip the logging step:if (command === 'add') { // Trim whitespace to catch empty/blank titles early const cleanTitle = argv.title ? argv.title.trim() : ''; const note = notes.addNote(cleanTitle, argv.body); if (note) { console.log('✅ Note created successfully!'); notes.logNote(note); } else { console.log('❌ Failed to create note: Title is empty or already exists'); } }Add safeguards in the
logNotefunction
Innotes.js, add a check to ensure the inputnoteis a valid object, and use fallback values to avoidundefinedin your logs:const logNote = (note) => { if (!note || typeof note !== 'object') { console.log('⚠️ Invalid note object received'); return; } console.log('\n--- Note Details ---'); console.log(`Title: ${note.title || 'No Title Provided'}`); console.log(`Body: ${note.body || 'No Body Provided'}\n`); }; module.exports = { logNote, addNote /* other functions */ };Ensure
addNotereturnsundefinedon failure
Double-check that youraddNotefunction innotes.jsreturnsundefinedwhen the title is invalid, so the caller can handle the failure properly.
2. Prevent Empty Titles from Overwriting notes-data.json
To stop empty/blank titles from messing with your JSON file, add validation at both the command line and core function levels:
Block empty titles in
app.js
Before callingaddNote, check if the title is empty or just whitespace—exit early if it is:if (command === 'add') { const cleanTitle = argv.title ? argv.title.trim() : ''; if (!cleanTitle) { console.log('❌ Error: Title cannot be empty or just whitespace!'); return; // Stop processing to avoid saving invalid data } // Proceed with adding the note const note = notes.addNote(cleanTitle, argv.body); // ... rest of your logic }Add a safety net in
notes.js'saddNote
Even if something slips past the command line check, add validation in the core function to ensure we never save a note with an empty title:const addNote = (title, body) => { // Validate title first const cleanTitle = title.trim(); if (!cleanTitle) { console.log('❌ Title cannot be empty'); return undefined; } const notes = fetchNotes(); const duplicateNote = notes.find(note => note.title === cleanTitle); if (!duplicateNote) { notes.push({ title: cleanTitle, body: body ? body.trim() : '' }); saveNotes(notes); return { title: cleanTitle, body }; } else { console.log('❌ Note title already exists'); return undefined; } }; // Helper functions (ensure these exist in your notes.js) const fetchNotes = () => { try { const notesString = fs.readFileSync('notes-data.json'); return JSON.parse(notesString); } catch (e) { return []; // Return empty array if file doesn't exist or is invalid } }; const saveNotes = (notes) => { fs.writeFileSync('notes-data.json', JSON.stringify(notes)); };
Now when you run node app.js add --title=" ", the title will be trimmed to an empty string, triggering the validation checks, and your notes-data.json will remain untouched.
内容的提问来源于stack exchange,提问作者daun jeruk

