serving files from file system with node.js, response body comes back as empty

So I'm trying to serve files back to a user after they've been uploaded to the server. I'm storing uploaded files inside the application directory, in a directory called uploads. Here is the code that I'm using to serve the files:

if (req.url.split("/")[1] == "uploads") {
    console.log("requesting file " + virtualToPhysical(req.url));
    var file = fs.readFile(virtualToPhysical(req.url), function (err, data) {
        if (err) {
            throw err;
        } else {
            res.writeHead(200, { 'Content-Type': mime.lookup(req.url) });
            res.end(data, 'binary');
        }
    });
}

virtualToPhysical just appends the path to the directory in the filesystem onto the request url. If req.url is "/uploads/image1.jpg", virtualToPhysical will spit out "/path/to/application/uploads/image1.jpg". The mime.lookup() call comes from an included library that deduces the correct MIME type for the file.

This code runs without any errors. The response headers look okay, but the body comes back as empty every time, no matter the file type or size. I've tried another method usinng util.pump() but that produces the same result.

*EDIT:*I've been looking all around and this is literally the only method that people say to use to serve a file over node. I'm at a loss as to what my problem could be. Someone suggested not using the 'binary' flag when calling res.end(), but the same effect occurs no matter what.

Remove the 'binary' argument from your call to res.end(); the encoding parameter is only applicable if you're sending a string, and in this case you're sending a buffer. Also, 'binary' was dropped as an encoding type in recent versions of node.

I figured out the problem wasn't in fs.readFile opening the file, it was the way I was saving the files on upload. Instead of using fs.writeFile() while saving the upload from formidable, you need to rename it from its location in /tmp. Here is an example:

form.parse(req, function (err, fields, files) {
  file_name = escape(files.upload.name);
  fs.rename(files.upload.path, virtualToPhysical("/uploads/" + file_name), function (err) {
    if (err) {
      throw err;
    } else {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end(file_name);
    }
  });
});