Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created September 29, 2011 05:02
Show Gist options
  • Save ishiduca/1250015 to your computer and use it in GitHub Desktop.
Save ishiduca/1250015 to your computer and use it in GitHub Desktop.
Node.js ファイルのダウンロード
var fs = require('fs');
var path = require('path');
var http = require('http');
// リンク先は .mp3 ファイル
var options = {
method : 'GET',
host : 'm.friendfeed-media.com',
port : '80',
path : '/0c5e82d9e6a0d5e60a1a85609adbe0e7f02976a6'
};
var req = http.request(options);
req.end();
req.on('response', function (res) {
onResponseCallback(res, options);
});
req.on('error', showError);
function onResponseCallback (res, opts) {
var ext = (res.headers['content-type'].split(/\//))[1];
var target = [ (opts['path'].split(/\?/))[0].replace(/^\//,''), ext ].join('.');
var writeStream = fs.createWriteStream(target);
writeStream.on('error', function (exception) {
throw exception;
});
writeStream.on('close', function () {
console.log('! Called "close" on writeStream');
});
//res.setEncoding('utf-8'); バイナリを扱うので指定しないと、 Buffer に
res.on('data', function (chunk) {
writeStream.write(chunk);
});
res.on('close', showError);
res.on('end', function () {
writeStream.end();
console.log(target);
});
}
function showError (e) {
console.log([ e.name, e.messsage ].join(': '));
return undefined;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment