title: Node.js: chunked transfer encoding
body: <p>Is that code valid HTTP/1.1?</p>
  
  <pre><code>var fs = require('fs')
  var http = require('http')
  
  var buf=function(res,fd,i,s,buffer){
   if(i+buffer.length&lt;s){
    fs.read(fd,buffer,0,buffer.length,i,function(e,l,b){
     res.write(b.slice(0,l))
     //console.log(b.toString('utf8',0,l))
     i=i+buffer.length
     buf(res,fd,i,s,buffer)
    })
   }
   else{
    fs.read(fd,buffer,0,buffer.length,i,function(e,l,b){
     res.end(b.slice(0,l))
     fs.close(fd)
    })
   }
  }
  
  var app = function(req,res){
   var head={'Content-Type':'text/html; charset=UTF-8'}
   switch(req.url.slice(-3)){
    case '.js':head={'Content-Type':'text/javascript'};break;
    case 'css':head={'Content-Type':'text/css'};break;
    case 'png':head={'Content-Type':'image/png'};break;
    case 'ico':head={'Content-Type':'image/x-icon'};break;
    case 'ogg':head={'Content-Type':'audio/ogg'};break;
    case 'ebm':head={'Content-Type':'video/webm'};break;
   }
   head['Transfer-Encoding']='chunked'
   res.writeHead(200,head)
   fs.open('.'+req.url,'r',function(err,fd){
    fs.fstat(fd,function(err, stats){
     console.log('.'+req.url+' '+stats.size+' '+head['Content-Type']+' '+head['Transfer-Encoding'])
     var buffer = new Buffer(100)
     buf(res,fd,0,stats.size,buffer)
    })
   })
  }
  
  http.createServer(app).listen(8000,"127.0.0.1")
  console.log('GET http://127.0.0.1:8000/appwsgi/www/index.htm')
  </code></pre>
  
  <p>I think I am violating HTTP/1.1 here? Text files do seem to work fine, but that could be coincidental. Is my header "200 OK" or need it to be "100"? Is one header sufficient?</p>