Why is the response undefined when I resize an image twice using a JavaScript promise chain?

When I attempt to resize an image using the sharp library twice in my route handler, the result returned is undefined. Despite the resized images being displayed, it seems that calling image.resize and .toBuffer() multiple times is causing corruption in the response object (res).

router.post('/submit', upload.single('file'), (req, res) => {
  var image = sharp(req.file.buffer)
  image.resize(1500, 1500, { fit: 'inside' }).toBuffer()
    .then(buffer => fs.writeFile('../image-md.jpg', buffer))
    .then(() => image.resize(500, 500, { fit: 'inside' }).toBuffer())
    .then(buffer => fs.writeFile('../image-sm.jpg', buffer))
    .then(() => res.json({ success: true })) 
    .catch(err => res.status(400).json({ error: err.message }))
})

// Issue: res is undefined and no status is being returned

An interesting observation is that when one of the resizing operations is commented out, everything functions properly:

router.post('/submit', upload.single('file'), (req, res) => {
  var image = sharp(req.file.buffer)
  image.resize(1500, 1500, { fit: 'inside' }).toBuffer()
    .then(buffer => fs.writeFile('../image-md.jpg', buffer))
    // .then(() => image.resize(500, 500, { fit: 'inside' }).toBuffer())
    // .then(buffer => fs.writeFile('../image-sm.jpg', buffer))
    .then(() => res.json({ success: true })) 
    .catch(err => res.status(400).json({ error: err.message }))
})

// Solution: res.data is { success: true } and status 200 is properly returned

In need of assistance!

Answer №1

The issue lies in this particular section:

.then(() => image.resize(500, 500, { fit: 'inside' }).toBuffer())

It is important to note that .then should only be used with a function as a parameter. In this case, you are passing the result of calling toBuffer on image.resize directly within parentheses for better clarity:

.then(
  (() => image.resize(500, 500, { fit: 'inside' }))
    .toBuffer()
)

Regarding conventions, it might be confusing for someone reading the code (like myself) to see a reference to fs without clarification. It could be helpful to rename it to something like fsPromises instead of just fs.

An alternative approach would be to utilize async/await for improved readability:

const processImage = async (requestBuffer) => {
  const image = sharp(requestBuffer);
  const bigBuffer = await image.resize(1500, 1500, { fit: 'inside' }).toBuffer();
  await fsPromises.writeFile('../image-md.jpg', bigBuffer);
  const smallBuffer = await image.resize(500, 500, { fit: 'inside' }).toBuffer();
  await fsPromises.writeFile('../image-sm.jpg', smallBuffer);
};

router.post('/submit', upload.single('file'), (req, res) => {
  processImage(req.file.buffer)
    .then(() => {
      res.json({ success: true });
    })
    .catch((err) => {
      res.status(400).json({ error: err.message })
    });
});

Answer №2

After some investigation, I discovered that my problem stemmed from a request timeout issue.

Initially, my timeout was configured for only 1 second. However, when I attempted to perform multiple resize operations, it exceeded the 1-second threshold. To resolve this, I adjusted the timeout setting to 10 seconds, which ultimately resolved the issue.

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

Check for length validation including spaces in JavaScript

My code includes a functionality that calculates the length of characters in a text area using both JSP and JavaScript: <textarea class="textAreaLarge" id="citation" rows="20" cols="180" name="citation" ...

What is the process for configuring a registry for a namespaced package using yarn?

Experimenting with yarn as a substitute for npm has been quite interesting. With npm, we usually rely on both a private sinopia registry and the official repository for some namespaced packages, since sinopia doesn't support namespaces. My .npmrc fi ...

Avoiding conflicts between banners, text, and images for HTML/CSS design

I'm having an issue with the banner I created for my project. It seems to be overlapping with text and images, hiding behind them. How can I fix this? Unfortunately, I can't post the link to my project here due to other files present. The specif ...

The mysterious nature of view binding in Ember.js

Here's a unique challenge I'm facing. I've developed a sidebar component called SortableStopView that extends CollectionView. This sidebar contains a scrollable and sortable list of 'stops' which users can click on to navigate to t ...

When viewing the material-ui Chip component at normal zoom, a border outlines the element, but this border disappears when zoomed in or out, regardless of

Edit I have recently discovered a solution to the unusual problem I was facing with the material-ui Chip Component. By adding the line -webkit-appearance: none; to the root div for the Chip, the issue seems to resolve itself. However, this line is being a ...

I am interested in creating a table that can toggle between show/hide mode with a plus/minus feature

$(document).ready(function() { $("#t1").hide(); // hide table by default $("#close").hide(); //hide the minus button as well if you only want one button to display at a time $('#sp1').on('click', function() { //when p ...

Accessing JSON data from a URL in AngularJS

Just dove into the world of fetching and displaying JSON data in my AngularJS app for the first time, but unfortunately, no data is showing up. Here's the code I have implemented: HTML <div ng-app="myApp" ng-controller="custom ...

Would you prefer to generate fresh HTML using JavaScript or dynamically load an existing HTML layout using AJAX?

I have a project where I need to generate a large amount of HTML that isn't currently on the page. Up until now, I've been using jQuery to construct the page piece by piece with JavaScript, adding divs and adjusting layouts as needed. Lately, I ...

Exploring the Bounds of Mongodb's $within Query

I'm currently working on a geospatial query in mongodb using the $within operator. I have a collection entry with a location field containing: location: { bounds: { south_west: { lat: XX.XXXXXX, lng: XX.XXXXX }, north_east: { lat: XX.XXXXXX ...

Tips for customizing the appearance of a redux-tooltip

After implementing the redux-tooltip from this GitHub repository, I wanted to customize its styling to better align with my application's design. However, I realized that the Tooltip-Component's divs do not have any identifiers or class names, ma ...

The issue at hand is the lack of execution for the Mocha Chai `.end()`

I have encountered an issue while trying to write a Mocha chai test for a Nodejs API that was previously tested using Supertest. Strangely, the test always passes even when I intentionally specify wrong expected parameters. Below is the code snippet of th ...

Some design elements are present in the interface. The functionality of the data tables is working properly, however, upon reloading the page, the table header shrinks. Interestingly

[![enter image description here][1]][1] This is the JavaScript code along with my footer and header references. The issue I am facing is with the design - initially, it shows a buggy design but when I click on the header, it displays the correct design. & ...

Tips for transferring parameters between functions in AngularJS

I'm currently working with the following piece of code: var FACEBOOK = 'facebook'; $scope.handle_credentials = function (network) { hello(network).api('me').then(function (json) { dbService.handle_credential ...

Having difficulty displaying elements from two arrays at particular intervals

I am currently working with two arrays that have the same number of items in each. My goal is to print these items in intervals within the console. The desired output would look something like this: 1 Bruce Wayne 45 Then, after a one-second interval, it s ...

Enhancing Material-UI component [TreeView] with drag and drop functionality using react-dnd

I have encountered an issue with my TreeView implementation. Whenever I try to drag and drop a TreeItem, all of its child TreeItems move along with it. Is there a way to enable drag'n'drop functionality for just one TreeItem without affecting its ...

Deploying a pair of GitHub repositories to a unified Azure web application

Although this isn't exactly a technical question, I couldn't find a more appropriate stackexchange site for it. Recently, I made the move to Azure for deploying my backend web applications and APIs. I discovered that it's possible to deploy ...

Testing for connected components with a specific property (React/Redux)

Having a React component with Redux @connect decorator, a situation arises like this: import React, { Component } from 'react' import { connect } from 'react-redux' @connect(mapStateToProps, { onPress: () => {...code}) // The ...

What is the significance of a listener signaling an asynchronous response with a return of true, only to have the communication channel close before the response could be received?

Currently, I am developing a React application that involves the use of various npm modules. One of these modules is a self-built NPM package called modale-react-rm (available at this link). This package serves as a simple modal component that utilizes the ...

The migration-mongo module is not being recognized as a standard CommonJS module

I have integrated a nodejs server component into my project, which includes the usage of migrate-mongo. In my package.json file, the type specified is module. However, when attempting to run the migration process, I encounter the following error: > migr ...

Transform for loop from Axios post requests to promises

I am currently working with a loop of axios requests: for(const [number, response] of Object.entries(questions)){ axios.post( this.address+'surveypost', {"patientID": patientID, "questionID": number, "lik ...