简体   繁体   English

Node.js 如何将缓冲区转换为 stream?

[英]Node.js how to convert a buffer to stream?

Im receiving a buffer from a post request in the form-data (which is being handled by multer).我从表单数据中的发布请求接收缓冲区(由 multer 处理)。 And i need to pass that along to another service by making post request using form-data.我需要通过使用表单数据发出发布请求将其传递给另一个服务。

const documentFile = req.body.image;
const image = bufferToStream(documentFile.buffer);
function bufferToStream(binary) {
    const readableInstanceStream = new Readable({
      read() {
        this.push(binary);
        this.push(null);
      },
    });

    return readableInstanceStream;

  }

image is now a Readable rather than a ReadStream you would get from fs.createReadStream(). image现在是 Readable 而不是从 fs.createReadStream() 获得的 ReadStream。 I need a readstream.我需要一个阅读流。

So i can use axios to send a form-data request like this.所以我可以使用 axios 来发送这样的表单数据请求。

const formData = new FormData();

formData.append("image",image);

const options: any = {
            url,
            method: "post",
            headers: formData.getHeaders(),
            data: formData,
            config: retryConfig,
};
await axios(options)

After getting file from multer , you can do exactly the same on server as if you were sending from client.multer获取文件后,您可以在服务器上执行与从客户端发送完全相同的操作。 Install form-data package and try below snippet.安装form-data package 并尝试以下代码段。

const FormData = require('form-data');

...
const formData = new FormData();
formData.append("image", req.body.image);
axios({ data: formData });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM