Search code examples
javascriptnode.jscloudinary

nodejs stream wait until I recieve my URL


I use cloudinary api to upload my files with stream. The problem is if I upload my image I recieve the URL to late. My backend sends back if I stream a empty URL and after 2-3 seconds I get in console log my uploaded URL. how can I wait until I have my uploaded URL (secure_url)

        if(getExtensionFromMime === 'jpeg') {
          imgSharp = await sharp(blobToBuffer).jpeg({quality: 90}).toBuffer();
        } else {
          imgSharp = await sharp(blobToBuffer).png({quality: 90}).toBuffer();
        }

        const stream = cloudinary.v2.uploader.upload_stream(
          { folder: "uploads" },
          (error, result) => {
            if (error) return console.error(error);
            console.log(result?.secure_url);
             return result?.secure_url;
          }
        );

        bufferToStream(imgSharp).pipe(stream);
  
      }
 
      return res.json(secureURLS);

Solution

  • The response from the upload request to Cloudinary hasn't come through by the time you render the JSON response. You could wrap it in a Promise and wait for it to resolve before rendering your response.

    // ... other code
    
    if(getExtensionFromMime === 'jpeg') {
        imgSharp = await sharp(blobToBuffer).jpeg({quality: 90}).toBuffer();
    } else {
        imgSharp = await sharp(blobToBuffer).png({quality: 90}).toBuffer();
    }
    
    
    function uploadStreamToCloudinary(buffer) {
      return new Promise((resolve, reject) => {
        cloudinary.v2.uploader
          .upload_stream(
            {
              folder: "uploads"
            },
            (error, result) => {
              if (error) {
                return reject(error);
              }
              resolve(result);
            }
          )
          .end(buffer);
      });
    }
    
    const result = await uploadStreamToCloudinary(imgSharp);
    
    return res.json(result); // or extract only the `result?.secure_url;`