简体   繁体   中英

Execute function from S3 downloaded JavaScript file without creating a local file on disk

Assume that we download the script below from S3 :

const sum_two = (a, b) => {
    return a + b;
}

Downloading using this:

async function downloadFileS3(filenameDownload) {
    const AWS = require('aws-sdk');
    const fs = require('fs');

    AWS.config.update(
        {
            accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXX",
            secretAccessKey: "YYYYYYYYYYYYYYYYYYYYY",
            correctClockSkew: true,
        }
    );

    const params = {
        Bucket: 'ZZZZZZZZZZZZZZZZZZZZZZZZ',
        Key: filenameDownload,
    }

    const s3 = new AWS.S3();
    try {
        const data = await s3.getObject(params).promise();
        if (data) {
            // do something with data.Body      
            const downloaded = data.Body.toString('utf-8');
            // grab sum_two from "downloaded" and use below 
            
            .......
            .......
            .......
        }
    }
    catch (error) {
        console.log(error);
    }

}

How can we extract sum_two (and use it afterwards) from downloaded WITHOUT creating a local file?

Meaning I don't want to use the code below !!!

// fs.writeFile(`${filenameDownload}`, downloaded, function (err) {
//    if (err) {
//         console.log('Failed to create file', err);
//    }
// console.log(sum_two(.... , ....));
// });

You can use node.js native vm module for this.

Create a Script from the downloaded code

Run it in the current context

After that the downloaded function will become available for usage:

const vm = require('vm');

// ...

const downloaded = data.Body.toString('utf-8');
const script = new vm.Script(downloaded);
script.runInThisContext()
console.log(sum_two(1,2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM