Redirect stdin to a Node.js script

📦 GitHub->command line.
✨ The Prompt Phrase
echo "data" | node script.js

💻 Code Preview

📦 All-in-One Code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Redirect stdin to a Node.js script - Interactive Tutorial</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700;900&family=Fira+Code:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #0a0e27;
            --bg-secondary: #151932;
            --bg-card: #1e2139;
            --accent-purple: #a855f7;
            --accent-blue: #3b82f6;
            --accent-green: #10b981;
            --accent-red: #ef4444;
            --accent-yellow: #f59e0b;
            --accent-pink: #ec4899;
            --accent-cyan: #06b6d4;
            --accent-indigo: #6366f1;
            --text-primary: #f8fafc;
            --text-secondary: #94a3b8;
            --gradient-pipe: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
            --gradient-flow: linear-gradient(135deg, #3b82f6 0%, #6366f1 100%);
            --shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            line-height: 1.6;
            overflow-x: hidden;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .progress-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 5px;
            background: var(--bg-secondary);
            z-index: 1000;
        }

        .progress-bar {
            height: 100%;
            background: var(--gradient-pipe);
            width: 0%;
            transition: width 0.3s ease;
        }

        .hero {
            text-align: center;
            padding: 100px 20px;
            background: var(--gradient-pipe);
            position: relative;
            overflow: hidden;
            border-radius: 0 0 50px 50px;
        }

        .hero::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="2" fill="white" opacity="0.1"/></svg>');
            animation: float 20s linear infinite;
        }

        @keyframes float {
            from { transform: translateY(0); }
            to { transform: translateY(-100px); }
        }

        .hero-content {
            position: relative;
            z-index: 1;
        }

        .pipe-icon {
            font-size: 5rem;
            margin-bottom: 20px;
            animation: pipeFlow 3s ease-in-out infinite;
        }

        @keyframes pipeFlow {
            0%, 100% { transform: translateX(0); }
            50% { transform: translateX(20px); }
        }

        .command-display {
            display: inline-block;
            background: rgba(0, 0, 0, 0.4);
            padding: 25px 40px;
            border-radius: 15px;
            font-family: 'Fira Code', monospace;
            font-size: 1.5rem;
            margin: 30px 0;
            border: 3px solid rgba(255, 255, 255, 0.3);
            animation: pulse 2s ease-in-out infinite;
            color: white;
            font-weight: 600;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }

        .hero h1 {
            font-size: 3.5rem;
            font-weight: 900;
            margin-bottom: 20px;
            color: white;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .hero p {
            font-size: 1.4rem;
            opacity: 0.95;
            color: white;
        }

        .section {
            margin: 60px 0;
        }

        .section-title {
            font-size: 2.5rem;
            margin-bottom: 30px;
            background: var(--gradient-pipe);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            display: inline-block;
            font-weight: 700;
        }

        .card {
            background: var(--bg-card);
            border-radius: 20px;
            padding: 40px;
            margin: 30px 0;
            box-shadow: var(--shadow);
            border: 1px solid rgba(255, 255, 255, 0.05);
            transition: transform 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .code-block {
            background: #1e1e1e;
            border-radius: 15px;
            padding: 25px;
            margin: 20px 0;
            font-family: 'Fira Code', monospace;
            position: relative;
        }

        .code-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .terminal-dots {
            display: flex;
            gap: 6px;
        }

        .terminal-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }

        .dot-red { background: #ff5f56; }
        .dot-yellow { background: #ffbd2e; }
        .dot-green { background: #27c93f; }

        .copy-btn {
            background: var(--accent-purple);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }

        .copy-btn:hover {
            background: var(--accent-blue);
            transform: scale(1.05);
        }

        .copy-btn.copied {
            background: var(--accent-green);
        }

        pre {
            margin: 0;
            overflow-x: auto;
        }

        code {
            color: #e0e0e0;
            font-size: 0.95rem;
            line-height: 1.8;
        }

        .code-comment { color: #6a9955; }
        .code-string { color: #ce9178; }
        .code-keyword { color: #569cd6; }
        .code-pipe { color: #06b6d4; font-weight: 600; }
        .code-echo { color: #10b981; font-weight: 600; }

        .steps {
            counter-reset: step-counter;
        }

        .step {
            background: var(--bg-secondary);
            border-radius: 15px;
            padding: 30px;
            margin: 20px 0;
            position: relative;
            padding-left: 100px;
            transition: all 0.3s ease;
        }

        .step:hover {
            background: var(--bg-card);
            transform: translateX(10px);
        }

        .step::before {
            counter-increment: step-counter;
            content: counter(step-counter);
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            width: 60px;
            height: 60px;
            background: var(--gradient-pipe);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.8rem;
            font-weight: 900;
            color: white;
        }

        .step h3 {
            color: var(--accent-cyan);
            margin-bottom: 10px;
            font-size: 1.5rem;
        }

        .feature-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 25px;
            margin: 30px 0;
        }

        .feature-card {
            background: var(--bg-secondary);
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }

        .feature-card:hover {
            border-color: var(--accent-cyan);
            transform: translateY(-10px);
        }

        .feature-icon {
            font-size: 3.5rem;
            margin-bottom: 15px;
        }

        .feature-title {
            font-weight: 600;
            color: var(--accent-cyan);
            margin-bottom: 10px;
            font-size: 1.3rem;
        }

        .demo-container {
            background: var(--bg-secondary);
            border-radius: 20px;
            padding: 40px;
            margin: 30px 0;
        }

        .flow-diagram {
            display: flex;
            justify-content: space-around;
            align-items: center;
            margin: 30px 0;
            flex-wrap: wrap;
            gap: 20px;
        }

        .flow-box {
            background: var(--bg-card);
            padding: 30px;
            border-radius: 15px;
            border: 2px solid var(--accent-cyan);
            text-align: center;
            min-width: 150px;
        }

        .flow-arrow {
            font-size: 3rem;
            color: var(--accent-cyan);
            animation: arrowPulse 2s ease-in-out infinite;
        }

        @keyframes arrowPulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.2); }
        }

        .terminal {
            background: #1e1e1e;
            border-radius: 15px;
            padding: 20px;
            font-family: 'Fira Code', monospace;
            min-height: 250px;
            margin: 20px 0;
            overflow-y: auto;
            max-height: 500px;
        }

        .terminal-line {
            margin: 10px 0;
        }

        .terminal-prompt {
            color: var(--accent-green);
        }

        .demo-button {
            background: var(--gradient-pipe);
            color: white;
            border: none;
            padding: 15px 40px;
            border-radius: 50px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            margin: 10px;
        }

        .demo-button:hover {
            transform: scale(1.05);
            box-shadow: 0 10px 30px rgba(6, 182, 212, 0.4);
        }

        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .tab {
            padding: 12px 24px;
            background: var(--bg-secondary);
            border: none;
            border-radius: 10px;
            color: var(--text-primary);
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 1rem;
        }

        .tab:hover {
            background: var(--bg-card);
        }

        .tab.active {
            background: var(--gradient-pipe);
            color: white;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .accordion-header {
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            background: var(--bg-secondary);
            border-radius: 12px;
            margin: 15px 0;
            transition: all 0.3s ease;
        }

        .accordion-header:hover {
            background: var(--bg-card);
        }

        .accordion-icon {
            transition: transform 0.3s ease;
            font-size: 1.2rem;
        }

        .accordion-icon.active {
            transform: rotate(180deg);
        }

        .accordion-content {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }

        .accordion-content.active {
            max-height: 2000px;
        }

        .accordion-body {
            padding: 20px;
            background: var(--bg-secondary);
            border-radius: 12px;
            margin-top: 5px;
        }

        .tip, .warning, .success, .info {
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }

        .tip {
            background: rgba(59, 130, 246, 0.1);
            border-left: 4px solid var(--accent-blue);
        }

        .tip::before { content: '💡 '; font-size: 1.5rem; }

        .warning {
            background: rgba(239, 68, 68, 0.1);
            border-left: 4px solid var(--accent-red);
        }

        .warning::before { content: '⚠️ '; font-size: 1.5rem; }

        .success {
            background: rgba(16, 185, 129, 0.1);
            border-left: 4px solid var(--accent-green);
        }

        .success::before { content: '✅ '; font-size: 1.5rem; }

        .info {
            background: rgba(236, 72, 153, 0.1);
            border-left: 4px solid var(--accent-pink);
        }

        .info::before { content: '🔍 '; font-size: 1.5rem; }

        .quiz-container {
            background: var(--bg-card);
            border-radius: 20px;
            padding: 40px;
            margin: 30px 0;
        }

        .quiz-question {
            margin: 30px 0;
        }

        .quiz-question h3 {
            color: var(--accent-purple);
            margin-bottom: 20px;
            font-size: 1.3rem;
        }

        .quiz-options {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .quiz-option {
            background: var(--bg-secondary);
            padding: 20px;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }

        .quiz-option:hover {
            border-color: var(--accent-blue);
            transform: translateX(10px);
        }

        .quiz-option.correct {
            border-color: var(--accent-green);
            background: rgba(16, 185, 129, 0.1);
        }

        .quiz-option.incorrect {
            border-color: var(--accent-red);
            background: rgba(239, 68, 68, 0.1);
        }

        .quiz-feedback {
            margin-top: 15px;
            padding: 15px;
            border-radius: 10px;
            display: none;
        }

        .quiz-feedback.show {
            display: block;
        }

        .quiz-feedback.correct {
            background: rgba(16, 185, 129, 0.1);
            border-left: 4px solid var(--accent-green);
        }

        .quiz-feedback.incorrect {
            background: rgba(239, 68, 68, 0.1);
            border-left: 4px solid var(--accent-red);
        }

        .cheat-sheet {
            background: var(--gradient-pipe);
            border-radius: 20px;
            padding: 40px;
            margin: 30px 0;
            color: white;
        }

        .cheat-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }

        .cheat-item {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            padding: 20px;
            border-radius: 15px;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .cheat-item h4 {
            color: white;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .cheat-item code {
            background: rgba(0, 0, 0, 0.3);
            padding: 4px 8px;
            border-radius: 5px;
            font-size: 0.9rem;
            color: white;
        }

        .highlight {
            color: var(--accent-yellow);
            font-weight: 600;
        }

        .footer {
            text-align: center;
            padding: 40px 20px;
            background: var(--bg-secondary);
            margin-top: 80px;
            border-radius: 20px;
        }

        .footer p {
            color: var(--text-secondary);
            margin: 10px 0;
        }

        .badge {
            display: inline-block;
            padding: 6px 12px;
            background: var(--gradient-pipe);
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
            margin: 5px;
        }

        .confetti {
            position: fixed;
            width: 10px;
            height: 10px;
            background: var(--accent-cyan);
            animation: confetti-fall 3s linear forwards;
            z-index: 9999;
        }

        @keyframes confetti-fall {
            to {
                transform: translateY(100vh) rotate(360deg);
                opacity: 0;
            }
        }

        @media (max-width: 768px) {
            .hero h1 { font-size: 2rem; }
            .command-display { font-size: 1rem; padding: 15px 20px; }
            .section-title { font-size: 1.8rem; }
            .card { padding: 25px; }
            .step { padding-left: 80px; }
            .step::before { width: 50px; height: 50px; font-size: 1.5rem; }
            .flow-diagram { flex-direction: column; }
        }
    </style>
</head>
<body>
    <div class="progress-container">
        <div class="progress-bar" id="progressBar"></div>
    </div>

    <div class="hero">
        <div class="hero-content">
            <div class="pipe-icon">⚡</div>
            <h1>Master Piping to Node!</h1>
            <div class="command-display">echo "data" | node script.js</div>
            <p>Stream data into Node.js! 🌊</p>
        </div>
    </div>

    <div class="container">
        <!-- What Is It -->
        <section class="section">
            <h2 class="section-title">🤔 What Is This Command?</h2>
            <div class="card">
                <p style="font-size: 1.2rem; margin-bottom: 20px;">
                    This command <span class="highlight">pipes data from echo into a Node.js script</span> through stdin (standard input) - it's like sending a message through a tube directly into your program! ⚡
                </p>
                <p style="margin-bottom: 20px;">
                    Think of it like a water pipe! 🚰 The <code>echo</code> command produces output (water), the pipe <code>|</code> connects them, and your Node.js script receives it as input. Instead of typing data manually or reading from a file, you can stream data directly into your script!
                </p>
                <div class="info">
                    <strong>Breaking It Down:</strong>
                    <ul style="margin-left: 30px; margin-top: 10px; line-height: 2;">
                        <li><code class="code-echo">echo "data"</code> - Outputs text to stdout</li>
                        <li><code class="code-pipe">|</code> - Pipe operator (connects commands)</li>
                        <li><code>node script.js</code> - Runs Node.js script</li>
                        <li>Data flows: echo → pipe → Node stdin</li>
                        <li>Script reads from <code>process.stdin</code></li>
                    </ul>
                </div>
                <div style="margin-top: 30px;">
                    <h3 style="color: var(--accent-pink); margin-bottom: 15px;">What's stdin? 🔍</h3>
                    <p>stdin (standard input) is a stream where programs receive input data. By default it's your keyboard, but with pipes, it can be output from another command! It's one of three standard streams: stdin (input), stdout (output), and stderr (errors).</p>
                </div>
            </div>
        </section>

        <!-- Flow Diagram -->
        <section class="section">
            <h2 class="section-title">📊 How Data Flows</h2>
            <div class="card">
                <h3 style="margin-bottom: 20px; text-align: center;">The Pipe Pipeline! 🌊</h3>
                <div class="flow-diagram">
                    <div class="flow-box">
                        <div style="font-size: 3rem; margin-bottom: 10px;">📢</div>
                        <h4 style="color: var(--accent-cyan);">echo "data"</h4>
                        <p style="color: var(--text-secondary); font-size: 0.9rem;">Produces output</p>
                    </div>
                    <div class="flow-arrow">→</div>
                    <div class="flow-box">
                        <div style="font-size: 3rem; margin-bottom: 10px;">🚰</div>
                        <h4 style="color: var(--accent-cyan);">| (pipe)</h4>
                        <p style="color: var(--text-secondary); font-size: 0.9rem;">Connects streams</p>
                    </div>
                    <div class="flow-arrow">→</div>
                    <div class="flow-box">
                        <div style="font-size: 3rem; margin-bottom: 10px;">📥</div>
                        <h4 style="color: var(--accent-cyan);">process.stdin</h4>
                        <p style="color: var(--text-secondary); font-size: 0.9rem;">Node receives</p>
                    </div>
                </div>
                <div class="success" style="margin-top: 30px;">
                    <strong>Result:</strong> Data flows seamlessly from one command to another!
                </div>
            </div>
        </section>

        <!-- Why Use It -->
        <section class="section">
            <h2 class="section-title">✨ Why Use Pipes?</h2>
            <div class="card">
                <div class="feature-grid">
                    <div class="feature-card">
                        <div class="feature-icon">🔗</div>
                        <div class="feature-title">Chain Commands</div>
                        <p style="color: var(--text-secondary);">Connect multiple tools!</p>
                    </div>
                    <div class="feature-card">
                        <div class="feature-icon">🚀</div>
                        <div class="feature-title">Efficient</div>
                        <p style="color: var(--text-secondary);">Stream processing!</p>
                    </div>
                    <div class="feature-card">
                        <div class="feature-icon">🎯</div>
                        <div class="feature-title">Flexible</div>
                        <p style="color: var(--text-secondary);">Any data source!</p>
                    </div>
                    <div class="feature-card">
                        <div class="feature-icon">💾</div>
                        <div class="feature-title">No Files Needed</div>
                        <p style="color: var(--text-secondary);">Direct streaming!</p>
                    </div>
                    <div class="feature-card">
                        <div class="feature-icon">🔄</div>
                        <div class="feature-title">Real-time</div>
                        <p style="color: var(--text-secondary);">Process as it comes!</p>
                    </div>
                    <div class="feature-card">
                        <div class="feature-icon">🛠️</div>
                        <div class="feature-title">Unix Philosophy</div>
                        <p style="color: var(--text-secondary);">Do one thing well!</p>
                    </div>
                </div>
            </div>
        </section>

        <!-- How It Works -->
        <section class="section">
            <h2 class="section-title">⚙️ How Does It Work?</h2>
            <div class="card">
                <div class="steps">
                    <div class="step">
                        <h3>Step 1: Echo Produces Output</h3>
                        <p>echo command outputs "data" to stdout (standard output).</p>
                    </div>
                    <div class="step">
                        <h3>Step 2: Pipe Connects Streams</h3>
                        <p>The | operator redirects echo's stdout to the next command's stdin.</p>
                    </div>
                    <div class="step">
                        <h3>Step 3: Node Starts</h3>
                        <p>Node.js launches and runs script.js.</p>
                    </div>
                    <div class="step">
                        <h3>Step 4: Script Reads stdin</h3>
                        <p>Script accesses data through process.stdin stream.</p>
                    </div>
                    <div class="step">
                        <h3>Step 5: Process Data</h3>
                        <p>Script processes the incoming data as it arrives.</p>
                    </div>
                    <div class="step">
                        <h3>Step 6: Output Results</h3>
                        <p>Script can output to stdout for further piping! 🎉</p>
                    </div>
                </div>
            </div>
        </section>

        <!-- Live Demo -->
        <section class="section">
            <h2 class="section-title">🎮 Interactive Demo</h2>
            <div class="demo-container">
                <div style="margin-bottom: 30px; text-align: center;">
                    <h4 style="margin-bottom: 15px;">See Piping in Action! ⚡</h4>
                    <button class="demo-button" onclick="simulatePipe()">
                        <span>🚰</span>
                        <span>Simple Pipe</span>
                    </button>
                    <button class="demo-button" onclick="simulateJSON()">
                        <span>📦</span>
                        <span>JSON Pipe</span>
                    </button>
                    <button class="demo-button" onclick="simulateChain()">
                        <span>🔗</span>
                        <span>Command Chain</span>
                    </button>
                </div>
                <div class="terminal" id="terminal">
                    <div class="terminal-line">
                        <span class="terminal-prompt">$</span>
                        <span style="color: var(--text-secondary);"> Ready to pipe data...</span>
                    </div>
                </div>
            </div>
        </section>

        <!-- Code Breakdown -->
        <section class="section">
            <h2 class="section-title">💻 Usage Examples</h2>
            <div class="card">
                <div class="tabs">
                    <button class="tab active" onclick="switchTab('basic')">Basic Example</button>
                    <button class="tab" onclick="switchTab('json')">JSON Data</button>
                    <button class="tab" onclick="switchTab('files')">File Processing</button>
                    <button class="tab" onclick="switchTab('advanced')">Advanced</button>
                </div>
                <div id="basic" class="tab-content active">
                    <h3 style="color: var(--accent-pink); margin-bottom: 15px;">Basic stdin Reading</h3>
                    <div class="code-block">
                        <div class="code-header">
                            <div class="terminal-dots">
                                <div class="terminal-dot dot-red"></div>
                                <div class="terminal-dot dot-yellow"></div>
                                <div class="terminal-dot dot-green"></div>
                            </div>
                            <button class="copy-btn" onclick="copyCode('basic-code')">📋 Copy</button>
                        </div>
                        <pre><code id="basic-code"><span class="code-comment">// script.js - Read from stdin</span>
process.stdin.on(<span class="code-string">'data'</span>, (data) => {
  console.log(<span class="code-string">'Received:'</span>, data.toString());
});

<span class="code-comment">// Usage in terminal:</span>
echo <span class="code-string">"Hello World"</span> | node script.js
<span class="code-comment"># Output: Received: Hello World</span>

<span class="code-comment">// Alternative: read all data at once</span>
<span class="code-keyword">let</span> input = <span class="code-string">''</span>;
process.stdin.on(<span class="code-string">'data'</span>, chunk => input += chunk);
process.stdin.on(<span class="code-string">'end'</span>, () => {
  console.log(<span class="code-string">'Complete input:'</span>, input);
});</code></pre>
                    </div>
                    <div class="success" style="margin-top: 15px;">
                        <strong>Result:</strong> Script receives and processes piped data!
                    </div>
                </div>
                <div id="json" class="tab-content">
                    <h3 style="color: var(--accent-pink); margin-bottom: 15px;">Processing JSON Data</h3>
                    <div class="code-block">
                        <div class="code-header">
                            <div class="terminal-dots">
                                <div class="terminal-dot dot-red"></div>
                                <div class="terminal-dot dot-yellow"></div>
                                <div class="terminal-dot dot-green"></div>
                            </div>
                            <button class="copy-btn" onclick="copyCode('json-code')">📋 Copy</button>
                        </div>
                        <pre><code id="json-code"><span class="code-comment">// process-json.js</span>
<span class="code-keyword">let</span> jsonData = <span class="code-string">''</span>;

process.stdin.on(<span class="code-string">'data'</span>, chunk => {
  jsonData += chunk;
});

process.stdin.on(<span class="code-string">'end'</span>, () => {
  <span class="code-keyword">try</span> {
    <span class="code-keyword">const</span> data = JSON.parse(jsonData);
    console.log(<span class="code-string">'Name:'</span>, data.name);
    console.log(<span class="code-string">'Age:'</span>, data.age);
  } <span class="code-keyword">catch</span> (err) {
    console.error(<span class="code-string">'Invalid JSON'</span>, err);
  }
});

<span class="code-comment">// Usage:</span>
echo <span class="code-string">'{"name":"Alice","age":30}'</span> | node process-json.js
<span class="code-comment"># Output:</span>
<span class="code-comment"># Name: Alice</span>
<span class="code-comment"># Age: 30</span></code></pre>
                    </div>
                    <div class="tip" style="margin-top: 15px;">
                        <strong>Pro Tip:</strong> Always handle JSON parsing errors when reading from stdin!
                    </div>
                </div>
                <div id="files" class="tab-content">
                    <h3 style="color: var(--accent-pink); margin-bottom: 15px;">File Processing</h3>
                    <div class="code-block">
                        <div class="code-header">
                            <div class="terminal-dots">
                                <div class="terminal-dot dot-red"></div>
                                <div class="terminal-dot dot-yellow"></div>
                                <div class="terminal-dot dot-green"></div>
                            </div>
                            <button class="copy-btn" onclick="copyCode('files-code')">📋 Copy</button>
                        </div>
                        <pre><code id="files-code"><span class="code-comment">// line-counter.js - Count lines from stdin</span>
<span class="code-keyword">let</span> lineCount = <span class="code-keyword">0</span>;

process.stdin.on(<span class="code-string">'data'</span>, (chunk) => {
  lineCount += chunk.toString().split(<span class="code-string">'\n'</span>).length - <span class="code-keyword">1</span>;
});

process.stdin.on(<span class="code-string">'end'</span>, () => {
  console.log(<span class="code-string">`Total lines: ${lineCount}`</span>);
});

<span class="code-comment">// Usage with files:</span>
cat file.txt | node line-counter.js

<span class="code-comment">// Usage with command output:</span>
ls -la | node line-counter.js

<span class="code-comment">// Chain multiple commands:</span>
cat data.txt | grep <span class="code-string">"error"</span> | node line-counter.js</code></pre>
                    </div>
                </div>
                <div id="advanced" class="tab-content">
                    <h3 style="color: var(--accent-pink); margin-bottom: 15px;">Advanced Patterns</h3>
                    <div class="code-block">
                        <div class="code-header">
                            <div class="terminal-dots">
                                <div class="terminal-dot dot-red"></div>
                                <div class="terminal-dot dot-yellow"></div>
                                <div class="terminal-dot dot-green"></div>
                            </div>
                            <button class="copy-btn" onclick="copyCode('advanced-code')">📋 Copy</button>
                        </div>
                        <pre><code id="advanced-code"><span class="code-comment">// transform.js - Transform and pipe to next command</span>
process.stdin
  .on(<span class="code-string">'data'</span>, (chunk) => {
    <span class="code-keyword">const</span> transformed = chunk
      .toString()
      .toUpperCase()
      .trim();
    process.stdout.write(transformed + <span class="code-string">'\n'</span>);
  });

<span class="code-comment">// Chain transformations:</span>
echo <span class="code-string">"hello"</span> | node transform.js | node another-script.js

<span class="code-comment">// Using readline for line-by-line processing:</span>
<span class="code-keyword">const</span> readline = require(<span class="code-string">'readline'</span>);

<span class="code-keyword">const</span> rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: <span class="code-keyword">false</span>
});

rl.on(<span class="code-string">'line'</span>, (line) => {
  console.log(<span class="code-string">`Processing: ${line}`</span>);
});

<span class="code-comment">// With async/await (Node 16+):</span>
<span class="code-keyword">const</span> { stdin } = process;
<span class="code-keyword">for await</span> (<span class="code-keyword">const</span> chunk <span class="code-keyword">of</span> stdin) {
  console.log(<span class="code-string">'Chunk:'</span>, chunk.toString());
}</code></pre>
                    </div>
                </div>
            </div>
        </section>

        <!-- Common Mistakes -->
        <section class="section">
            <h2 class="section-title">❌ Common Mistakes</h2>
            <div class="card">
                <div class="accordion">
                    <div class="accordion-item">
                        <div class="accordion-header" onclick="toggleAccordion(this)">
                            <span><strong>1. Not Handling 'end' Event</strong></span>
                            <span class="accordion-icon">▼</span>
                        </div>
                        <div class="accordion-content">
                            <div class="accordion-body">
                                <div class="warning">
                                    <strong>Problem:</strong> Script exits before processing all data
                                </div>
                                <div class="success" style="margin-top: 15px;">
                                    <strong>Solution:</strong> Always listen for 'end' event to know when input is complete!
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="accordion-item">
                        <div class="accordion-header" onclick="toggleAccordion(this)">
                            <span><strong>2. Forgetting toString()</strong></span>
                            <span class="accordion-icon">▼</span>
                        </div>
                        <div class="accordion-content">
                            <div class="accordion-body">
                                <div class="warning">
                                    <strong>Problem:</strong> Data comes as Buffer, not string
                                </div>
                                <div class="success" style="margin-top: 15px;">
                                    <strong>Solution:</strong> Use <code>chunk.toString()</code> to convert Buffer to string!
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="accordion-item">
                        <div class="accordion-header" onclick="toggleAccordion(this)">
                            <span><strong>3. Not Setting Encoding</strong></span>
                            <span class="accordion-icon">▼</span>
                        </div>
                        <div class="accordion-content">
                            <div class="accordion-body">
                                <div class="warning">
                                    <strong>Problem:</strong> Character encoding issues with special characters
                                </div>
                                <div class="success" style="margin-top: 15px;">
                                    <strong>Solution:</strong> Set encoding: <code>process.stdin.setEncoding('utf8')</code>!
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="accordion-item">
                        <div class="accordion-header" onclick="toggleAccordion(this)">
                            <span><strong>4. Blocking Operations</strong></span>
                            <span class="accordion-icon">▼</span>
                        </div>
                        <div class="accordion-content">
                            <div class="accordion-body">
                                <div class="warning">
                                    <strong>Problem:</strong> Using synchronous operations blocks the stream
                                </div>
                                <div class="success" style="margin-top: 15px;">
                                    <strong>Solution:</strong> Use async operations to keep stream flowing!
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Pro Tips -->
        <section class="section">
            <h2 class="section-title">🚀 Pro Tips</h2>
            <div class="card">
                <div class="tip">
                    <strong>Set encoding early</strong> - Use <code>process.stdin.setEncoding('utf8')</code> to avoid Buffer conversion!
                </div>
                <div class="tip">
                    <strong>Use readline module</strong> - For line-by-line processing, readline is cleaner!
                </div>
                <div class="tip">
                    <strong>Handle errors</strong> - Always add error handlers to stdin stream!
                </div>
                <div class="tip">
                    <strong>Check for TTY</strong> - Use <code>process.stdin.isTTY</code> to detect if input is piped!
                </div>
                <div class="tip">
                    <strong>Async iteration</strong> - Node 16+ supports <code>for await...of</code> on stdin!
                </div>
                <div class="tip">
                    <strong>Backpressure</strong> - Handle <code>process.stdout.write()</code> return value for large data!
                </div>
                <div class="tip">
                    <strong>Testing</strong> - Test with <code>echo</code>, files, and command output!
                </div>
            </div>
        </section>

        <!-- Quiz -->
        <section class="section">
            <h2 class="section-title">🎯 Knowledge Check Quiz</h2>
            <div class="quiz-container">
                <p style="margin-bottom: 30px; font-size: 1.1rem;">Test your understanding! 🧠</p>
                <div class="quiz-question">
                    <h3>Question 1: What does the | operator do?</h3>
                    <div class="quiz-options">
                        <div class="quiz-option" onclick="checkAnswer(this, false, 1)">A) Performs bitwise OR</div>
                        <div class="quiz-option" onclick="checkAnswer(this, true, 1)">B) Pipes stdout to stdin of next command</div>
                        <div class="quiz-option" onclick="checkAnswer(this, false, 1)">C) Separates commands</div>
                    </div>
                    <div class="quiz-feedback" id="feedback1"></div>
                </div>
                <div class="quiz-question">
                    <h3>Question 2: How do you read from stdin in Node.js?</h3>
                    <div class="quiz-options">
                        <div class="quiz-option" onclick="checkAnswer(this, false, 2)">A) console.read()</div>
                        <div class="quiz-option" onclick="checkAnswer(this, true, 2)">B) process.stdin.on('data', callback)</div>
                        <div class="quiz-option" onclick="checkAnswer(this, false, 2)">C) fs.readStdin()</div>
                    </div>
                    <div class="quiz-feedback" id="feedback2"></div>
                </div>
                <div class="quiz-question">
                    <h3>Question 3: What type is stdin data by default?</h3>
                    <div class="quiz-options">
                        <div class="quiz-option" onclick="checkAnswer(this, false, 3)">A) String</div>
                        <div class="quiz-option" onclick="checkAnswer(this, true, 3)">B) Buffer</div>
                        <div class="quiz-option" onclick="checkAnswer(this, false, 3)">C) Array</div>
                    </div>
                    <div class="quiz-feedback" id="feedback3"></div>
                </div>
                <div id="quizScore" style="margin-top: 30px; padding: 20px; background: var(--bg-secondary); border-radius: 12px; display: none;">
                    <h3 style="color: var(--accent-green); font-size: 1.5rem;">🎉 Quiz Complete!</h3>
                    <p id="scoreText" style="font-size: 1.2rem; margin-top: 10px;"></p>
                </div>
            </div>
        </section>

        <!-- Summary Card -->
        <section class="section">
            <h2 class="section-title">📚 Quick Reference</h2>
            <div class="cheat-sheet">
                <h3 style="margin-bottom: 20px; font-size: 2rem;">Piping Cheat Sheet! 🔖</h3>
                <div class="cheat-grid">
                    <div class="cheat-item">
                        <h4>⚡ Basic Syntax</h4>
                        <p><code>echo "data" | node script.js</code></p>
                        <p style="font-size: 0.85rem; margin-top: 5px;">Pipe to Node</p>
                    </div>
                    <div class="cheat-item">
                        <h4>📥 Read Data</h4>
                        <p><code>process.stdin.on('data', fn)</code></p>
                        <p style="font-size: 0.85rem; margin-top: 5px;">Listen for input</p>
                    </div>
                    <div class="cheat-item">
                        <h4>🏁 End Event</h4>
                        <p><code>process.stdin.on('end', fn)</code></p>
                        <p style="font-size: 0.85rem; margin-top: 5px;">Input complete</p>
                    </div>
                    <div class="cheat-item">
                        <h4>🔤 Set Encoding</h4>
                        <p><code>stdin.setEncoding('utf8')</code></p>
                        <p style="font-size: 0.85rem; margin-top: 5px;">Auto-convert</p>
                    </div>
                    <div class="cheat-item">
                        <h4>📝 Line-by-Line</h4>
                        <p><code>readline.createInterface</code></p>
                        <p style="font-size: 0.85rem; margin-top: 5px;">Process lines</p>
                    </div>
                    <div class="cheat-item">
                        <h4>🔗 Chain Commands</h4>
                        <p><code>cmd1 | node | cmd2</code></p>
                        <p style="font-size: 0.85rem; margin-top: 5px;">Multiple pipes</p>
                    </div>
                    <div class="cheat-item">
                        <h4>📄 From Files</h4>
                        <p><code>cat file.txt | node script.js</code></p>
                        <p style="font-size: 0.85rem; margin-top: 5px;">File input</p>
                    </div>
                    <div class="cheat-item">
                        <h4>✅ Check TTY</h4>
                        <p><code>process.stdin.isTTY</code></p>
                        <p style="font-size: 0.85rem; margin-top: 5px;">Detect piping</p>
                    </div>
                </div>
            </div>
        </section>

        <!-- Footer -->
        <div class="footer">
            <h2 style="font-size: 2rem; margin-bottom: 20px; color: var(--accent-pink);">🎉 Congratulations!</h2>
            <p style="font-size: 1.2rem; margin-bottom: 20px;">You now understand <strong>piping to Node.js</strong>! 🚀</p>
            <div style="margin: 30px 0;">
                <span class="badge">⚡ Pipe Master</span>
                <span class="badge">🌊 Stream Pro</span>
                <span class="badge">🚀 Unix Expert</span>
            </div>
            <p style="color: var(--text-secondary); margin-top: 30px;">Generated by <strong>AI Prompt Dictionary</strong> 🤖</p>
            <p style="color: var(--text-secondary); font-size: 0.9rem;">Made with ❤️ for developers learning Node.js</p>
        </div>
    </div>

    <script>
        // Progress bar
        window.addEventListener('scroll', () => {
            const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
            const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
            const scrolled = (winScroll / height) * 100;
            document.getElementById('progressBar').style.width = scrolled + '%';
        });

        // Copy to clipboard
        function copyCode(codeId) {
            const code = document.getElementById(codeId).innerText;
            navigator.clipboard.writeText(code).then(() => {
                event.target.textContent = '✅ Copied!';
                event.target.classList.add('copied');
                setTimeout(() => {
                    event.target.textContent = '📋 Copy';
                    event.target.classList.remove('copied');
                }, 2000);
            });
        }

        // Tab switching
        function switchTab(tabName) {
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');
        }

        // Accordion toggle
        function toggleAccordion(header) {
            const content = header.nextElementSibling;
            const icon = header.querySelector('.accordion-icon');
            content.classList.toggle('active');
            icon.classList.toggle('active');
        }

        // Simulate simple pipe
        function simulatePipe() {
            const terminal = document.getElementById('terminal');
            terminal.innerHTML = '<div class="terminal-line"><span class="terminal-prompt">$</span> echo "Hello World" | node script.js</div>';
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-cyan); margin-top: 10px;">📢 echo outputs: "Hello World"</div>';
            }, 500);
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-blue); margin-top: 10px;">🚰 Pipe redirects to stdin...</div>';
            }, 1200);
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-green); margin-top: 10px;">📥 Node.js receives data:</div>';
                terminal.innerHTML += '<div style="color: var(--text-secondary); margin-left: 20px;">process.stdin.on(\'data\', ...)</div>';
            }, 2000);
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-green); margin-top: 10px; font-weight: 600;">✅ Output: Received: Hello World</div>';
                terminal.innerHTML += '<div style="color: var(--accent-cyan); margin-top: 5px;">🎉 Data successfully piped!</div>';
                createConfetti();
            }, 3000);
        }

        // Simulate JSON pipe
        function simulateJSON() {
            const terminal = document.getElementById('terminal');
            terminal.innerHTML = '<div class="terminal-line"><span class="terminal-prompt">$</span> echo \'{"name":"Alice","age":30}\' | node process-json.js</div>';
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-cyan); margin-top: 10px;">📦 Sending JSON data through pipe...</div>';
            }, 500);
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-blue); margin-top: 10px;">🔄 Node.js collecting data chunks...</div>';
                terminal.innerHTML += '<div style="color: var(--text-secondary); margin-left: 20px;">Chunk 1: {"name":"Alice"</div>';
                terminal.innerHTML += '<div style="color: var(--text-secondary); margin-left: 20px;">Chunk 2: ,"age":30}</div>';
            }, 1500);
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-yellow); margin-top: 10px;">🔍 Parsing JSON...</div>';
            }, 2500);
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-green); margin-top: 10px; font-weight: 600;">✅ Parsed successfully!</div>';
                terminal.innerHTML += '<div style="color: var(--text-secondary); margin-left: 20px; margin-top: 5px;">Name: Alice</div>';
                terminal.innerHTML += '<div style="color: var(--text-secondary); margin-left: 20px;">Age: 30</div>';
                terminal.innerHTML += '<div style="color: var(--accent-cyan); margin-top: 10px;">🎯 JSON data processed!</div>';
                createConfetti();
            }, 3500);
        }

        // Simulate command chain
        function simulateChain() {
            const terminal = document.getElementById('terminal');
            terminal.innerHTML = '<div class="terminal-line"><span class="terminal-prompt">$</span> cat data.txt | node transform.js | node output.js</div>';
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-cyan); margin-top: 10px;">📄 cat reads file: "hello world"</div>';
            }, 500);
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-blue); margin-top: 10px;">🚰 First pipe → transform.js</div>';
                terminal.innerHTML += '<div style="color: var(--text-secondary); margin-left: 20px;">Transforms to: "HELLO WORLD"</div>';
            }, 1500);
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-purple); margin-top: 10px;">🚰 Second pipe → output.js</div>';
                terminal.innerHTML += '<div style="color: var(--text-secondary); margin-left: 20px;">Adds prefix: "Result: HELLO WORLD"</div>';
            }, 2500);
            setTimeout(() => {
                terminal.innerHTML += '<div style="color: var(--accent-green); margin-top: 10px; font-weight: 600;">✅ Final output: Result: HELLO WORLD</div>';
                terminal.innerHTML += '<div style="color: var(--accent-cyan); margin-top: 5px;">🔗 Multiple commands chained successfully!</div>';
                createConfetti();
            }, 3500);
        }

        // Quiz system
        let quizScore = 0;
        let questionsAnswered = 0;

        function checkAnswer(element, isCorrect, questionNum) {
            const options = element.parentElement.querySelectorAll('.quiz-option');
            options.forEach(opt => opt.style.pointerEvents = 'none');
            const feedback = document.getElementById('feedback' + questionNum);
            if (isCorrect) {
                element.classList.add('correct');
                feedback.className = 'quiz-feedback correct show';
                feedback.innerHTML = '<strong>🎉 Correct!</strong> Great job!';
                quizScore++;
                createConfetti();
            } else {
                element.classList.add('incorrect');
                feedback.className = 'quiz-feedback incorrect show';
                feedback.innerHTML = '<strong>❌ Not quite!</strong> Review the material and try again!';
            }
            questionsAnswered++;
            if (questionsAnswered === 3) {
                setTimeout(() => {
                    document.getElementById('quizScore').style.display = 'block';
                    document.getElementById('scoreText').textContent = `You scored ${quizScore}/3! ${quizScore === 3 ? '🏆 Perfect!' : quizScore === 2 ? '👍 Good job!' : '💪 Keep learning!'}`;
                }, 1000);
            }
        }

        // Confetti animation
        function createConfetti() {
            const colors = ['#06b6d4', '#3b82f6', '#6366f1', '#10b981', '#a855f7'];
            for (let i = 0; i < 50; i++) {
                const confetti = document.createElement('div');
                confetti.className = 'confetti';
                confetti.style.left = Math.random() * window.innerWidth + 'px';
                confetti.style.background = colors[Math.floor(Math.random() * colors.length)];
                confetti.style.animationDuration = (2 + Math.random() * 2) + 's';
                document.body.appendChild(confetti);
                setTimeout(() => confetti.remove(), 4000);
            }
        }
    </script>
</body>
</html>
Live Preview