2016-12-23 40 views
2

我在抓取r/theonion并将标题写入文本文件onion.txt。之后,我打算把这些标题写入文本文件nottheonion.txt。我成功写入onion.txt,但不写入notononion.txt。NodeJS:用承诺修复两个URL

var onion_url = "https://www.reddit.com/r/theonion"; 
var not_onion_url = "https://www.reddit.com/r/nottheonion"; 

var promise = new Promise(function(resolve, reject) { 

    request(onion_url, function(error, response, html) { 
     if (error) { 
      console.log("Error: " + error); 
     } 

     var $ = cheerio.load(html); 

     $("div#siteTable > div.link").each(function(idx) { 
      var title = $(this).find('p.title > a.title').text().trim(); 
      console.log(title); 

      fs.appendFile('onion.txt', title + '\n'); 
     }); 
     }); 
    }); 

promise.then(function(result) { 
    request(not_onion_url, function(error, response, html) { 
     if (error) { 
      console.log("Error: " + error); 
     } 

     var $ = cheerio.load(html); 

     $("div#siteTable > div.link").each(function(idx) { 
      var title = $(this).find('p.title > a.title').te . xt().trim(); 
      console.log(title); 

      fs.appendFile('not_onion.txt', title + '\n'); 
     }); 
    }); 
}, function(err) { 
    console.log("Error with scraping r/nottheonion"); 
}); 
+0

*但not notononion.txt *,你必须得到一些错误?你试过调试它吗? – Mritunjay

+2

你没有调用'promie'的'resolve'。 –

回答

2

使用request-promisefs-promise。如果你想使用的承诺,并使用功能不重复自己,以简化你的代码。

var rp = require('request-promise'); 
var fsp = require('fs-promise'); 

var onion_url = "https://www.reddit.com/r/theonion"; 
var not_onion_url = "https://www.reddit.com/r/nottheonion"; 

function parse(html) { 
    var result = ''; 
    var $ = cheerio.load(html); 
    $("div#siteTable > div.link").each(function(idx) { 
     var title = $(this).find('p.title > a.title').text().trim(); 
     console.log(title); 
     result += title + '\n'; 
    }); 
    return result; 
} 

var append = file => content => fsp.appendFile(file, content); 

rp(onion_url) 
    .then(parse) 
    .then(append('onion.txt')) 
    .then(() => console.log('Success')) 
    .catch(err => console.log('Error:', err)); 

rp(not_onion_url) 
    .then(parse) 
    .then(append('not_onion.txt')) 
    .then(() => console.log('Success')) 
    .catch(err => console.log('Error:', err)); 

这没有测试。

+1

不错........ :) – Alnitak