Created
October 10, 2012 21:39
-
-
Save modalsoul/3868625 to your computer and use it in GitHub Desktop.
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
// モジュールの読み込み | |
var util = require('util'); | |
url = require('url'); | |
http = require('http'); | |
// ダウンロードを実行する関数 | |
function download(urlStr) { | |
// URL文字列のパース | |
var options = url.parse(urlStr); | |
// http.clientRequestオブジェクトの組み立て | |
var request = http.request(options, function(res) {}); | |
// リクエストの送信終了 | |
request.end(); | |
// イベントハンドラの定義 | |
request.on('response', function(response) { | |
// ステータスコードとヘッダーの出力 | |
console.log(response.statusCode); | |
for(var i in response.headers) { | |
console.log(i + ":" + response.headers[i]); | |
} | |
console.log(''); | |
// データ取得イベントの非同期処理 | |
response.setEncoding('utf8'); | |
response.on('data', function(chunk) { | |
// chunkは受信したデータ(デフォルトでURF8エンコード) | |
util.print(chunk); | |
}); | |
// レスポンス終了イベントの非同期処理 | |
response.on('end', function() { | |
console.log(''); | |
}); | |
}); | |
} | |
download(process.argv[2]); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
動作には問題ないけど、モジュール読み込み部で
url
,http
がvarで宣言されてないからグローバル変数扱いになっちゃってるのが気になる。。コンマで区切って上げたほうが良いよ。
あと
function
もネームスペースはグローバルになるから気をつけた方がいいかも。var
指定ならその場のネームスペース内で定義できるよ。