NodeJS - 强大的 200 MB 文件限制和崩溃

NodeJS - Formidable 200 MB file limit and crash

我有 nodejs 服务器:

var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    console.log(req.rawHeaders)
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      if (err) throw err;
      var oldpath = files.file.path
      var newpath = 'C:/VSI/' + files.file.name;
      fs.rename(oldpath, newpath, function (err) {
        //if (err) throw err;
        //res.write('File uploaded and moved!');
        if (err) {
          res.write(JSON.stringify({
            success: false,
            message: 'error happend'
          })
          );
          res.end()
          throw err;
        }

        res.write(JSON.stringify({
          success: true,
          message: 'Successfully Uploaded'
        })
        );
        res.end();
      });
    });
  } else {
    console.log(req.rawHeaders)
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(8080, () => {
  console.log('server running')
}).on("error", () => console.log("error happend"));

并得到

if (err) throw err;
               ^

Error: maxFileSize exceeded, received 209715683 bytes of file data

如何使用 formidable 上传更多 200 MB?

如何正确处理异常以及为什么 "on error" on("error", () =>) 事件不起作用?

我试过 Multer,它没有 200 MB 的限制并且可以正常工作。

只需阅读文档: https://www.npmjs.com/package/formidable

默认最大大小为 200MB,将其更改为(例如 300MB):

form.maxFileSize = 300 * 1024 * 1024;