Created
March 19, 2015 03:12
-
-
Save joerx/f7bb652460ab70f1aacb to your computer and use it in GitHub Desktop.
Uploading a file to 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
require('./.env'); // AWS config is set here via process.env. | |
var Aws = require('aws-sdk'); | |
var uniqid = require('uniqid'); | |
var fs = require('fs'); | |
var s3 = new Aws.S3(); | |
const BUCKET_NAME = 'test-joerx'; | |
const BUCKET_REGION = 'eu-west-1'; | |
function bail(err) { | |
if (!err) return; | |
console.error(err.stack); | |
process.emit('error', err); | |
process.exit(1); | |
} | |
function getOrCreateBucket(conf, cb) { | |
var bucketName = conf.name, bucketRegion = conf.region; | |
s3.headBucket({Bucket: bucketName}, function(err, res) { | |
if (err && err.statusCode === 404) { | |
var params = { | |
Bucket: bucketName, | |
ACL: 'public-read', | |
CreateBucketConfiguration: { | |
LocationConstraint: bucketRegion | |
} | |
}; | |
s3.createBucket(params, function(err, res) { | |
if (err) cb(err); | |
else s3.waitFor('bucketExists', {Bucket: BUCKET_NAME}, cb); | |
}); | |
} else { | |
return err ? cb(err) : cb(null, {status: 'ok'}); | |
} | |
}); | |
} | |
function upload(path, bucket, key, cb) { | |
var str = fs.createReadStream(path); | |
var params = { | |
Bucket: bucket, | |
Body: str, | |
ACL: 'public-read', | |
Key: key | |
} | |
s3.upload(params, function(err, res) { | |
if (err) return cb(err); | |
console.log('Uploaded to ' + res.Location); | |
cb(null, {location: res.Location}); | |
}); | |
} | |
getOrCreateBucket({name: BUCKET_NAME, region: BUCKET_REGION}, function(err, res) { | |
if (err) return bail(err); | |
var key = uniqid(); | |
upload(__dirname + '/sample.jpg', BUCKET_NAME, key, function(err, res) { | |
if (err) return bail(err); | |
var file = fs.createWriteStream(__dirname + '/out.jpg'); | |
var str = s3.getObject({Bucket: BUCKET_NAME, Key: key}).createReadStream(); | |
str.on('end', console.log.bind(null, 'done')); | |
str.pipe(file); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment