0
0
Node.jsframework~5 mins

process.stdin and process.stdout in Node.js

Choose your learning style9 modes available
Introduction

These let your Node.js program read what a user types and show messages on the screen. They help your program talk with people.

When you want to ask the user a question and get their answer.
When you want to show messages or results in the terminal.
When you want to build simple command-line tools that interact with users.
When you want to read input from the keyboard in real time.
When you want to write output that the user can see immediately.
Syntax
Node.js
process.stdin.on('data', (input) => {
  // handle input here
});

process.stdout.write('message');

process.stdin listens for user input from the keyboard.

process.stdout.write() prints messages to the terminal without adding a new line automatically.

Examples
This listens for what the user types and then prints it back with a message.
Node.js
process.stdin.on('data', (input) => {
  console.log('You typed:', input.toString());
});
This prints a message asking the user to type, without moving to a new line.
Node.js
process.stdout.write('Hello! Please type something: ');
This example reads input as text, exits if the user types 'exit', or repeats what they said.
Node.js
process.stdin.setEncoding('utf8');
process.stdin.on('data', (input) => {
  if(input.trim() === 'exit') {
    process.stdout.write('Goodbye!\n');
    process.exit();
  } else {
    process.stdout.write(`You said: ${input}`);
  }
});
Sample Program

This program asks the user for their name, then greets them with a message and ends.

Node.js
process.stdout.write('What is your name? ');
process.stdin.setEncoding('utf8');
process.stdin.on('data', (input) => {
  const name = input.trim();
  process.stdout.write(`Hello, ${name}! Nice to meet you.\n`);
  process.exit();
});
OutputSuccess
Important Notes

Remember to call process.stdin.setEncoding('utf8') to get readable text instead of raw bytes.

Use process.exit() to stop the program after you finish reading input.

process.stdout.write() does not add a new line automatically, so add \n if you want one.

Summary

process.stdin reads what the user types.

process.stdout shows messages on the screen.

They help make interactive command-line programs.