Я попробовал это, и это похоже на работу:
const http = require('http')
const util = require('util')
const mime = require('mime')
const PORT = process.env.PORT || 8080
const onFinished = require('on-finished')
const parseRange = require('range-parser')
const torrentStream = require('torrent-stream')
const engine = torrentStream('magnet:?xt=urn:btih:b42f85d4d976f31d9edde30a101c79928e1353f6')
engine.on('ready', (files) => {
http.createServer(function (req, res) {
const index = parseInt(req.url.slice(1), 10)
if (!files.hasOwnProperty(index)) return res.end()
const file = files[index || 0]
console.log(`${file.name} ${req.headers.range ? req.headers.range : ''}`)
send(req, res, file)
}).listen(PORT, function() { console.log('Server listening on: http://localhost:%s', PORT) })
})
function send (req, res, file) {
let stream
let len = file.length
const type = mime.lookup(file.path)
if (type) {
const charset = mime.charsets.lookup(type)
res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''))
}
res.setHeader('Content-Length', len)
res.setHeader('Accept-Ranges', 'bytes')
if (req.headers.range) {
const ranges = parseRange(len, req.headers.range, { combine: true })
if (ranges === -1) {
res.setHeader('Content-Length', 0)
res.setHeader('Content-Range', contentRange('bytes', len))
res.statusCode = 416
return res.end()
}
if (ranges !== -2 && ranges.length === 1) {
res.statusCode = 206
res.setHeader('Content-Range', contentRange('bytes', len, ranges[0]))
len = ranges[0].end - ranges[0].start + 1
res.setHeader('Content-Length', len)
if (req.method === 'HEAD') return res.end()
stream = file.createReadStream(ranges[0])
}
} else {
if (req.method === 'HEAD') return res.end()
stream = file.createReadStream()
}
onFinished(res,() => stream && stream.destroy())
stream.pipe(res)
return stream
}
function contentRange (type, size, range) {
return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size
}