Skip to content

Instantly share code, notes, and snippets.

@kaizhu256
Last active December 2, 2018 21:52
Show Gist options
  • Save kaizhu256/5644f9cc790ac9f78317 to your computer and use it in GitHub Desktop.
Save kaizhu256/5644f9cc790ac9f78317 to your computer and use it in GitHub Desktop.
nodejs - standalone code to upload data to amazon s3
/*
this standalone nodejs code requires the following env variables to be set:
process.env.AWS_ACCESS_KEY_ID
process.env.AWS_S3_BUCKET
process.env.AWS_SECRET_ACCESS_KEY
*/
/*jslint
bitwise: true, browser: true,
indent: 2,
maxerr: 8,
node: true, nomen: true,
regexp: true,
stupid: true,
todo: true
*/
(function () {
'use strict';
var options;
// init options
options = {
// init content-type
contentType: 'text/plain',
// init date used in hmac signature
date: new Date().toGMTString() + ' +0000',
// init data to upload
data: 'hello world!',
// init https method
method: 'PUT',
// init s3 url endpoint for uploaded data
// use env variable $AWS_S3_BUCKET
url: 'https://' + process.env.AWS_S3_BUCKET + '.s3.amazonaws.com/hello.txt'
};
// parse url used in https request
options.host = require('url').parse(options.url).host;
options.path = require('url').parse(options.url).path;
// init hmac signature used in https authorization header
// use env variable $AWS_SECRET_ACCESS_KEY
options.hmac = require('crypto').createHmac('sha1', process.env.AWS_SECRET_ACCESS_KEY);
options.hmac.update('PUT\n\n' + options.contentType + '\n' +
options.date + '\n' +
'/' + process.env.AWS_S3_BUCKET + options.path);
// init headers
options.headers = {
// use env variable $AWS_ACCESS_KEY_ID
authorization: 'aws ' + process.env.AWS_ACCESS_KEY_ID + ':' + options.hmac.digest('base64'),
'content-length': Buffer.byteLength(options.data),
'content-type': options.contentType,
date: options.date,
host: options.host
};
// init https request
options.request = require('https').request(options, function (response) {
response.on('data', function (chunk) {
// print error to stderr
console.error(String(chunk));
});
});
// PUT https data to s3
options.request.end(options.data);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment