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

前端 未结 4 1893
栀梦
栀梦 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)
           }
        })
    }
    

提交回复
热议问题