Skip to content

Instantly share code, notes, and snippets.

@caub
Created April 4, 2018 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caub/688f64f169609c25476171acd625855e to your computer and use it in GitHub Desktop.
Save caub/688f64f169609c25476171acd625855e to your computer and use it in GitHub Desktop.
const DIR = os.homedir() + '/.foo';
// adapted from https://stackoverflow.com/a/24977085/3183756
const downloadFromFs = (req, res) => {
const { name } = req.params;
const filePath = path.join(DIR, name);
fs.stat(filePath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
return res.status(404).end();
}
return res.status(400).end(err.message);
}
const range = req.headers.range;
let headers = {
'Content-Disposition': `inline; filename=${name}`,
'Accept-Ranges': 'bytes',
'Content-Length': stats.size,
'Content-Type': mime.getType(name),
};
let status = 200;
let streamOpts;
if (range) {
status = 206;
const positions = range.replace(/bytes=/, '').split('-');
const start = parseInt(positions[0], 10);
const total = stats.size;
const end = Math.max(start, positions[1] ? parseInt(positions[1], 10) : total - 1);
const chunkSize = end - start + 1;
Object.assign(headers, {
'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
'Content-Length': chunkSize,
});
streamOpts = { start, end };
}
res.writeHead(status, headers);
const stream = fs
.createReadStream(filePath, streamOpts)
.on('open', () => {
stream.pipe(res);
})
.on('error', err => {
res.end(err.message);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment