为什么下载文件会产生EADDRNOTAVAIL错误?

时间:2013-01-03 03:01:22

标签: node.js

我正在尝试使用node.js使用以下脚本下载文件:

var http = require('http');
var fs = require('fs');

var file = fs.createWriteStream("google.html");
var request = http.get("http://www.google.com/", function(response) {
  response.pipe(file);
});

我在Windows 7上一直收到以下错误:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: connect EADDRNOTAVAIL
    at errnoException (net.js:670:11)
    at Object.afterConnect [as oncomplete] (net.js:661:19)
Press any key to continue . . .

...以及Linux Mint 13上的以下错误:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:646:11)
    at Object.afterConnect [as oncomplete] (net.js:637:18)

此错误的最可能原因是什么,我该如何解决?我的网络上没有阻止网址,所以我不确定为什么这不起作用。

1 个答案:

答案 0 :(得分:1)

试试这个。

var http = require('http');

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/index.html',
  method: 'GET'
};   

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.end();