Skip to content

Instantly share code, notes, and snippets.

@bnoordhuis
Created November 16, 2010 23:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bnoordhuis/702695 to your computer and use it in GitHub Desktop.
Save bnoordhuis/702695 to your computer and use it in GitHub Desktop.
node.js + sendfile = file serving++
http = require('http');
fs = require('fs');
fd = fs.openSync(__filename, 'r');
size = fs.fstatSync(fd).size;
server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Length': size,
'Content-Type': 'text/plain'
});
res._send(''); // force flush
fs.sendfile(req.connection.fd, fd, 0, size, function(err, n) {
console.log(arguments);
res.end();
});
});
console.log("Starting server.");
server.listen(8080);
@gurdiga
Copy link

gurdiga commented Jan 11, 2011

I could not find the sendfile method in the node documentation. Is this pseudo-code or some other library is needed?

@bnoordhuis
Copy link
Author

Neither. It's in lib/fs.js but undocumented.

@fbzhong
Copy link

fbzhong commented Jan 7, 2012

It seems like after nodejs 0.6.x, the socket fd has been removed from javascript api. The sample does not works.

@LiSheep
Copy link

LiSheep commented Dec 1, 2013

I am trying to find linux's "sendfile" system call in node.js, it seems had been implement?~

@adamkaplan
Copy link

It was removed in 2012, apparently broken between 2010 and 2012.

nodejs/node@910e24b

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