I am looking to use swagger to upload a csv file and then process the file in my nodejs app, by looping through each row. The swagger part is fairly straight forward, but I can't read the file to be able to process the data.
I have used the basic swagger example below that works fine to serve the file, but I am unsure how to handle it in the backend.
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"
I then have a very basic function in the backend:
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")
});
};
When I log the file I receive:
{ 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 }
Now when I try to read the stream from "req.swagger.params['upfile'].value", I receive the following error:
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL
So I thought maybe I can then pass in the buffer value via: "req.swagger.params['upfile'].value.buffer" but then I get the error:
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
'
How would I go about reading the file so that I can process and loop through the data?