0
0
NodejsConceptBeginner · 3 min read

What is process.stdin and process.stdout in Node.js Explained

process.stdin is a readable stream in Node.js that lets your program receive input from the keyboard or other input sources. process.stdout is a writable stream that sends output from your program to the console or terminal screen.
⚙️

How It Works

Think of process.stdin as a microphone for your Node.js program. It listens and waits for you to type something or send data. When you type on your keyboard, this stream captures that input so your program can use it.

On the other hand, process.stdout is like a speaker. It takes whatever your program wants to say and shows it on the screen or console. This way, your program can communicate back to you.

Both stdin and stdout are streams, which means they handle data piece by piece, making it easy to work with large or continuous input and output without waiting for everything at once.

💻

Example

This example reads a line from the keyboard and then writes it back to the console using process.stdin and process.stdout.

javascript
process.stdout.write('Please type something and press Enter:\n');

process.stdin.on('data', (data) => {
  const input = data.toString().trim();
  process.stdout.write(`You typed: ${input}\n`);
  process.exit();
});
Output
Please type something and press Enter: You typed: hello
🎯

When to Use

Use process.stdin when you want your Node.js program to accept input from the user or another program, like typing commands or feeding data. This is common in command-line tools or scripts that need user interaction.

Use process.stdout to display messages, results, or any output your program generates. It’s the standard way to show information in the terminal or to send data to other programs.

For example, you might build a quiz app that asks questions via stdin and shows scores with stdout, or a script that processes files and prints progress updates.

Key Points

  • process.stdin reads input as a stream, usually from the keyboard.
  • process.stdout writes output as a stream to the console.
  • Both are part of Node.js’s standard input/output system.
  • They allow interactive command-line programs to communicate with users.
  • Streams handle data efficiently, even for large or continuous input/output.

Key Takeaways

process.stdin lets your Node.js program receive input from the user or other sources.
process.stdout sends output from your program to the console or terminal screen.
Both are streams that handle data piece by piece for efficient input/output.
Use them to build interactive command-line tools and scripts.
They are essential for communicating with users in terminal-based Node.js apps.