首页 > 解决方案 > NodeJS 中间件 GCS 视频流在加载时挂起

问题描述

我正在尝试使用 node express 作为视频流的中间件,当我测试负载时,我一次只能加载大约 5-6 个视频。

我加了油门只是想看看它是否有帮助,但显然没有。

当前的解决方案是将签名的 url 发送到前端并让它们直接从 GCS 加载,但我想知道这是否是我设置错误的东西,因为我记得 Nodejs 应该能够轻松处理多个加载请求。

app.get("/video/:bucketname/*", async function (req, res) {
    if(req.params ==undefined|| req.params["bucketname"]==undefined|| req.params["0"]==undefined){
        console.log("Invalid routing")
        
        return
    }
    req.setTimeout(10000,function(){
        console.log("timeout")
        res.status(408).send('Requested Timeout');
    })

    const storage = new Storage({
        keyFilename: path.join(__dirname, "keyfile.json"),
        projectId: projectname
    })

    // TODO: Further checks on authorisation

    const range = req.headers.range;
    const bucket = storage.bucket(req.params["bucketname"]);
    
    const remoteFile = bucket.file(req.params["0"]);

    
    const [metaData] = await remoteFile.getMetadata();
    const fileSize = metaData.size;

    if (range) {
        const parts = range.replace(/bytes=/, "").split("-")
        const start = parseInt(parts[0], 10)
        const end = parts[1]
            ? parseInt(parts[1], 10)
            : fileSize - 1
        
        if (start >= fileSize) {
            res.status(416).send('Requested range not satisfiable\n' + start + ' >= ' + fileSize);
            return
        }

        const chunksize = (end - start) + 1

        const head = {
            'Content-Range': `bytes ${start}-${end}/${fileSize}`,
            'Accept-Ranges': 'bytes',
            'Content-Length': chunksize,
            'Content-Type': 'video/mp4',
        }
        // HTTP Status 206 for Partial Content
        res.writeHead(206, head);

        //returns the chunk that you want
        remoteFile.createReadStream({ start, end })
        .pipe(new Throttle({rate: 500000})).pipe(res)
        
        
    } else {
        console.log("fullstream")
        const head = {
            'Content-Length': fileSize,
            'Content-Type': 'video/mp4',
        }
        res.writeHead(200, head)
        remoteFile.createReadStream(path).pipe(res)
    }

});

标签: node.jsexpressgoogle-cloud-storage

解决方案


推荐阅读