Created
November 20, 2012 20:08
-
-
Save mheadd/4120691 to your computer and use it in GitHub Desktop.
Fun with Node.js Pipes
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
| // Include required modules. | |
| var http = require('http'); | |
| // Globally available vars. | |
| var endpoint = 'search.yahoo.com'; | |
| var proxyPath = '/search?p='; | |
| // HTTP server for client requests. | |
| var server = http.createServer(function (clientRequest, clientResponse) { | |
| clientRequest.setEncoding('utf8'); | |
| // Get the inbound HTTP request. | |
| clientRequest.on('end', function() { | |
| // Extract the search term from the request URL (ugly, but it works). | |
| var searchTerm = clientRequest.url.substring(1, clientRequest.url.length); | |
| // Create HTTP client to send request to endpoint. | |
| var options = { host: endpoint, port: 80, path: proxyPath + searchTerm, method: 'GET' }; | |
| var request = http.request(options, function(proxyResponse) { | |
| // Pipe the HTTP client response from endpoint back to the HTTP server response. | |
| proxyResponse.pipe(clientResponse); | |
| }).end(); | |
| }); | |
| }).listen(3000); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Start the proxy server:
~$ node pipes.js
Enter the following in your web browser:
http://127.0.0.1:3000/node.js