使用节点请求管道映像,但在非200 HTTP状态代码上中止

Gee*_*Jan 0 node.js node-request

我正在尝试使用node-request通过管道传输存储在Amazon S3上的图像。但是,有时不存在图像,该图像由S3作为状态代码403公开。我正在努力查看如何在成功的情况下进行管道传输(200),但在非200的情况下采取替代措施。

r.abort is not a function尽管似乎应该在请求中可用,但使用abort()方法似乎是一种方法,但是却获得了。

// context: inside a request handler, where `res` is the response to write to
const r = request(url)
  .on('response', function (response) {
    if (response.statusCode !== 200) {
      r.abort(); //failing
      // I want to stop the piping here and do whatever instead.
    }
  })
  .pipe(res);
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Gee*_*Jan 5

要回答我自己的问题:在确定正确之前,请勿开始管道:

 request(url)
    .on('response', function (r) {
      if (r.statusCode !== 200) {
        //take other action
      }
      r.pipe(res);
    })
Run Code Online (Sandbox Code Playgroud)