Created
February 23, 2020 06:05
-
-
Save Mirochiu/990b88cd50bf94a93c111da0da5e7416 to your computer and use it in GitHub Desktop.
An aws s3 uploading sample code in Node.js
This file contains hidden or 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
console.log('Arg list below:'); | |
process.argv.forEach((val, index) => { | |
console.log(`${index}: ${val}`); | |
}); | |
function isEmpty(obj) { | |
return !Object.keys(obj).length; | |
} | |
var args = process.argv.slice(2); | |
if (isEmpty(args)) { | |
console.error('Please give a path for uploading'); | |
process.exit(0); | |
} | |
// ref: https://stackoverflow.com/questions/47535820 | |
function uploadToS3(key, body) { | |
var AWS = require('aws-sdk'); | |
var s3 = new AWS.S3(); | |
var bucketName = '{PLEASE-REPLACE-THIS-FOR-YOUR-BUCKET-NAME}'; | |
s3.upload({ | |
Bucket: bucketName, | |
ACL: 'public-read', | |
Body: body, | |
Key: key, | |
ContentType: 'application/octet-stream' | |
}, (err, response) => { | |
if (err) { | |
console.error(err); | |
} else { | |
console.log('uploading is succeed!', response); | |
} | |
}); | |
} | |
var uploadPath = args[0]; | |
var fs = require('fs'); | |
fs.access(uploadPath, fs.F_OK, (err) => { | |
if (err) { | |
console.error('fail to read from file:', uploadPath, err); | |
process.exit(-1); | |
} else { | |
var path = require('path'); | |
var uuid = require('node-uuid'); | |
var keyName = 'upload_' + uuid.v4() + path.extname(uploadPath); | |
uploadToS3(keyName, fs.createReadStream(uploadPath)); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment