'Reading a CSV file in express/multer without saving the file on the server

I currently have a express server set up with a react front-end and I managed to send a csv file from the front end to the back end using this

onClickHandler = async e => {
    e.preventDefault();
    const data = new FormData()
    data.append('file',this.state.selectedFile)
   Axios.post("/api/upload",data)
   .then(res => console.log(res))
   .catch(err => console.log(err));
    
  }

(FormData holds my CSV files)

However in express, I am using multer to receive this

const upload = multer()
app.post('/api/upload', upload.single("file"), (req, res) => {
  console.log(req.body)
  
 
});

When I console log the "req" I get this:

fieldname: 'file',
[0]     originalname: 'test1.csv',
[0]     encoding: '7bit',
[0]     mimetype: 'application/vnd.ms-excel',
[0]     buffer: <Buffer 41 63 63 6f 75 6e 74 4e 61 6d 65 2c 41 63 63 6f 75 6e 74 56 61 6c 75 65 0d 0a 50 45 54 54 59 20 43 41 53 48 2c 31 37 32 36 39 2e 35 31 0d 0a 43 41 53 ... 
381 more bytes>,

I understand that I am sending a buffer object however I want to access the content and eventually validate the columns and rows of the file, but everything I have searched is about saving the file first, which is what I do not want to do. I just want to access it without saving to the server.

Any help would be appreciated.



Solution 1:[1]

You should use multer inbuilt storage(memoryStorage) method.

Try following code ??

const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() })

app.post('/api/upload', upload.single("file"), (req, res) => {
  console.log(req.file) // it'll return file uploaded from client side
});

Solution 2:[2]

Below code worked for me

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

const upload = multer()
app.post('/api/upload', upload.single("file"), (req, res) => {
 console.log(req.file.buffer)
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rishav Pandey
Solution 2