Sending a Large File with Axios

I am facing a challenge while trying to upload a large JSON file containing at least 400,000 objects into my database. When I attempt to post only 20,000 objects at a time, everything works smoothly, indicating that the issue lies with the size of the JSON.

To overcome this hurdle, I have divided the JSON file into 20 smaller chunks with the intention of uploading one chunk at a time. However, I am encountering difficulties in implementing this approach effectively.

Below is the code snippet I am currently using:

var rows = {};
Papa.parse(content, {
    header: false,
    delimiter: '|',
    worker: true,
    encoding: "utf16le",
    dynamicTyping: true,
    skipEmptyLines: true,
    complete: function(results) {
        rows = results.data;
        let obj = []
        for(var i=0; i < rows.length; i++){
            obj.push(rows[i])
        }

        let result = []

        for(let i in obj) {
            let temp = {}
            if(i > 0) {
                temp["id"] = obj[i][0]
                temp["name"] = obj[i][1]
                temp["tel"] = obj[i][2]
                temp["email"] = obj[i][3]
                temp["status"] = obj[i][5]
                
                result.push(temp)
            }
        }
        
        var array1 = result.map((e) => {
            return {
                id: e.id,
                name: e.name,
                email: e.email
            }
        })

        let chunked = []
        let size = 20000;

        Array.from({length: Math.ceil(array1.length / size)}, (val, i) => {
        chunked.push(array1.slice(i * size, i * size + size))
        })

        console.log(chunked); // at this point I have my array divided into chunks of 20000

        axios({
            url: 'url',
            method: 'post',
            data: chunked
          })
          .then(function (response) {
              // your action after success
              console.log(response);
          })
          .catch(function (error) {
             // your action on error successif (error.response) {
            console.log(error);
        
          });

Answer №1

If you want to send the data one by one, you can follow this approach. Make sure your backend is capable of accepting the data format.

for(let i=0;i<chunked.length;i++){
    axios({
        url: 'url',
        method: 'post',
        data: chunked[i]
    })
    .then(function (response) {
        // Perform actions after success
        console.log(response);
    })
    .catch(function (error) {
        // Perform error handling actions if required
        console.log(error);
    });
}

Alternatively, a more modern solution would be to utilize Promise.all([])

let promiseArray = [];
for(let i=0;i<chunked.length;i++){
    promiseArray.push(axios({
       url: 'url',
       method: 'post',
       data: chunked[i]
    }))
}

Promise.all(promiseArray)
.then((responses) => {
    console.log(responses);   // Returns an array of resolved/rejected promises
})
.catch(error => { 
    console.error(error.response)
});

For further information on Promise.all([]), visit this link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NodeJS: Implementing external URL redirection functionality

I've set up a GET /auth route that is supposed to redirect to an external resource, like https://google.com. However, instead of redirecting me to the correct URL, it redirects me to http:localhost:3000/api/auth/https://google.com. Is there a way to ...

Press the Text and Alter Text with React

I'm having an issue with the onClick event using React hooks. My goal is to have the text change to a different one when the user clicks, and then revert back to the original text on another click. For example, clicking "Change First" should switch it ...

Upon initiating a React Native project, five critical vulnerabilities become apparent

Upon starting my React Native project, I encountered 5 high severity vulnerabilities. Despite attempting to fix them with the command "npm audit fix --force", the issue persisted. I even went as far as reinstalling node.js and React Native, but the vulne ...

Verify whether the current directory includes a package.json file with a matching name value

When I run a custom command in the terminal, I am attempting to achieve two objectives: Verify if there is a package.json file in the current directory (similar to checking for the existence of process.cwd() + '/package.json'). Determine if the ...

What is the procedure for altering a particular element using ajax technology?

I have an AJAX request that updates the user information. I need to retrieve a specific value from the response and update the content of a specific element. For example, here is the element that needs to be changed: <div id="changeMe"><!-- New ...

Is there a way to retrieve MongoDB count results in Node.js using a callback function?

Is there a way to access mongodb count results in nodejs so that the outcome can be easily retrieved by asynchronous requests? Currently, I am able to retrieve the result and update the database successfully. However, when it comes to accessing the varia ...

Exploring the power of JavaScript Callback using nano and now.js

every.person.now.guessValue = function(value) { database.find('lists', 'project_names', { startingPoint: value, endingPoint: value + "\u9999" }, function(_, information) { return information.rows.map(function( ...

The ng-model failed to display the updated value until a click was made somewhere on the page

I am struggling with displaying the correct value of an ngModel variable defined in my controller. Despite changing to the correct value in the console, it doesn't update on the page until I click somewhere else or hit the update button again. Here&a ...

Mutation observer fails to observe an element if it is housed within a function

I am attempting to initialize the liveChatAvailable value as true and set the isLoading value to false once the crispClient element loads onto the page. However, when the observer object is placed within a function, the if (crispClient) code does not exec ...

Passing event handlers to Client Components within NextJS 13 and using the <button onClick={}> element is not supported

Oops! It looks like you can't pass event handlers to Client Component props. If you want your component to be interactive, consider converting some of it to a Client Component. const reqHelp = () => { Swal.fire({ title: '1', ...

Developing a web application using Node.js and Angular that can send both 401 Unauthorized and 200 OK responses

Upon clicking the register button on my form, it appears that Angular is setting the URL to /profile (a protected route) before the node server can authorize the JWT and send the 200 OK response. I'm unsure of how to address this issue. Even when I h ...

Retrieve data attributes to obtain details about the slider before and after

My task is to create a slider with information about the previous and next slides. For example, in the slider, there are left < and right > arrows. Behind these arrows, there are circles. When you hover over any arrow to change the next or previous ...

Is transforming lengthy code into a function the way to go?

I have successfully implemented this code on my page without any errors, but I am wondering if there is a more concise way to achieve the same result. Currently, there is a lot of repeated code with only minor changes in class names. Is it possible to sh ...

I am struggling to link my JS application with a PHP file as it is showing "PHP file not found

I am facing an issue with my JS application. I am unable to send data from jQuery to a PHP file, as I encountered this error message: POST https://magazyn.rob-tech.pl/savesettings.php 404 The app is running on PORT=8080 npm run start and the package.json ...

Which RxJS operators necessitate unsubscription?

It can be confusing to know which operators in RxJS must be unsubscribed from to prevent subscription leaks. Some, like forkJoin, complete automatically, while others, such as combineLatest, never complete. Is there a comprehensive list or guideline availa ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...

Dealing with JavaScript errors within an Express application

Consider the following async function export async function fetchData() { const result = await fetchData(); return result[0].id; } In the route, there is router.post( '/some-route', handleAsyncError(async (req: Request, resp: Response, _ ...

Controlling the v-model value of a v-select within a v-for loop

I have set up a table of members using a v-for loop, and certain users have the ability to manage other members based on their role. I have implemented some checks to prevent unauthorized roles from intervening, but the full list of checks is carried out o ...

Delete class at waypoints

I am currently using waypoints.js to manage a single-page website that includes a highlighted navigation feature. When the viewport reaches the element with the class "content", the corresponding navigation point is given the class "active". The script i ...

Struggling to insert HTML into an element using JavaScript or jQuery within a function

I'm currently experimenting with implementing smooth page transitions using Barba. The following is my code snippet for adding some HTML when a new page is loaded. Barba.Dispatcher.on('newPageReady', function(currentStatus, oldStatus, conta ...