Course contentsShow
← Node.js
Lesson 572 of 1,9806. Networking and HTTP FundamentalsFree lesson

Zero-Copy File Serving

Use system-level sendfile operations to stream files directly from disk to the network interface.

In this lesson, you will learn how to bypass the CPU and memory bottlenecks of standard file reading by using Zero-Copy File Serving.

The Traditional Bottleneck

When you serve a file using standard methods like fs.readFile, the process follows a long, resource-heavy path:

  1. The kernel reads data from the disk into its own memory space (the page cache).
  2. The kernel copies that data into your Node.js application's memory (the user-space buffer).
  3. The Node.js application then copies that same data back into the kernel's network buffer so the network card can transmit it.

This "middle-man" approach creates unnecessary CPU cycles and consumes your application's heap memory, which can lead to performance degradation when serving large files to many users.

The Zero-Copy Solution

Zero-copy operations, specifically the system-level sendfile call, eliminate these unnecessary data copies. Instead of moving data into your application, the kernel is instructed to stream data directly from the disk cache to the network socket. Your Node.js process stays out of the way, acting only as the conductor of the operation.

In Node.js, we leverage this through the stream API. When you pipe a file stream to an HTTP response object, Node.js automatically detects that it can perform a high-performance transfer:

const fs = require('fs');
const http = require('http');

http.createServer((req, res) => {
  // Creating a read stream triggers the optimized sendfile path
  const fileStream = fs.createReadStream('large-video.mp4');
  
  // Directly pipe from disk to the network socket
  fileStream.pipe(res);
}).listen(3000);

By piping the stream, you ensure your server memory remains light and stable, even if you are serving a file that is significantly larger than the available RAM on your server. Because the CPU isn't busy copying bytes back and forth, you free up resources to handle other tasks like Authentication Interceptors or Request Rate Limiting, which you learned about earlier.

Key Takeaway: Zero-copy file serving shifts the burden of data movement from your application's memory to the kernel, allowing for high-performance streaming with minimal CPU and RAM overhead.