diff --git a/index.js b/index.js index e69de29..74ff8bc 100644 --- a/index.js +++ b/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; diff --git a/package.json b/package.json index 5d1a80e..ae44f16 100644 --- a/package.json +++ b/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 ", "main": "./index", @@ -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": "*" } } diff --git a/test/test-fetcher-http.js b/test/test-fetcher-http.js new file mode 100644 index 0000000..306bf23 --- /dev/null +++ b/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(); + }); + }); +}); +