Node.js输入过滤:通讯录格式用户数据处理技术问询
Node.js Contact List Input Filtering & Processing Solution
Hey there! Let's walk through how to implement input filtering and processing for contact list data in Node.js, exactly as you need. I'll cover both common input scenarios and add necessary validation to keep things robust.
First, Let's Recap the Requirements
Just to make sure we're on the same page:
- The first line (or first segment) of user input is an integer, which we'll store in
noOfIterations— this tells us how many contact entries to expect- Each subsequent line (or pair of values) contains a contact's name (string) and a numeric phone number, separated by spaces
- Example valid input (either format works):
Or a single line (if the user inputs everything at once):2 sam 99912222 tom 111222222 sam 99912222 tom 11122222
Implementation Options
I'll share two practical solutions depending on how users will input the data.
1. Handling Interactive Line-by-Line Input (Terminal)
This is the most common scenario for user input in Node.js. We'll use the built-in readline module to handle interactive input, with validation at every step.
const readline = require('readline'); // Set up the readline interface for terminal input/output const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); let noOfIterations; const contacts = []; let lineNumber = 0; console.log('Enter your contact data:\n- First line: number of entries\n- Each next line: [name] [phone number]\n'); rl.on('line', (input) => { lineNumber++; // Process the first line (entry count) if (lineNumber === 1) { const parsedCount = parseInt(input.trim(), 10); // Validate it's a positive integer if (isNaN(parsedCount) || parsedCount <= 0) { console.error('❌ Error: First line must be a positive whole number!'); rl.close(); return; } noOfIterations = parsedCount; console.log(`Got it! Preparing to process ${noOfIterations} contact(s)\n`); } else { // Stop collecting once we have all entries if (contacts.length >= noOfIterations) { console.log('\n✅ All entries collected!'); rl.close(); return; } // Split input, handling multiple spaces between values const entryParts = input.trim().split(/\s+/); if (entryParts.length !== 2) { console.error('❌ Error: Each line must have exactly a name and phone number, separated by space!'); return; } const [name, phoneStr] = entryParts; // Validate phone number is numeric if (!/^\d+$/.test(phoneStr)) { console.error('❌ Error: Phone number must be a numeric value!'); return; } // Add valid contact to our list (convert phone to number type) contacts.push({ name: name.trim(), phone: parseInt(phoneStr, 10) }); // Auto-close once we hit the required entry count if (contacts.length === noOfIterations) { rl.close(); } } }); // Run cleanup and output results when input ends rl.on('close', () => { console.log('\n--- Processing Complete ---'); console.log(`Total entries specified: ${noOfIterations}`); console.log('Contacts:'); contacts.forEach((contact, idx) => { console.log(`${idx + 1}. Name: ${contact.name}, Phone: ${contact.phone}`); }); // Add your next steps here (save to DB, write to file, etc.) });
2. Handling Single-Line Input (e.g., Command Line Argument)
If users are passing all input as a single string (like a command line argument), we can parse the entire string at once with validation checks.
// Example input (could also come from process.argv[2] for CLI use) const inputString = '2 sam 99912222 tom 11122222'; // Split input into parts, ignoring extra spaces const inputParts = inputString.trim().split(/\s+/); // Parse and validate entry count const noOfIterations = parseInt(inputParts[0], 10); if (isNaN(noOfIterations) || noOfIterations <= 0) { throw new Error('First value must be a positive integer (number of entries)'); } // Validate we have enough values for the specified entries if (inputParts.length - 1 !== noOfIterations * 2) { throw new Error(`Input mismatch: Expected ${noOfIterations} entries (each with name + phone), but got invalid number of values`); } const contacts = []; // Loop through pairs of values to build contacts for (let i = 1; i < inputParts.length; i += 2) { const name = inputParts[i].trim(); const phoneStr = inputParts[i + 1].trim(); if (!/^\d+$/.test(phoneStr)) { throw new Error(`Invalid phone number: ${phoneStr} (must be numeric)`); } contacts.push({ name, phone: parseInt(phoneStr, 10) }); } // Output results console.log(`Total entries: ${noOfIterations}`); console.log('Processed Contacts:'); contacts.forEach((contact, idx) => { console.log(`${idx + 1}. ${contact.name} - ${contact.phone}`); });
Key Best Practices I Included
- Input Validation: Every step checks for valid data types and formats to avoid crashes or bad data
- Robust Splitting: Uses
split(/\s+/)instead ofsplit(' ')to handle multiple spaces or tabs between values - User Feedback: Clear error messages help users correct input mistakes quickly
- Type Safety: Converts phone numbers to numeric type as required, while keeping names as strings
内容的提问来源于stack exchange,提问作者Ashfaque Rifaye
相关产品推荐
相关产品推荐

