我希望使用swagger上传一个csv文件,然后通过遍历每一行在我的nodejs应用中处理该文件。摇摇晃晃的部分相当简单,但是我无法读取文件来处理数据。
我使用了下面的基本swagger示例,可以很好地处理文件,但是我不确定如何在后端处理它。
paths:
/upload:
post:
summary: "Uploads a file."
operationId: "uploadPOST"
consumes:
- "multipart/form-data"
parameters:
- name: "upfile"
in: "formData"
description: "The file to upload."
required: false
type: "file"
responses:
201:
description: "An object with user details"
x-swagger-router-controller: "Default"
然后我在后端有一个非常基本的功能:
const fs = require('fs');
const csv = require('csv-parser');
module.exports.uploadPOST = function uploadPOST (req, res, next) {
var fileValue = req.swagger.params['upfile'].value;
console.log(fileValue);
fs.createReadStream(fileValue)
.pipe(csv())
.on('data', function(data){
console.log(data);
})
.on('end',function(){
console.log("Done")
});
};
当我记录文件时,我收到:
{ fieldname: 'upfile',
originalname: 'test.csv',
encoding: '7bit',
mimetype: 'application/octet-stream',
buffer:
<Buffer 63 6f 6c 75 6d 6e 5f 61 2c 63 6f 6c 75 6d 6e 5f 62 2c 63 6f 6c 75 6d 6e 5f 63 2c 63 6f 6c 75 6d 6e 5f 64 2c 63 6f 6c 75 6d 6e 5f 65 2c 63 6f 6c 75 6d ... >,
size: 251 }
现在,当我尝试从“ req.swagger.params ['upfile']。value”读取流时,出现以下错误:
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL
所以我想也许我可以通过以下方式传递缓冲区值:“ req.swagger.params ['upfile']。value.buffer”,但随后出现错误:
Error: ENOENT: no such file or directory, open 'column_a,column_b,column_c,column_d,column_e,column_f
a1,b1,c1,d1,e1,f1
a2,b2,c2,d2,e2,f2
a3,b3,c3,d3,e3,f3
a4,b4,c4,d4,e4,f4
a5,b5,c5,d5,e5,f5
a6,b6,c6,d6,e6,f6
a7,b7,c7,d7,e7,f7
a8,b8,c8,d8,e8,f8
a9,b9,c9,d9,e9,f9
a10,b10,c10,d10,e10,f10
'
我将如何读取文件,以便处理和遍历数据?
答案 0 :(得分:0)
所以我在想这个错误的方式。如注释中所述,fs.createReadStream()特定于从文件读取。昂首阔步将文件转换为对象时,需要使用其他方法。
这是通过csv节点模块实现的。
public abstract class Dessert {
/** Name of the dessert item. */
protected final String name;
/**
* Constructs a new dessert item.
* @param name Name of the dessert.
*/
public Dessert(String name) {
this.name = name;
}
/**
* Get name of the dessert.
* @return dessert name
*/
public final String getName() {
return name;
}
/**
* Get the price of the dessert.
* @return Dessert price
*/
public abstract double getPrice();
}
并像这样使用它
public class Cookie extends Dessert {
private int number;
private double price;
public Cookie (String name, int number, double price) {
super(name);
this.number = number;
this.price = price;
}
public int getItemCount() {
return number;
}
public double getPricePerDozen() {
return (price / 12) * number;
}
}
这将依次将csv转换为数组数组
npm install csv