使用express的nodejs输入流

nodejs input stream using express

有没有一种方法可以使用 express 路由消费者将输入流发送到端点并读取它?

简而言之,我希望端点用户通过流式传输而不是 multipart/form 方式上传文件。类似于:

app.post('/videos/upload', (request, response) => {
    const stream = request.getInputStream();
    const file = stream.read();
    stream.on('done', (file) => {
        //do something with the file
    });
});

可以吗?

在 Express 中,request 对象是 http.IncomingMessage 的增强版本,"...实现了可读流接口".

换句话说,request已经是一个流:

app.post('/videos/upload', (request, response) => {
  request.on('data', data => {
    ...do something...
  }).on('close', () => {
    ...do something else...
  });
});

如果你打算先将整个文件读入内存(可能不是),你也可以使用bodyParser.raw():

const bodyParser = require('body-parser');
...
app.post('/videos/upload', bodyParser.raw({ type : '*/*' }), (request, response) => {
  let data = req.body; // a `Buffer` containing the entire uploaded data
  ...do something...
});