2016-11-18 101 views
0

我试图用Node.js来抓取一个网页的内容,并将它与我存储为一个文件的同一页的副本进行比较,如下所示:request()和fs.createReadStream()不返回“正确的”值

var fs = require("fs"); 
var request = require("request"); 
var archive = ["./archive.html", "http://praguerace.com/comic/archive"]; 

request(archive[1], //request Prague Race's archive 
    function (error, response, body) { 
     if (fs.createReadStream(archive[0]) == body) //if no change occurred 
      console.log("checkpoint 1"); 
     else 
      console.log("checkpoint 2"); 
    } 
); 

我已经安装(正确)安装了Request模块,并且没有使用Express。

问题是,脚本不断打印“检查点2”,就好像我从服务器获取的响应一直在变化,或者节点不知道什么==意味着什么。

回答

1

fs.createReadStream(存档[0])返回一个流,而不是内容

使用流事件来检索内容,readStream.on( '开放', '数据',等等

或者只是使用READFILE或readFileSync

异步版本:

request(archive[1], //request Prague Race's archive 
function (error, response, body) { 
    fs.readFile(archive[0], "utf8", function(err, data){ 
    if(data == body) 
     .... 
    else 
     .... 
    }); 
}); 

同步版本

request(archive[1], //request Prague Race's archive 
function (error, response, body) { 
    if(fs.readFileSync(archive[0], "utf8") == body) 
     .... 
    else 
     .... 
});