Skip to content

Instantly share code, notes, and snippets.

@jessecravens
Created November 26, 2012 18:32
Show Gist options
  • Save jessecravens/4149801 to your computer and use it in GitHub Desktop.
Save jessecravens/4149801 to your computer and use it in GitHub Desktop.
NodeJS Hacks - Streams
exports.example1 = function(req, res){
var fs = require('fs');
//Open a file as a readable stream
var readStream = fs.ReadStream(__dirname + "/../in.txt");
readStream.setEncoding('ascii'); // This is key; otherwise we'd be using buffers
var writeStream = fs.createWriteStream(__dirname + "/../out.txt");
// every time "data" is read, this event fires
readStream.on('data', function(textData) {
console.log("Input: " + textData);
writeStream.write(textData);
});
// the reading is finished...
readStream.on('close', function () {
writeStream.end(); // ...close up the write, too!
console.log("Output created.");
});
res.render('example1', { title: 'Example1' })
};
@jessecravens
Copy link
Author

Request URL:http://localhost:3000/example1
Request Method:GET
Status Code:200 OK

Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:false_r=1; __atuvc=85%7C38%2C4%7C39%2C1%7C40
Host:localhost:3000
Referer:http://localhost:3000/example1
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11

Response Headers
Connection:keep-alive
Content-Length:1977
Content-Type:text/html; charset=utf-8
Date:Mon, 26 Nov 2012 18:48:50 GMT
X-Powered-By:Express

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment