Why This Matters
Every useful program communicates with the outside world. When you read a file, accept keyboard input, display results on screen, or send data over a network, you are performing I/O operations. I/O is the bridge between your program's internal logic and everything external: disks, screens, keyboards, and networks.
Understanding I/O explains why some programs feel instant while others stall. It reveals why a web server can handle thousands of requests, and why reading a large file can freeze your entire application if done carelessly.
Define Terms
Visual Model
The full process at a glance. Click Start tour to walk through each step.
Data flows from your program through the kernel and device drivers before reaching hardware.
Code Example
// Standard output (stdout)
console.log("Hello, world!"); // writes to stdout
console.error("Oops!"); // writes to stderr
// Reading and writing files (Node.js)
const fs = require("fs");
// Synchronous (blocking) file read
const data = fs.readFileSync("input.txt", "utf8");
console.log(data);
// Writing to a file
fs.writeFileSync("output.txt", "Hello from Node!");
// Piping: reading stdin line by line
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
// Transform input and write to stdout
process.stdout.write(chunk.toUpperCase());
});
// In a terminal: echo "hello" | node script.js
// Output: HELLOInteractive Experiment
Try these exercises:
- Run
echo "hello world" | node -e \"process.stdin.on('data', d => process.stdout.write(d.toString().toUpperCase()))"in a terminal and observe the pipe in action. - Write a small script that reads from a file, transforms the content (e.g., reverses each line), and writes the result to a new file.
- Compare the speed of writing 10,000 small writes vs. one large buffered write. Time both approaches.
Quick Quiz
Coding Challenge
Write a function called `pipeTransform` that takes an array of strings (simulating lines of input) and a transform function. It should return a new array where each line has been passed through the transform. This models how UNIX pipes work: data flows from one program through a transform to the next.
Real-World Usage
I/O operations underpin nearly every application:
- Web servers read HTTP requests from network sockets and write responses back. Node.js and Nginx excel because of their non-blocking I/O models.
- Databases perform disk I/O to read and write data. Buffer pools in memory cache frequently accessed pages to reduce disk reads.
- UNIX philosophy is built on pipes: small programs connected via stdin/stdout. Commands like
cat file.txt | grep "error" | wc -lchain I/O between processes. - Log systems write stderr output to log files. Tools like
teeduplicate output to both a file and the terminal simultaneously.