javascript / intermediate
Snippet
Robust Stream Processing with pipeline()
The pipeline utility is a cleaner and safer alternative to .pipe(), as it handles error propagation and stream cleanup automatically, preventing memory leaks.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const { pipeline } = require('node:stream/promises');const { createReadStream, createWriteStream } = require('node:fs');async function compressLogs() {try {await pipeline(createReadStream('access.log'),createWriteStream('access.log.bak'));console.log('Pipeline succeeded');} catch (err) {console.error('Pipeline failed:', err);}}
nodejs
Breakdown
1
require('node:stream/promises')
Imports the promise-based version of the stream module for use with async/await.
2
await pipeline(...)
Sequentially connects multiple streams and waits for the entire process to finish or fail.