Last active
July 22, 2016 22:43
-
-
Save kawanet/5697626 to your computer and use it in GitHub Desktop.
Download a file and directly upload it to Amazon S3. ファイルを外部のウェブサーバからダウンロードして、そのまま S3 にアップロードする。
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
/*! s3mirror.js */ | |
var knox = require("knox"); | |
var http = require("http"); | |
var opts = { | |
source: 'http://www.example.com/title.png', | |
knox: { | |
endpoint: 's3-ap-northeast-1.amazonaws.com', // tokyo region | |
key: '<api-key-here>', | |
secret: '<secret-here>', | |
bucket: '<bucket-here>' | |
}, | |
dest: '/mirror' | |
}; | |
s3mirror(opts, function(err, url) {/* */}); | |
function s3mirror(opts, callback) { | |
var client = knox.createClient(opts.knox); | |
var path = opts.source.replace(/^[^\/]*:?\/+/, '/'); | |
path = (opts.dest || '') + path; | |
var dest = 'http://' + opts.knox.bucket + path; | |
http.get(opts.source, function(res) { | |
if ((res.statusCode + '').substr(0, 1) != '2') { | |
callback(new Error('STATUS ' + res.statusCode)); | |
return; | |
} | |
var headers = { | |
'Content-Length': res.headers['content-length'], | |
'Content-Type': res.headers['content-type'] | |
}; | |
client.putStream(res, path, headers, function(err, result) { | |
if (err) { | |
callback(err); | |
} else { | |
callback(null, dest); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment