Need to upload multiple pdf files using File API- Node

The below code works for a single file upload, but if I have an array of file paths

filePaths = [‘abc.pdf’, ‘sample.pdf’,‘xyz.pdf’] all files are in current directory. When I loop over the array, the code just uploads the last file 3 times to hubspot folder. I think fs.createReadStream() should be async. please advise

const axios = require(‘axios’);

const FormData = require(‘form-data’);

const fs = require(‘fs’);

let data = new FormData();

const filePaths = [‘abc.pdf’, ‘sample.pdf’,‘xyz.pdf’];

async function toCall(){

for(var i=0; i< filePaths.length; i++){

await getFormData(filePaths[i]);

let config = {

method: ‘post’,

maxBodyLength: Infinity,

url: ‘https://api.hubapi.com/files/v3/files/’,

headers: {

'Authorization': 'Bearer \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*',

...data.getHeaders()

},

data : data

};

axios.request(config)

.then((response) => {

console.log(JSON.stringify(response.data));

})

.catch((error) => {

console.log(error);

});

}

}

async function getFormData(path)

{

data.append('file', fs.createReadStream(path));

data.append('folderId', '\*\*\*\*\*\*\*\*\*\*');

data.append('options', '{"access":"PRIVATE"}');

}

toCall();

Hey, @AngelKanna :waving_hand:

Here’s what I’d look at:

  • Creating new FormData for each file vs. reusing for the same instance
  • Use proper async/await handling versus mixing with .then()
  • Look into using Promise.all for doing concurrent uploads
  • Add error handling to both the individual files and the batch process

Best,

Jaycee

Yes, I used async/await and error handling, so I can upload each file perfectly. Thanks for the suggestions, it helped me to reach a perfect solution