如何将多行输入通过管道传递给Node.js程序?
Parsing Multi-Line Poker Input with Node.js Readline
Hey there! Let's fix up your Node.js code to properly parse that multi-line poker input you're working with. Right now your code just logs each line as it comes in, but we need to map that input into the communityCards and evalCards arrays you've already defined. Here's a polished, functional version with explanations:
Improved Code
const readline = require('readline'); function parsePokerInput() { return new Promise((resolve) => { const lineReader = readline.createInterface({ input: process.stdin, output: process.stdout }); let lineCount = 0; let communityCards = []; let evalCards = []; // Show prompt to indicate we're ready for input lineReader.prompt(); lineReader.on('line', (line) => { // Clean up the input line and split into individual elements const inputParts = line.trim().split(/\s+/); if (lineCount === 0) { // First line is always the community cards communityCards = inputParts; console.log(`✅ Parsed community cards: ${communityCards.join(', ')}`); } else { // Subsequent lines follow [Player Name, Card1, Card2] format if (inputParts.length >= 3) { const playerData = { name: inputParts[0], cards: inputParts.slice(1) }; evalCards.push(playerData); console.log(`✅ Added player ${playerData.name}: ${playerData.cards.join(', ')}`); } else { console.warn(`⚠️ Skipping invalid line: "${line}" — expected format: [Player Name] [Card1] [Card2]`); } } lineCount++; lineReader.prompt(); // Keep the prompt active for next input line }); lineReader.on('close', () => { // Resolve with the structured data when input is done resolve({ communityCards, playerHands: evalCards }); }); }); } // Example usage to test the parser parsePokerInput() .then((parsedData) => { console.log('\n🎉 Final Parsed Results:'); console.log('Community Cards:', parsedData.communityCards); console.log('Player Hands:', parsedData.playerHands); }) .catch((error) => { console.error('❌ Error parsing input:', error); });
Key Improvements & Explanations
- Structured Parsing: We split the input into community cards (first line) and player hands (all subsequent lines) to match your input format.
- Input Sanitization: Using
trim()andsplit(/\s+/)handles extra spaces or leading/trailing whitespace in your input lines. - Validation: We check that player lines have at least 3 elements (name + two cards) to avoid malformed data.
- Promise Wrapper: Encapsulates the readline logic in a Promise so you can easily handle the parsed data once input is complete (matches your original
resolve(evalCards)intent). - User Feedback: Clear console logs let you see what's being parsed as you input each line.
How to Use
- Run the script with
node your-file-name.js - Paste or type your input lines one by one:
KS AD 3H 7C TD
John 9H 7S
Sam AC KH
Becky JD QC - When you're done entering lines, press Ctrl+D (on Unix/macOS) or Ctrl+Z (on Windows) to trigger the
closeevent. The parsed results will print out.
内容的提问来源于stack exchange,提问作者Amit Merchant
相关产品推荐
相关产品推荐

