Get a Javascript file from Amazon S3 and run it within a Lambda function

Within S3, there exists a hello.js file that includes the following code snippet:

function greet() {
    console.log(" From Greetings: ");
}

An AWS Lambda function written in NodeJS is attempting to access and execute this script. Despite having the necessary permissions to retrieve the file from S3, the outcome of calling exec remains unclear. Although no errors are thrown, the expected output of "From Greetings" does not appear in the logs.

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const { exec } = require('child_process');

exports.handler = async (event, context) => {
    const s3Bucket = 'monitor-state';
    const s3Key = 'hello.js';

    
    const params = { Bucket: s3Bucket, Key: s3Key };

    try {
        const data = await s3.getObject(params).promise();
        const script = data.Body.toString();

        // Execute the script
        exec(`node -e "${script}"`, (error, stdout, stderr) => {
            if (error) {
                console.error(`Script execution error: ${error}`);
                return context.fail('Error executing the script.');
            } else {
                console.log('Script execution output:');
                console.log(stdout);
                return context.succeed('Script executed successfully.');
            }
        });
    } catch (error) {
        console.error('Error fetching the script from S3:', error);
        return context.fail('Error executing the script.');
    }
};

Despite experimenting with different approaches for invoking exec, none have resulted in the desired functionality.

Answer №1

Your lambda handler triggers the exec function, which does not wait for the child process to finish executing.

The exec function returns immediately, causing your async handler to return a completed promise right away. This signals Lambda to halt processing.

To address this issue, convert your exec callback into a promise and await its completion:

const AWS = require("aws-sdk");
const s3 = new AWS.S3();
const { exec } = require("child_process");

exports.handler = async () => {
  const s3Bucket = "monitor-state";
  const s3Key = "hello.js";

  const params = { Bucket: s3Bucket, Key: s3Key };

  const data = await s3.getObject(params).promise();
  const script = data.Body.toString();

  // Execute the script
  const [stdout, stderr] = await new Promise((resolve, reject) =>
    exec(`node -e "${script}"`, (error, stdout, stderr) => {
      if (error) {
        reject(error);
      }
      resolve([stdout, stderr]);
    }),
  );
  console.log('Script execution output:');
  console.log(stdout);
};

If you are using promises, there is no need to utilize context; any rejected promises will be handled as errors and logged in CloudWatch.

Consider the purpose of fetching code from S3 on every Lambda invocation. Depending on your requirements, it might be more efficient to store it in the Lambda layer or use Step functions instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for displaying a table with a button click

I am struggling to figure out how to embed a table inside a button in order to display the table when the button is clicked and hide it when clicked again. Below is the code I have been working with: function toggleTable(){ document.getElementById ...

What is the process by which Oracle HRMS retrieves the complete description of a job posting?

With my limited understanding of JavaScript, I noticed that the HRMS refreshes the page and displays the job details under the same URL as the job list page. I expected to find job detail information in the network requests, but upon inspecting them, I dis ...

Is there a method to adjust the styling of my <header> once the page hits a specific #anchor point?

Seeking some assistance with a website design challenge I am facing. I am currently working on a one-page portfolio site with four #anchor points that serve as "pages". Each div has a height of 100% to fill the entire browser height. The header, which co ...

Create a loop to iterate through dates within a specified range using the Fetch API

When I need to get the exchange rate from the bank for a specific interval specified in the input, I follow these steps. The interval is defined as [startdate; enddate]. However, in order to make a successful request to the bank, the selected dates must be ...

Managing several items within one function

I am working with a json file that contains similar data sets but different objects. { "AP": [{ "name": "Autogen Program" }, { "status": "Completed" }, { "start": "2014-05-05" }, { ...

Encountering issues with the hyperlink tag '<a>' in an HTML document

I've encountered an issue with the code on my HTML page: <body> <div align="center"> <a href="../index.html"> <img border="0" src="banner1.jpg" width="800" height="120" alt="Ecommerce Knowledge Base"> &l ...

Tips for incorporating external functions into Vue Component data synchronization:

As someone new to JavaScript, I am trying to incorporate external functions into Vue component data bindings, but I am encountering issues. helper.js function groupArrayOfObjects(list, key) { return blah blah } function parseDate(d) { ret ...

How can Node.js and Express be used to conceal Javascript code on the backend?

I'm a beginner when it comes to Node and Express. I have a query regarding how to securely hide Javascript code on the backend. Currently, I am working with Node.js and Express. My goal is to prevent users from easily accessing the code through browse ...

Ways to showcase a standalone identifier from iTunes RSS

I have a script below that fetches iTunes charts directly from the RSS and displays it. However, I am looking to only display the information for a specific ID from the RSS entry. Any suggestions on how this can be achieved? <script> jQuery(functi ...

Error encountered: When implementing mergeImages in express.js, a ReferenceError occurs stating that the window is not

I am encountering an issue while using mergeImages on my express.js server. The error message "ReferenceError: window is not defined" is displayed, but I am puzzled because I have not used the word 'window' in my code at all. Could you please rev ...

Mastering the art of redirection in Node.js

Encountering an issue with redirecting between directories - having trouble directing to another file in a different directory. Here is my directory structure: -views -add_user.jade -routes -index.js Attempting to redirect to add_user.jade from inde ...

Unable to click on hyperlinks in TinyMCE's read-only mode

I have a situation where I am displaying TinyMCE content inside a modal in read-only mode to show the user the information but not allow them to edit it. The content displays correctly, however, my links are not functioning. When clicked, they do not tri ...

Exploring the possibilities of using the typeof operator within an Event

I want to log some information if the input value is a number. However, I am facing an issue where it's not working and no bugs are appearing. Here is a snippet of code from CodePen (https://codepen.io/matoung/pen/KBNmPP) let button = document.que ...

What is the reason for the text not being written continuously in the textfield?

Looking to create a page for collecting user information. This is a Codesandbox.io page where the issue arises. https://codesandbox.io/s/material-demo-z1x3q?fontsize=14 When I try to input "d" continuously in the 성별* textfield, I can only enter "d" ...

Setting the state to an array of objects in React: A beginner's guide

Currently, I am developing a flashcard application using React. To store the data entered by the user, I have initialized my state as an array of objects that can hold up to 10 terms and definitions at a time: state = { allTerms: [ { ...

Using Google Apps Script to input data into the next available row

Utilizing Google Apps Script, I am retrieving data from another spreadsheet and storing it daily in a sheet named "DATABASE". Although my current solution is basic, it keeps overwriting existing data. I wish to enhance the script to copy data from the imp ...

Trouble with Mocha async hooks execution?

I keep encountering the issue of receiving 'undefined' for the page in this setup. It appears that none of Mocha's hooks are being executed. I've attempted adding async to the describe at the top level, used done statements, and even tr ...

Ways to avoid executing JavaScript code that is outputted in PHP

My question relates to the code snippet below, which is obtained via the jquery Data object on a php page. echo " var $d = $('<div/>', { id: 'hi' + $('#textResp').children().length, class: 'even ...

Tips for resolving a post 405 error on a Windows 2012 R2 server

My test application is designed to record camera footage and send the file to a directory on my server. The main code for this application is shown below: <!DOCTYPE html> <html> <head> <script src="https://cdn.WebRTC-E ...

Using JavaScript to dynamically add items from a menu and include a delete button for the option to remove them

//I am embarking on an exciting AJAX lab where I will be experimenting with dynamic element creation and deletion. Below is a snippet of the code to get started. //Generate elements and text nodes along with a deletion button for each item in the cart fu ...