簡體   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