2016-12-23 8 views
2

私はr/theonionを盗んで、タイトルをテキストファイルonion.txtに書きます。それから、私は悲しみを掻き集め、タイトルをテキストファイルに書いてみようと思っています。notion.txtではありません。私はonion.txtに書き込むことに成功しますが、nottheonion.txtには成功しません。NodeJS:約束を持った2つの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

*ただしnottheonion.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

nice ........ :) – Alnitak

関連する問題