Last active
March 20, 2023 22:42
-
-
Save mulhoon/9996d992e5c3518134d435372b0f5b96 to your computer and use it in GitHub Desktop.
Serve S3 files through express proxy
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
// Example of using express to proxy files from s3. | |
// Works with streaming media like mp4 | |
const AWS = require('aws-sdk') | |
const mime = require('mime-types') | |
const express = require('express') | |
AWS.config.update({ | |
secretAccessKey: '...', | |
accessKeyId: '...', | |
}) | |
const s3 = new AWS.S3({ params: { Bucket: 'bucketname' } }) | |
const app = express() | |
AWS.Request.prototype.forwardToExpress = function forwardToExpress(res, next, key) { | |
this.on('httpHeaders', function(code, headers) { | |
res.status(code) | |
if (code < 300) { | |
const newHeaders = { | |
...headers, | |
'Content-Type': mime.lookup(key), | |
} | |
// Remove some unwanted amazon headers | |
delete newHeaders['x-amz-id-2'] | |
delete newHeaders['x-amz-request-id'] | |
delete newHeaders['x-amz-meta-modified'] | |
res.set(newHeaders) | |
} | |
}) | |
.createReadStream() | |
.on('error', next) | |
.pipe(res) | |
} | |
app.get('/myfile.mp4', function(req, res, next) { | |
s3.getObject({ | |
Bucket: 'bucketname', | |
Key: 'myfile.mp4', | |
Range: req.headers.range, | |
}).forwardToExpress(res, next, key) | |
}) | |
app.listen(8000, () => console.log('App launched on port 8000')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment