Skip to content
This repository has been archived by the owner on Sep 3, 2019. It is now read-only.

Commit

Permalink
HTTPリクエストを送信してデータを受け取るまでを実装
Browse files Browse the repository at this point in the history
  • Loading branch information
summerwind committed Mar 4, 2012
1 parent dc3f7b9 commit b028ec4
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 3 deletions.
43 changes: 43 additions & 0 deletions index.js
@@ -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;
7 changes: 4 additions & 3 deletions package.json
@@ -1,7 +1,7 @@
{
"name": "fetcher",
"version": "0.0.1",
"description": "A simple URI fetcher.",
"description": "A simple URI fetcher for Node.js.",
"keywords": ["http", "uri", "fetch"],
"author": "Moto Ishizawa <summerwind.jp@gmail.com>",
"main": "./index",
Expand All @@ -13,12 +13,13 @@
"node": ">= 0.4.x < 0.8.0"
},
"scripts": {
"test": "make test"
"test": "./node_modules/.bin/mocha"
},
"dependencies":{
"iconv": "1.1.3"
},
"devDependencies": {
"mocha": "*"
"mocha": "*",
"chai": "*"
}
}
14 changes: 14 additions & 0 deletions test/test-fetcher-http.js
@@ -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();
});
});
});

0 comments on commit b028ec4

Please sign in to comment.