NodeJS 请求:管道传输时如何获得“response.statusCode”?

NodeJS Request: How do I get `response.statusCode` when piping?

抱歉各位,我有点迷路了。管道时如何console.log response.statusCode

var express = require('express');
var path = require('path');
var request = require('request');
var fs = require('fs');
var app = express();
var port = 8000;

var destination = fs.createWriteStream('./downloads/google.html');
var url = "http://www.google.com/";
request(url).pipe(destination)
.on("finish", function() {
    console.log("done");
    console.log(response.statusCode); // <<<<<<<<<<<<<<<<<<<<<<<<<<<< this
})
.on("error", function(err){
  console.log(err);
});

app.listen(port, function(){
console.log('running server on ' + port);
});

您需要从 request 捕获 response 事件。它不会出现在管道的 finished 事件中。您还应该考虑在管道之前捕获错误。这是您将捕获网络错误的地方。在管道之后你会发现文件错误。

request(url)
.on('response', function(response) {
    console.log(response.statusCode) // <--- Here 200
})
.on("error", function(err){
    console.log("Problem reaching URL: ", err);
 })
.pipe(destination)
.on("finish", function(response) {
    console.log("done");
})
.on("error", function(err){
    console.log("Problem writing file: ", err);
});