Using Multer - How do I read an uploaded file (text/.csv)

Chris Johnson picture Chris Johnson · Mar 13, 2018 · Viewed 9.2k times · Source

First time using Multer - I built an app to parse a .csv file and count the # of occurences of each keyword and phrase in the file, but I made changes using node and express to parse the file AFTER it's been submitted via a form using express router and multer.

I'm a bit confused as I am no longer reading a File but this:

{
[💻]   fieldname: 'file-upload',
[💻]   originalname: 'Google-Analytics.csv',
[💻]   encoding: '7bit',
[💻]   mimetype: 'text/csv',
[💻]   buffer: <Buffer 48 65 61 64 65 72 2c 53 75 62 2d 68 65 61 64 65 72 2c 54 61 67 2c 4b 65 79 77 6f 72 64 73 2c 54 65 73 74 69 6d 6f 6e 69 61 6c 0d 0a 54 75 72 6e 20 69 ... >,
[💻]   size: 2990
}

I think I need to find something to process the buffer as Jimp processes an image upload from multer.

TL;DR; How do I read the text file contents when uploading with multer?

Answer

Amaranadh Meda picture Amaranadh Meda · Mar 13, 2018

I hope below answer will resolve your problem.

Add

app.use(multer({
  dest: 'uploads/'
}));

after

app = express(); 

In the request handler you can access file details as below

 req.files 

For example in the input field name is "test". You can access file details as below.

req.files.test
req.files.test.path

will give you exact path of the file.

So you can use

let data = fs.createReadStream(req.files.test.path,'utf8');

then you can take a look at

console.log(data);