Created
April 2, 2019 20:19
-
-
Save JhonatanHern/ab2395297e36aa3fd83f525975544f3d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 fs = require('fs'), | |
{ promisify } = require('util'), | |
express = require('express') | |
const asyncStat = promisify(fs.stat) | |
var router = express.Router() | |
router.use(function(req, res, next){next()}) | |
router.get('/song', async function(req, res) { | |
let path = 'file.mp3' | |
const stat = await asyncStat(path) | |
const fileSize = stat.size | |
const range = req.headers.range | |
if (range) { | |
const parts = range.replace(/bytes=/, "").split("-") | |
const start = parseInt(parts[0], 10) | |
const end = parts[1] | |
? parseInt(parts[1], 10) | |
: fileSize-1 | |
const chunksize = (end-start)+1 | |
const file = fs.createReadStream(path, {start, end}) | |
const head = { | |
'Content-Range': `bytes ${start}-${end}/${fileSize}`, | |
'Accept-Ranges': 'bytes', | |
'Content-Length': chunksize, | |
'Content-Type': 'audio/mpeg', | |
} | |
res.writeHead(206, head); | |
file.pipe(res); | |
} else { | |
const head = { | |
'Content-Length': fileSize, | |
'Content-Type': 'audio/mpeg', | |
} | |
res.writeHead(200, head) | |
fs.createReadStream(path).pipe(res) | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment