'Error: socket hang up in Http Request made in Node JS using request-promise causing for loop to restart

I am trying to make an Http Request using request-promise inside a for loop. But it seems if a Http Request takes long, request-promise closes the connection.

This behavior is ok but what I am not able to grasp is the for loop starts from 0 again after the error is printed.

Below is the code

const rp = require('request-promise');
async function stepIterator(processingSteps, documentId) {
    var finalResult = null;
    for (var step = 0, len = processingSteps.length; step < len; step++) {
        if (step === 0 || step === 1 || step == 2 || step == 3) {
            try {
                console.log('Calling step ', step);
                let url = 'http://internal-server:8080/process';
                let collection = getCollection(documentId);
                let splitText = getSPlit(documentId);
                let outputFormat = 'xmi';
                let documentObject = await callServer(url, collection, splitText, outputFormat);
                finalResult = documentObject;
            } catch (error) {
                console.log("Error");
            }
        }
    }
    return finalResult;
}

async function callServer(url, collection, splitText, outputFormat) {
    var options = {
        method: 'POST',
        uri: url,
        headers: {
            'Content-Type': 'multipart/form-data',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive '
        },
        formData: {
            collection: collection,
            text: splitText,
            output: outputFormat
        }
    };
    return rp(options)
} 

The complete error trace is as follows

{ RequestError: Error: socket hang up at new RequestError (D:\New_Projects\new-data-access-layer\node_modules\request-promise-core\lib\errors.js:14:15) at Request.plumbing.callback (D:\New_Projects\new-data-access-layer\node_modules\request-promise-core\lib\plumbing.js:87:29) at Request.RP$callback [as _callback] (D:\New_Projects\new-data-access-layer\node_modules\request-promise-core\lib\plumbing.js:46:31) at self.callback (D:\New_Projects\new-data-access-layer\node_modules\request\request.js:185:22) at Request.emit (events.js:182:13) at Request.onRequestError (D:\New_Projects\new-data-access-layer\node_modules\request\request.js:881:8) at ClientRequest.emit (events.js:182:13) at Socket.socketOnEnd (_http_client.js:425:9) at Socket.emit (events.js:187:15) at endReadableNT (_stream_readable.js:1094:12) at process._tickCallback (internal/process/next_tick.js:63:19) name: 'RequestError', message: 'Error: socket hang up', cause:
{ Error: socket hang up at createHangUpError (_http_client.js:322:15) at Socket.socketOnEnd (_http_client.js:425:23) at Socket.emit (events.js:187:15) at endReadableNT (_stream_readable.js:1094:12) at process._tickCallback (internal/process/next_tick.js:63:19) code: 'ECONNRESET' }, error: { Error: socket hang up at createHangUpError (_http_client.js:322:15) at Socket.socketOnEnd (_http_client.js:425:23) at Socket.emit (events.js:187:15) at endReadableNT (_stream_readable.js:1094:12) at process._tickCallback (internal/process/next_tick.js:63:19) code: 'ECONNRESET' }, options: { method: 'POST', uri: 'http://internal-server:8080/process', json: true, headers: { Connection: 'keep-alive ' }, body: { docSplitId: [Array], _id: 5c579d84812acb17ec74ac39, contentType: 'application/pdf', location: 'C:\\Users\\newuser\\AppData\\Local\\Temp\\2\\report.pdf', docModelVersion: '1', visualMetaDataId: null, categoryId: '5c52a72f6df294140c0535bc', deductedInfo: null, status: 'New', isDeleted: false, metadata: [Object], detailedStatus: [Array] }, callback: [Function: RP$callback], transform: undefined, simple: true, resolveWithFullResponse: false, transform2xxOnly: false }, response: undefined }



Solution 1:[1]

Obviously the socket is hanging! Don't bother with http, it is a little complex. Use node unirest and it closes the data stream.

var unirest = require('unirest');
var req = unirest('POST', 'localhost:3200/store/artifact/metamodel')
  .attach('file', '/home/arsene/DB.ecore')
  .field('description', 'We are trying to save the metamodel')
  .field('project', '6256d72a81c4b80ccfc1768b')
  .end(function (res) { 
    if (res.error) throw new Error(res.error); 
    console.log(res.raw_body);
  });

Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arsene Online