流大文件时,节点JS内存堆出

时间:2019-11-07 13:46:18

标签: node.js streaming

我尝试使用nodejs进行电影流服务并进行表达。我使用fs.createReadStream()pipe()并将其发送到http响应。当处理1位用户时,它的服务效果很好,没有问题。当7个用户一起访问它时,第7个用户没有来自http的任何响应。刚等。该视频不显示。前六个用户没有任何问题。

这是一些代码段:

const asset = path.join(__dirname,/content${data.path}${contentType.name}.${contentType.ext})
const stat = fs.statSync(asset)
    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([1],10):fileSize-1
        const chunkSize = (end-start)+1
        const file = fs.createReadStream(asset,{start,end})
        const head = {
            "Content-Range":`bytes ${start}-${end}/${fileSize}`,
            "Accept-Ranges":"bytes",
            "Content-Length":chunkSize,
            "Content-Type":contentType.contType
        }
        res.writeHead(206,head)

        file.pipe(res)
    }else{
        const head = {
            "Content-Length":fileSize,
            "Content-Type":contentType.contType
        }
        res.writeHead(200,head)
        const file = fs.createReadStream(asset)

        file.pipe(res)

        file.on('error',(err)=>{
            console.log(err)
        })
    }

我必须排空缓冲区才能解决它吗?

0 个答案:

没有答案
相关问题