Advertisement
Javi

AWS: Lambda for S3 processing

Dec 21st, 2020
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. const os = require('os');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const readline = require('readline');
  5. const aws = require('aws-sdk');
  6. const s3 = new aws.S3();
  7.  
  8. async function downloadFileFromS3 (bucket, fileKey, filePath) {
  9. console.log('downloading', bucket, fileKey, filePath);
  10. return new Promise(function (resolve, reject) {
  11. const file = fs.createWriteStream(filePath),
  12. stream = s3.getObject({
  13. Bucket: bucket,
  14. Key: fileKey
  15. }).createReadStream();
  16. stream.on('error', reject);
  17. file.on('error', reject);
  18. file.on('finish', function () {
  19. console.log('downloaded', bucket, fileKey);
  20. resolve(filePath);
  21. });
  22. stream.pipe(file);
  23. });
  24. };
  25.  
  26. async function processFile(filePath) {
  27. console.log(`Processing ${filePath}.`);
  28. return new Promise(function (resolve, reject) {
  29. const outputPath = `${filePath}.out`;
  30. const readFile = readline.createInterface({
  31. input: fs.createReadStream(filePath),
  32. output: fs.createWriteStream(outputPath),
  33. terminal: false
  34. });
  35.  
  36. readFile
  37. .on('line', transform)
  38. .on('close', function() {
  39. console.log(`Created "${this.output.path}"`);
  40. resolve(outputPath);
  41. });
  42.  
  43. function transform(line) {
  44. this.output.write(line.toUpperCase() + '\n');
  45. }
  46. });
  47. }
  48.  
  49. async function uploadFileToS3 (bucket, fileKey, filePath, contentType) {
  50. console.log('uploading', bucket, fileKey, filePath);
  51. return s3.upload({
  52. Bucket: bucket,
  53. Key: fileKey,
  54. Body: fs.createReadStream(filePath),
  55. ACL: 'private',
  56. ContentType: contentType
  57. }).promise();
  58. };
  59.  
  60. exports.handler = async function (eventObject, context) {
  61. const OUTPUT_BUCKET = 'demo-s3-output';
  62. const eventRecord = eventObject.Records && eventObject.Records[0];
  63. const inputBucket = eventRecord.s3.bucket.name;
  64. const key = eventRecord.s3.object.key;
  65. const workdir = os.tmpdir();
  66. const inputFile = path.join(workdir, key);
  67.  
  68. console.log(`Transforming ${key} using ${inputFile}`);
  69. await downloadFileFromS3(inputBucket, key, inputFile);
  70. const newFile = await processFile(inputFile);
  71. await uploadFileToS3(OUTPUT_BUCKET, key, newFile);
  72. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement