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(.... , ....));
// });
CodePudding user response:
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))