Skip to content

Instantly share code, notes, and snippets.

@modalsoul
Created October 10, 2012 21:13
Show Gist options
  • Select an option

  • Save modalsoul/3868441 to your computer and use it in GitHub Desktop.

Select an option

Save modalsoul/3868441 to your computer and use it in GitHub Desktop.
// モジュールの読み込み
var util = require('util');
url = require('url');
http = require('http');
// ダウンロードを実行する関数
function download(urlStr) {
// URL文字列のパース
var u = url.parse(urlStr);
// http.clientRequestオブジェクトの組み立て
var client = http.createClient(u.port || 80, u.hostname);
var request = client.request('GET', u.pathname, {host: u.hostname});
// リクエストの送信終了
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は受信したデータ(デフォルトでUTF8エンコード)
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