Express.js and Multer are facing an issue where the response is being sent before the onFileUploadComplete function is

Currently, I am utilizing the following code for a file upload service:

onFileUploadStart: function (file) {
        uploadPath = "";
        imageDimensions = null;
        console.log(file.originalname + ' is starting to upload...');
    },
onFileUploadComplete: function (file) {
        uploadPath = file.path;
        uploadPath = uploadPath.replace(/\\/g,"/");
        console.log("Upload complete. " + file.fieldname + ' uploaded to  ' + file.path)
        sizeOf(file.path, function (err, dimensions) {
            if (err){
                console.log("ERROR, Can't get size of image! " + err);
                return;
            }
            else{
                imageDimensions = { 
                    width : dimensions.width,
                    height: dimensions.height
                };
                console.log("Size of image: width: " + imageDimensions.width + ". height: " + imageDimensions.height);
            }

        });
    }

Also,

app.post('/imageupload',function(req,res){
  upload(req,res,function(err) {
    console.log("response is being send..");
    if(err) {
        return res.end("Error uploading file.");
    }
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.json({
        dimensions: imageDimensions,
        path: uploadPath
    });
});

});

According to my observation mentioned here, it seems like onFileUploadComplete is processed before the .post handler gets executed. However, when I check my console output, I see:

a.jpg is starting to upload...
Upload complete. file uploaded to uploadeddata\a1235412.jpg
response is being send..
Size of image: width: 2835, height: 1654

This indicates that while in the middle of the onFileUploadComplete function, the .post handler is already running.

Does anyone have suggestions on how I can resolve this issue?

Answer №1

Ah, I understand now... the sizeOf function that was utilized is asynchronous...

var dimensions = sizeOf(file.path);

This is the synchronous version.

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

The communication between the Next.js and Node.js servers is being obstructed as the request body fails

Could you lend me a hand with this issue? Here is the function being called: function apiCreate(url, product) { console.log('Posting request API...' + JSON.stringify(product) ); fetch(url, { dataType: 'json', method: 'post ...

Issues with React Native: Struggling to iterate through an array and show it with an image URL stored

Just diving into React and I'm facing a challenge with my code. I have an array stored in my .state that I want to loop through and display the images. (I'm using 'Image' and a Card object from https://github.com/lhandel/react-native-ca ...

Module compilation error: BrowserslistError: Invalid browser query 'dead' was not recognized

Whenever I attempt to execute "npm run build" in the command prompt, I encounter an error message stating: "Module build failed: BrowserslistError: Unknown browser query dead at Array.forEach()". I have experimented with the commonly suggested fix found o ...

Is `console.log()` considered a native function in JavaScript?

Currently, I am utilizing AngularJS for my project. The project only includes the angular.min.js file without any additional references to other JavaScript files. The code snippet responsible for sending requests to the server is as shown below: var app = ...

Determining the specific page or method being called in a JSP page upon submission

There is a JSP page named X.JSP that contains radio buttons and a submit button. When the submit button is clicked on X.JSP, the next page Y.JSP is displayed with parameters xxxx=1111&yyyy=2222&zzzz=3333. Is there a way to determine the page, ser ...

"Resetting select fields in a Django application using jQuery: A step-by-step guide

Recently, I was tasked with taking over a partially-developed Django application. Python is familiar territory for me, but I am completely new to JavaScript. This application heavily relies on jQuery for various form manipulations. One specific issue I enc ...

Is there a way to retrieve php session in a javascript file?

Here's the code snippet for reference: Contents of index.php file Javascript code from index.php function Result() { var marks = 55; document.getElementById("hdnmarks").innerHTML= marks; window.location = "results.php"; } HTML code from ind ...

What is the best way to set up Storybook.js Webpack to support absolute image paths within CSS modules for a Next.js project?

I'm currently setting up Storybook to integrate with Next.js, Ant Design, Less, and TypeScript. In Next.js, images need to be stored in the public/ directory and linked using absolute paths for universal usage within the project. I am facing challenge ...

Encountering difficulties accessing Node.JS Sessions

Hey there, I am currently working on integrating an angular application with Node.js as the backend. I have set up sessions in Angular JS and created my own factory for managing this. Additionally, I am utilizing socket.io in my Node.js server and handling ...

Vertical sorting of arrays in JavaScript based on index positions

Here is an array containing the letters of the alphabet: ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] From the server, I receive the number of columns to display. Let's assume it's 3 f ...

Why won't NextJS Image elements render on iOS 16 when they are not in the viewport initially?

I opted to implement NextJS for enhanced routing capabilities and image optimization. However, I encountered an issue with certain images failing to load properly on iOS devices. The problem arises within a scrollable horizontal container featuring Product ...

Accessing JSON fields containing accents in JavaScript

I am encountering an issue with the JSON file below: { "foo supé": 10 } My attempt is to extract and log the value of the field "foo supé" into the console using the code snippet provided: <!DOCTYPE html> <html> <s ...

Regular expression that prohibits the acceptance of numbers with leading zeros

Below is the directive I am using to ensure that the input consists purely of numbers from 0-9. import { Directive, HostListener, ElementRef } from "@angular/core"; @Directive({ selector: "[numbersOnly]", }) export class OnlynumberDi ...

Exploring the implementation of float type in TypeScript

Is it possible to use Number, or is there a more type-specific alternative? In the past, I have relied on Number and it has proven effective for me. For example, when defining a variable like percent:Number = 1.01... ...

Determine the DOM element that corresponds to a right-click action

I utilized the code snippet below to construct a personalized context menu: <script type="text/javascript"> $(document).ready(function() { var x, y; document.oncontextmenu = function(e) { e.preventDefault(); x = e.clientX; ...

Is there a way to export static HTML from Next.js to different directories at once?

My Next.js website is static with 1 million pages, but I am facing an issue where all the exported pages are stored in the same folder, requiring a lot of RAM to access files. Is there a way to export pages into multiple folders, maybe grouping 100k pages ...

Disabling $routeprovider while implementing bootstrap

I am encountering an issue with my normal routeprovider code. In a specific section of my HTML, I have some Twitter Bootstrap expand/collapse sections which inadvertently trigger the routeprovider when clicked. Is there a way to prevent this from happening ...

What is the best way to embed an HTML tag along with its attributes as a string within an element?

https://i.sstatic.net/EZSOX.png Is there a way to incorporate this specific HTML tag with its distinct colors into an element within a JSX environment? I attempted the following approach: const htmlTag = '<ifx-icon icon="calendar-16"> ...

"Seeking clarification on submitting forms using JQuery - a straightforward query

My goal is to trigger a form submission when the page reloads. Here's what I have so far: $('form').submit(function() { $(window).unbind("beforeunload"); }); $(window).bind("beforeunload", function() { $('#disconnectform&apo ...

Attempting to assign headers after they have already been sent to the client, causing a conflict in NEST

After connecting Redis to my session store, I am encountering an error after the first request, causing subsequent requests to fail. Error: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at Serv ...