Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Serve large files with Node.js
var libpath = require('path');
var http = require('http');
var fs = require('fs');
var url = require('url');
var bind_port = 8001;
var path = "/path/to/your/base_directory/";
http.createServer(function (request, response) {
var uri = url.parse(request.url).pathname;
var filename = libpath.join(path, uri);
libpath.exists(filename, function (exists) {
if (!exists) {
console.log('404 File Not Found: ' + filename);
response.writeHead(404, {
"Content-Type": "text/plain"
});
response.write("404 Not Found\n");
response.end();
return;
} else{
console.log('Starting download: ' + filename);
var stream = fs.createReadStream(filename, { bufferSize: 64 * 1024 });
stream.pipe(response);
}
});
}).listen(bind_port);
console.log('Download Server listening on Port' + bind_port);
@ripper2hl

This comment has been minimized.

Copy link

ripper2hl commented Nov 3, 2015

what is bufferSize ?

@dreaddymck

This comment has been minimized.

Copy link

dreaddymck commented Sep 22, 2016

I think

{ bufferSize: 64 * 1024 } 

is now

{ highWaterMark: 64 * 1024 }
@odilitime

This comment has been minimized.

Copy link

odilitime commented Sep 11, 2017

libpath.exists probably should be fs.exists

@djy0

This comment has been minimized.

Copy link

djy0 commented Oct 14, 2018

libpath.exists probably should be fs.exists

yes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.