This repository has been archived by the owner on Sep 3, 2019. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
dc3f7b9
commit b028ec4
Showing
3 changed files
with
61 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
var http = require('http'); | ||
var url = require('url'); | ||
|
||
var fetcher = {}; | ||
|
||
fetcher.fetch = function(req_url, option, cb) { | ||
// オプションの判定 | ||
if(typeof option == 'function') { | ||
cb = option; | ||
option = null; | ||
} | ||
|
||
// URLのパース | ||
var parsed_url = url.parse(req_url); | ||
|
||
// HTTPリクエスト | ||
var req = http.request(parsed_url, function(res){ | ||
var body = ''; | ||
|
||
// エンコードをUTF-8に固定 | ||
res.setEncoding('utf8'); | ||
|
||
// data イベントハンドラを設定 | ||
res.on('data', function(chunk) { | ||
body += chunk; | ||
}); | ||
|
||
// end イベントハンドラを設定 | ||
res.on('end', function() { | ||
cb(null, res, body); | ||
}); | ||
}); | ||
|
||
// HTTPリクエストエラー | ||
req.on('error', function(e) { | ||
cb(e, null, null); | ||
}); | ||
|
||
// HTTPリクエストを送信 | ||
req.end(); | ||
}; | ||
|
||
module.exports = fetcher; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
var should = require('chai').should(); | ||
var fetcher = require('../index.js'); | ||
|
||
describe('HTTP', function() { | ||
it('HTTPリクエスト', function(done) { | ||
var url = 'http://www.yahoo.co.jp'; | ||
fetcher.fetch(url, function(err, res, data){ | ||
res.statusCode.should.equal(200); | ||
data.should.be.a('string'); | ||
done(); | ||
}); | ||
}); | ||
}); | ||
|