Created
April 4, 2018 08:57
-
-
Save caub/688f64f169609c25476171acd625855e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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