From b028ec4aa7d33d1b9594670fff58860e5377017e Mon Sep 17 00:00:00 2001 From: Moto Ishizawa Date: Sun, 4 Mar 2012 17:44:02 +0900 Subject: [PATCH] =?UTF-8?q?HTTP=E3=83=AA=E3=82=AF=E3=82=A8=E3=82=B9?= =?UTF-8?q?=E3=83=88=E3=82=92=E9=80=81=E4=BF=A1=E3=81=97=E3=81=A6=E3=83=87?= =?UTF-8?q?=E3=83=BC=E3=82=BF=E3=82=92=E5=8F=97=E3=81=91=E5=8F=96=E3=82=8B?= =?UTF-8?q?=E3=81=BE=E3=81=A7=E3=82=92=E5=AE=9F=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.js | 43 +++++++++++++++++++++++++++++++++++++++ package.json | 7 ++++--- test/test-fetcher-http.js | 14 +++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 test/test-fetcher-http.js 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(); + }); + }); +}); +