2017-02-20 119 views

回答

1

我嘗試了這一點,似乎工作:

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 
} 
0

我不知道的方式來播放,因爲它是下載的音頻文件,但這裏是一些代碼,可能會爲你正在嘗試做的工作:

var http = require('http'), 
    fs = require('fs'), 
    filePath = 'myfile.mp3', 
    stat = fs.statSync(filePath); 

http.createServer(function(request, response) { 

    response.writeHead(200, { 
     'Content-Type': 'audio/mpeg', 
     'Content-Length': stat.size 
    }); 

    fs.createReadStream(filePath).pipe(response); 
}) 
.listen(2000); 

希望這有助於!