NODE JS Cancellation Request

I use this code to upload files in node js:

var currentVideoRequest = null;

window.spawnVideoPlayer = function (url, subs, movieModel,tag) {
    if(currentVideoRequest) {
    try
    {
      currentVideoRequest.abort();
    }
    catch(err)
    {
      alert(err.message);
    }

    }

    var fs = require('fs');
    var urlrequest = currentVideoRequest = require('request');

    urlrequest.get({url: url, encoding: 'binary'}, function (err, response, body) {
      fs.writeFile(FILEURL, body, 'binary', function(err) {

      }); 
    });
}

And in currentVideoRequest.abort();I get this error:

    Object function request(uri, options, callback) {
  if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.')
  if ((typeof options === 'function') && !callback) callback = options
  if (options && typeof options === 'object') {
    options.uri = uri
  } else if (typeof uri === 'string') {
    options = {uri:uri}
  } else {
    options = uri
  }

  options = copy(options)

  if (callback) options.callback = callback
  var r = new Request(options)
  return r
} has no method 'abort'
+4
source share
3 answers

To add @Etai to the answer, you need to request the request module before using it for one instance of the request. Something like that:

var request = require('request');
// ...
// then later in the code
var urlrequest = request.get(uri, function(err, response, body) {
    // process data here
});

// later, you'd abort this as:
urlrequest.abort();

Note that I am saving the instance with var urlrequest = request.get(params, callback);, so that I can later interrupt it.

+4
source

your current VideoRequest is the constructor of the request object, not the request object, so this does not work.

The query constructor returns the request object when called, i.e.

require('request')('uri', function(err, resp, body){})
+3
source

abort(), .

var reqObj = request({uri: 'https://jsonplaceholder.typicode.com/albums'  }, function (error, response, body) {
    console.log('API requested ') ;
    if (!err){
        console.log(body);
    }
    else
    {
        console.log(err);
    }
});

reqObj.abort();
+1

Source: https://habr.com/ru/post/1536742/


All Articles