简体   繁体   English

NodeJS - ExpressJS:如何在没有缓冲的情况下 stream 请求正文

[英]NodeJS - ExpressJS: How to stream request body without buffering

I need to handle some request without content-type as binary file我需要处理一些没有content-type的请求作为二进制文件

const app = express();
app.use(bodyParser.raw({type: (req) =>  !req.headers['content-type'], limit: '500mb' }));

those file can be huge (eg. 500 MB).这些文件可能很大(例如 500 MB)。

I want to read req.body as stream for don't wast memory, but bodyParser.raw() make req.body as Buffer .我想将req.body读为 stream 以防止浪费 memory,但bodyParser.raw()req.body设为Buffer

How handle req.body as Stream ?如何将req.body处理为Stream

You can use stream to handle huge file.您可以使用 stream 来处理大文件。

Express http request is a readable stream, you can pipe the request binary to file, but make sure the output is also a writable stream. Express http request is a readable stream, you can pipe the request binary to file, but make sure the output is also a writable stream.

Example code:示例代码:

const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();

app.post('/', (req, res, next) => {
    req.pipe(fs.createWriteStream(path.join('./uploadFiles', Date.now().toString() + '.mp4')));
    req.on('end', () => {
        res.end('Upload complete');
        next();
    })
})

app.listen('3000', () => {
    console.log('Server listen to port 3000');
})

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

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