Introduction
Streams are used for making a handy abstraction, and we can do a lot of new inventions using them. Streams are I/O abstractions. In this article, we will be describing the Stream.pipe() method. The Stream pipe method is used to attach a readable stream to the writable Stream. We use this method to switch in flowing mode and push all the data to the attached writable file.
Let’s learn about the stream pipe method using elaborative examples.

Uses of Stream Pipes
The various uses of Stream pipes are:
- Stream.pipe() method is used to attach a readable stream to the writable Stream.
- Stream.pipe() method is also used in file streams in NodeJs.
- Stream.pipe() can be used for HTTP requests and response objects.
- Stream.pipe() method can be used to send incoming requests to a file logging.
Let’s see an example of these uses,
#!/usr/bin/env node var child = require('child_process'); var myREPL = child.spawn('node'); myREPL.stdout.pipe(process.stdout, { end: false }); process.stdin.resume(); process.stdin.pipe(myREPL.stdin, { end: false }); myREPL.stdin.on('end', function() { process.stdout.write('REPL stream ended.'); }); myREPL.on('exit', function (code) { process.exit(code); }); |
In the above example, we have seen that if we need to spawn a node child process and use the pipe for stdout and stdin methods.
For the following example, we will cover the use of pipes as file streams in NodeJs.
#!/usr/bin/env node var child = require('child_process'), fs = require('fs'); var myREPL = child.spawn('node'), myFile = fs.createWriteStream('myOutput.txt'); myREPL.stdout.pipe(process.stdout, { end: false }); myREPL.stdout.pipe(myFile); process.stdin.resume(); process.stdin.pipe(myREPL.stdin, { end: false }); process.stdin.pipe(myFile); myREPL.stdin.on("end", function() { process.stdout.write("REPL stream ended."); }); myREPL.on('exit', function (code) { process.exit(code); }); |
In the example below, we can observe the easiest kind of proxy,
#!/usr/bin/env node var http = require('http'); http.createServer(function(request, response) { var proxy = http.createClient(9000, 'localhost') var proxyRequest = proxy.request(request.method, request.url, request.headers); proxyRequest.on('response', function (proxyResponse) { proxyResponse.pipe(response); }); request.pipe(proxyRequest); }).listen(8080); http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('request successfully proxied to port 9000!' + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); }).listen(9000); |
This article has explained the basics of using the Stream.pipe() method for effortlessly passing our data streams around.