node.jsでストリーミング的な

ストリーミングってよくわかってないんだけど、こういう事なのかなあ?

index.js
#!/usr/bin/env node

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

http.createServer(function (req, res) {
  var aaa;
  
  res.writeHead(200, {
    'content-type': 'text/plain; charset=utf-8'
  });
  
  aaa = fs.createReadStream('./aaa', {
    bufferSize: 1
  });
  aaa.on('data', function (data) {
    res.write(data);
  });
  aaa.on('end', function () {
    res.end();
  });
  aaa.on('error', function () {
    res.writeHead(500);
  });

}).listen(3000);
aaa

aaaというファイルは大きい方が良いので、とりあえずVim

:e ./aaa(Enter)100ia(ESC)yy10000p:wq(Enter)

としてaが沢山書かれたファイルを保存しておきました。


あとは

$ node index.js

としてhttp://localhost:3000/を見ると、ちょこちょことaaaの中身が表示されていきます。
これを画像ファイルとか音声ファイルでやると良いのかな?


エラーが発生したら500返してるつもりなのだけど、これでいいのだろうか……


追記:
ちょっとだけ短くした。

#!/usr/bin/env node

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

http.createServer(function (req, res) {
  res.writeHead(200, {
    'content-type': 'text/plain; charset=utf-8'
  });
  
  fs.createReadStream('./aaa', {
    bufferSize: 1
  })
  .on('data', function (data) {
    res.write(data);
  })
  .on('end', function () {
    res.end();
  })
  .on('error', function () {
    res.writeHead(500);
  });

}).listen(3000);


追記2:
Re:node.jsでストリーミング的な - .blogにてpipe使った方が楽だよと教えてもらった!
てか、上記を書いた後にそのことに気がついたw
pipeラクチンだなー。