JSFiddle - React, Tailwind, and code Playground
JavaScript
/*
хэндл, срабатывающий при нажатии на аудио файл
*/
function handleTrack(event) {
const url = new URL(`https://${globalhost}:${port}/play`);
url.search = new URLSearchParams({path: event.srcElement.attributes.path.value}).toString();
fetch(url).then(response => {
response.blob().then(blob => {
const urlBlob = URL.createObjectURL(blob);
audioPlayer.setAttribute('src', urlBlob);
audioPlayer.setAttribute('type', response.headers.get('content-type'));
});
});
}
/*
на сервере обработка запроса выполняется следующим образом
*/
https.createServer(options).on('request', (req, res) => {
const urlObj = url.parse(req.url, true);
switch (urlObj.pathname) {
case '/play': {
sendAudioFile(req, res, urlObj.query.path);
break;
}
default:
break;
}
}).listen(port, localhost, () => {
console.log(`Server was started on https://${localhost}:${port}`);
});
/*
функция отправки файла
*/
function sendAudioFile(req, res, path) {
const splitedPath = path.split('.');
const format = splitedPath[splitedPath.length - 1];
const fileSize = fs.statSync(path).size;
//const range = req.headers.range;
const range = 'bytes=0-';
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 head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunkSize,
'Content-Type': `audio/${format}`
};
res.writeHead(206, head);
fs.createReadStream(path, {start, end}).pipe(res);
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': `audio/${format}`
};
...