Streaming

A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout. Streams are readable, writable, or both. All streams are instances of EventEmitter

You can load the Stream base classes by doing require('stream'). There are base classes provided for Readable streams,Writable streams, Duplex streams, and Transform streams.

This document is split up into 3 sections. The first explains the parts of the API that you need to be aware of to use streams in your programs. If you never implement a streaming API yourself, you can stop there.

The second section explains the parts of the API that you need to use if you implement your own custom streams yourself. The API is designed to make this easy for you to do.

The third section goes into more depth about how streams work, including some of the internal mechanisms and functions that you should probably not modify unless you definitely know what you are doing.

 

Streaming Response

http.createServer(function(request, response){ 
});

request is readable stream
response is writable stream

 

Example receive from the request

var http = require('http');
http.createServer(function(request, response) {
response.writeHead(200);
request.on('readable', function(){
var chunk = null;
while(null !== (chunk = request.read())) {
console.log(chunk.toString());
response.write(chunk);
}
});
request.on('end', function(){
response.end();
});
}).listen(8080);
Request when reponse passed to pipe method , like these following :
http.createServer(function(request, response) {
response.writeHead(200);
request.pipe(response);
}).listen(8080);
// lets try to the command line
curl -d 'hello' http://localhost:8080
// this is will print 'hello' on the client

 

Example Upload File using Blocking Code

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

http.createServer(function(request,response){
var newFile = fs.createWriteStream("test.txt");
request.pipe(newFile);

request.on('end', function() {
response.end('uploaded!');
});

}).listen(8080);

Example Upload File using Non Blocking Code

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

http.createServer(function (request,response) {
var newFile = fs.createWriteStream("test.txt");
var fileBytes = request.headers['content-length'];
var uploadedBytes = 0;

request.on('readable', function () {
var chunk = null;
while(null !== (chunk = request.read())){
uploadedBytes += chunk.length;
var progress = (uploadedBytes/fileBytes) * 100 + "%\n";
response.write(progress);
}
});
request.pipe(newFile);
}).listen(8080);
curl --upload-file test.txt http://localhost:8080

 

Leave a Comment:



digital_ocean