繁体   English   中英

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

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

我需要处理一些没有content-type的请求作为二进制文件

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

这些文件可能很大(例如 500 MB)。

我想将req.body读为 stream 以防止浪费 memory,但bodyParser.raw()req.body设为Buffer

如何将req.body处理为Stream

您可以使用 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.

示例代码:

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