Skip to content

Instantly share code, notes, and snippets.

@youurayy
Created November 9, 2011 09:02
Show Gist options
  • Save youurayy/1350901 to your computer and use it in GitHub Desktop.
Save youurayy/1350901 to your computer and use it in GitHub Desktop.
Node.js (v0.4) sendfile() non-caching fileserver - fast and efficient!
var http = require('http');
var fs = require('fs');
var path = require('path');
var constants = require('constants');
var timers = require('timers');
var port = 8080;
http.createServer(function(req, res) {
if(req.url == '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('filesender.js v1\n');
}
else {
var fn = path.resolve('.'+ req.url.replace(/\.\./g, '.'));
fs.open(fn, 'r', function(err, fd) {
if(err) {
var msg = 'Not found: ' + fn;
res.writeHead(404, {
'Content-Length': msg.length,
'Content-Type': 'text/plain'
});
res.end(msg);
}
else {
var off = 0;
var s = res.socket;
var size = fs.fstatSync(fd).size;
console.log('serving file', fn, 'of size', size);
s.write('HTTP/1.1 200 OK\r\n' +
'Content-Length: ' + size + '\r\n' +
'Content-Type: application/octet-stream\r\n' +
'Cache-Control: no-cache\r\n' +
'Connection: close\r\n' +
'Pragma: no-cache\r\n' +
'Expires: -1\r\n' +
'\r\n'
);
var sendData = function() {
s.removeListener('drain', sendData);
try {
do {
off += fs.sendfileSync(s.fd, fd, off, size - off);
timers.active(s);
}
while(off < size);
s.flush();
}
catch(e) {
if(e.errno === constants.EAGAIN) {
s.on('drain', sendData);
s._writeWatcher.start();
}
else {
console.log(e);
s.end();
}
}
};
sendData();
}
});
}
}).listen(port, "0.0.0.0");
console.log('serving files from directory',
path.resolve('.'), 'at port', port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment