如何解析 multer 返回的 javascript 对象?

How can I parse a javascript object returned by multer?

我正在尝试使用 multer 处理 express 中 csv 文件的上传,然后逐行解析文件。我能够将文件作为 req.body 中包含的对象获取,但我无法解析它,因为它现在似乎只是一个对象,不再是 csv 字符串。如何分别从上传的文件中获取每一行? (app/index):

const csv = require('csvtojson');
const multer  = require('multer');
const upload = multer();

router.post('/distributor/:id/upload', upload.single(), function (req, res, 
next) {
  req.setTimeout(600000);
  console.log(req.body) 
  next()
}, function (req, res, next) {
    //calling req.body here returns an object with \r between each line from 
    file, but I cannot seem to parse each line
    res.end();
}) 

我尝试在第二个函数中使用 csvtojson,如下所示:

 csv()
.fromString(req.body.toString(UTF8))
.subscribe((csvLine)=>{
    console.log(csvLine); 
} 

但这只是试图解析整个对象,而不是其中的每一行。这是 multer 返回的对象的片段:

{"UPC,Price,SKU,Title\r\n043171884536,1.17,538397,ORANGE YARN EGGS SIZE 4 - 
4 PK\r\n043171080044,1.39,942227,MIKE'S YELLOW/CORN GLO 
BAIT\r\n035011000046,1.98,161687,REPLACEMENT BRAKE 
PADS\r\n056389001503,1.79,41582,FIRE 
LIGHTERS\r\n087837005156,5.04,266320,PLATINUM GREEN 1/4LB SPOOL 
25#\r\n046295070045,1.54,604652,MIKE'S GARLIC GLO-SCENT 
OIL\r\n043171660161,1.02,126011,THREAD  RED 100'\r"} 

编辑** 在我使用 bodyParser 之前。我在一个issue中看到bodyParser和multer一起使用是行不通的,所以我把它注释掉了。现在,我没有得到正文对象、文件对象或文件对象。我尝试使用 upload.none() 并在请求中发送相同的文件,看看我是否可以通过消息 "LIMIT_UNEXPECTED_FILE" 让它出错,但它没有,所以看起来 multer 甚至没有识别正在发送文件。我正在 Postman 中对此进行测试,内容类型设置为 false,正文为二进制文件并附有文件。尝试以这种方式测试请求有问题吗?

在 multer 文档提供的示例中,req.body 对象将包含表单中的文本字段,req.file 将包含上传的文件:

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

您是否尝试过使用 file 对象?类似于以下内容:

router.post('/distributor/:id/upload', upload.single(), function (req, res, next) {
  req.setTimeout(600000);
  console.log(req.body)
  console.log(req.file)
  csv()
  .fromFile(req.file.path)
  .then((jsonObj)=>{
    console.log(jsonObj);
    //loop through array of objects here
  }) 
  next()
});