首页 > 解决方案 > 如何在 Node JS 中将数据从一个流复制到另一个流

问题描述

我想在Java中将数据从一个流复制到另一个流,我以以下方式进行

ByteStreams.copy( inputStream, outputStream );

在 Node JS 中,我试图找出如何做到这一点

    // Making an ajax call to get the Video file
const getVideo = async (req, res) => {
  try {
      axios.get('Video URL')
          .then(function (videoResponse) {
              res.setHeader("Content-Type", "video/mp4");
              // copy the inputStram of videoResponse 
              //to the output stram of res
              // copy the videoResponse to res
          })
  } catch (error) {
      console.log(error);
  }
};

任何人都可以建议如何做到这一点,谢谢您的帮助

标签: node.js

解决方案


读取和写入文件系统的最简单示例是:

  const fs = require('fs')
  const input = fs.createReadStream('input_file')
  const output = fs.createWriteStream('output_file')
  input.pipe(output)

检查Node.js的文件系统文档。

输入和输出流可以是任何 ReadStream 和 WriteStream,例如 HTTP 响应或 S3。

Axios Github 自述文件中,您可以看到与您尝试做的非常相似的示例(请使用原始示例,我必须在此处更改 URL)

// GET request for remote image in node.js
axios({
  method: 'get',
  url: 'https://lh3.googleusercontent.com/iXm....',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });

推荐阅读