Last active
December 20, 2015 18:19
-
-
Save rkrzr/6174797 to your computer and use it in GitHub Desktop.
An example of how to use streams in Node.js.
It gets a page via http, transforms the data to uppercase and prints it to stdout.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = require('request'); | |
var url = 'http://www.site2mobile.com'; | |
// Set both readable and writable in constructor. | |
var UpperStream = function () { | |
this.readable = true; | |
this.writable = true; | |
}; | |
// Inherit from base stream class. | |
require('util').inherits(UpperStream, require('stream')); | |
UpperStream.prototype.write = function (data) { | |
data = data ? data.toString() : ""; // convert bytes to string | |
this.emit('data', data.toUpperCase()); | |
}; | |
UpperStream.prototype.end = function () { | |
this.emit('end'); | |
}; | |
// stream an HTTP request to stdout and uppercase everything | |
request({uri: url}) | |
.pipe(new UpperStream()) | |
.pipe(process.stdout); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment