如何在不写入其他文件的情况下流式传输加密视频以做出响应?

时间:2019-01-15 20:22:51

标签: node.js express nodejs-stream

我正在尝试使用nodejs传输加密的视频文件。服务器代码如下,

在窗口10和节点v8.12.0上测试代码。使用AES-256-CBC进行解密,文件将被加密。如果直接流式传输(不使用Range),则工作正常,但我必须分块发送。

app.get('/video', function(req, res) {
    const unzip = zlib.createUnzip();
    var getVideoID = req.query.videoId;
    const path ="./assets/"+video_path[getVideoID];
    const stat = fs.statSync(path);
    const fileSize = stat.size;
    const range = req.headers.range;
    if (range) {
        const parts = range.replace(/bytes=/, "").split("-");
        const start = parseInt(parts[0], 10);
        var end = parts[1] ? parseInt(parts[1], 10): fileSize-1;

        var chunksize = (end-start)+1;   
        var maxChunk = 1024 * 1024; // 1MB at a time
        if (chunksize > maxChunk) {
          end = start + maxChunk - 1;
          chunksize = (end - start) + 1;
        }
        readStream = fs.createReadStream(path, {start, end, autoClose: true})
        .on("open", function() {
          let  ivbuf = Buffer.alloc(16);
          let deciph = crypto.createDecipheriv("aes-256-cbc", Buffer.from(secretKey,'binary'), ivbuf);
          readStream.pipe(deciph).pipe(unzip).pipe(res);
        })
        .on('error', function(err){
          res.end(err);
        })
        const head = {
          'Content-Range': `bytes ${start}-${end}/${fileSize}`,
          'Accept-Ranges': 'bytes',
          'Content-Length': chunksize,
          'Content-Type': 'video/mp4',
        }
        res.writeHead(206, head);
    } else {
      const head = {
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
      }
      res.writeHead(200, head)
      let  ivbuf = Buffer.alloc(16);
      let deciph = crypto.createDecipheriv("aes-256-cbc", Buffer.from(secretKey,'binary'), ivbuf);
      readStream = fs.createReadStream(path,{start:256});
      readStream.pipe(deciph).pipe(unzip).pipe(res);
    }
})

我想直接从加密文件流式传输视频,而不要将其写入另一个文件。

0 个答案:

没有答案