Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs input stream using express

Is there a way that using express a route consumer can send an input stream to the endpoint and read it?

In short I want the endpoint user upload a file by streaming it instead of the multipart/form way. Something like:

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

Is it possible to do it?

like image 345
RicardoE Avatar asked Oct 18 '17 12:10

RicardoE


1 Answers

In Express, the request object is an enhanced version of http.IncomingMessage, which "...implements the Readable Stream interface".

In other words, request is already a stream:

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

If your intention is to first read the entire file into memory (probably not), you can also use 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...
});
like image 73
robertklep Avatar answered Oct 23 '22 21:10

robertklep