Node-request - How to determine if an error occurred during the request?

前端 未结 4 1876
栀梦
栀梦 2020-12-24 12:20

I\'m trying to leverage the node-request module, but the documentation isn\'t that great. If I make a request to a valid resource and pipe it to a Writable Stream, everythin

相关标签:
4条回答
  • 2020-12-24 12:27

    The way I ended up succeeding with new Streams in node:

    function doQuery(){
        var r = request(url)
        r.pause()
        r.on('response', function (resp) {
           if(resp.statusCode === 200){
               r.pipe(new WritableStream()) //pipe to where you want it to go
               r.resume()
           }else{  }
        })
    }
    

    This is really flexible - if you want to retry, you can call the function recursively with setTimeout

    function doQuery(){
        var r = request(url)
        r.pause()
        r.on('response', function (resp) {
           if(resp.statusCode === 200){
               r.pipe(new WritableStream()) //pipe to where you want it to go
               r.resume()
           }else{ 
               setTimeout(doQuery,1000)
           }
        })
    }
    
    0 讨论(0)
  • 2020-12-24 12:35

    @Mikeal solution looks great, but may have some problem with the piping (first few bytes can be missed). Hee is an updated code:

    var r = request(url)
    r.pipe(new WritableStream());
    r.on('response', function (resp) {
       resp.headers 
       resp.statusCode
       // Handle error case and remove your writablestream if need be.
    })
    
    0 讨论(0)
  • 2020-12-24 12:39

    i wrote request :)

    you might want to try this

    var r = request(url)
    r.on('response', function (resp) {
       resp.headers 
       resp.statusCode
       r.pipe(new WritableStream())
    })
    
    0 讨论(0)
  • 2020-12-24 12:46

    Why not use the http module directly.http.request

    It has an 'error' event which you can use to catch the error.

    0 讨论(0)
提交回复
热议问题