Skip to content

Instantly share code, notes, and snippets.

@peter
Last active August 6, 2021 05:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peter/09c15ef07ef7114a216b4c62db470b0e to your computer and use it in GitHub Desktop.
Save peter/09c15ef07ef7114a216b4c62db470b0e to your computer and use it in GitHub Desktop.
File upload from Node.js to Amazon S3 with the REST API and the minimal aws4 npm package
#!/usr/bin/env node
// This script uploads a local file to S3
// Depends on the aws4 npm package for AWS signatures
// Usage:
// AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... s3-upload
const fs = require('fs')
const https = require('https')
const aws4 = require('aws4') // Handles complex AWS signatures: http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
const FILE_PATH = '...'
const BUCKET = '...'
const REGION = '...'
const S3_PATH = '...'
const ACL = 'public-read'
const data = fs.readFileSync(FILE_PATH)
const opts = {
host: `${BUCKET}.s3.amazonaws.com`,
service: 's3',
region: REGION,
path: S3_PATH,
method: 'PUT',
headers: {
'x-amz-acl': ACL
},
body: data
}
aws4.sign(opts)
console.log(`Uploading file...`)
const req = https.request(opts, function(res) {
console.log(`File upload complete status=${res.statusCode}`)
res.pipe(process.stdout)
})
req.end(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment