Node.js › File System & File Processing
How would you copy a large file efficiently in Node.js, and what's the difference between fs.copyFile() and manually piping streams?
IntermediateAnswer
fs.copyFile() (or fs.cp() for directories) performs an efficient, often OS-optimized file copy in a single call, suitable for most use cases. Manually piping a read stream to a write stream (fs.createReadStream(src).pipe(fs.createWriteStream(dest))) offers more control -- useful if you need to transform the data during the copy (like compressing it), but generally has more overhead than the OS-level optimized copy that fs.copyFile() can leverage for a plain, unmodified copy.
// Simple, efficient copy
await fs.promises.copyFile('source.txt', 'destination.txt');
// Manual piping, useful when transforming data during the copy
fs.createReadStream('source.txt').pipe(zlib.createGzip()).pipe(fs.createWriteStream('destination.txt.gz'));Real-world example A backup utility uses fs.copyFile() for straightforward file duplication (letting the OS handle the copy as efficiently as possible), but switches to manual stream piping specifically when it needs to simultaneously compress files during the backup process.