【问题标题】:Zero byte files after XML download in node.js在 node.js 中下载 XML 后的零字节文件
【发布时间】:2013-07-19 22:43:44
【问题描述】:

我目前正在使用以下代码 sn-p 尝试获取 Yahoo 天气 XML 文件:

// This script requires request libraries.
// npm install request

var fs = require('fs');
var woeid_array = fs.readFileSync('woeid.txt').toString().split("\n");
var grabWeatherFiles = function (array) {
//var http = require('http');
//var fs = require('fs');

array.forEach( 
function(element)  {
    var http = require('http');
    var file_path = 'xml/' + element + '.xml';
    console.log(file_path);
    var file = fs.createWriteStream(file_path);
    var request = http.get('http://weather.yahooapis.com/forecastrss?w=' + element, function(response) {
        response.pipe(file);

    });

});

};
grabWeatherFiles( woeid_array );

此代码 sn-p 成功下载 XML 文件。但是,如果我尝试读取文件并在字符串中获取 XML 数据以便解析它,则文件为 0。 node.js 写得不正确吗?这发生在我的 Mac 和 c9.io 上。任何提示都会很可爱。我很困在这部分。

【问题讨论】:

    标签: javascript xml node.js npm


    【解决方案1】:

    您使用了错误的功能。 fs.writeFile 至少接受三个参数 filenamedatacallback。你不能管它。它只是将数据写入文件名并在完成后执行回调。

    您需要的是fs.createWriteStream,它采用路径(除了额外的选项)。它创建一个可写流,您可以通过管道将其输入响应。

    【讨论】:

      【解决方案2】:

      这些是我用来完成这项工作的步骤,并且有效。在 *.js 文件所在的同一级别创建了一个名为 xml 的文件夹。使用来自 http://woeid.rosselliot.co.nz/lookup/london 的一些有效 woeid 创建了 woeids.txt 文件

      使用路径定义创建代码的修改版本以使用__dirname(有用的解释:What is the difference between __dirname and ./ in node.js?)并将代码放入sample.js

      // This script requires request libraries.
      // npm install request
      
      var fs = require('fs');
      var woeid_array = fs.readFileSync(__dirname + '/woeids.txt').toString().split("\n");
      var grabWeatherFiles = function (array) {
          array.forEach( 
          function(element)  {
              var http = require('http');
              var file_path = __dirname + '/xml/' + element + '.xml';
              console.log(file_path);
              var file = fs.createWriteStream(file_path);
              var request = http.get('http://weather.yahooapis.com/forecastrss?w=' + element, function(response) {
                  response.pipe(file);
      
              });
      
          });
      };
      grabWeatherFiles( woeid_array );
      

      通过终端 node sample.js 运行它,它会使用正确的 xml 文件填充 xml 文件夹。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        • 1970-01-01
        • 2017-01-14
        • 2016-05-04
        • 1970-01-01
        • 2017-06-04
        • 1970-01-01
        相关资源
        最近更新 更多