1

fs.readFile(), fs.readFileSync() and also Amazon S3 return a Buffer object. How can I use this Buffer as actual JavaScript code that I can execute?

Here is a very basic example.

some-file.js:

module.exports = function () {
    console.log('hello');
};

main.js

const data1 = fs.readFileSync('./some-file.js'); // This is a Buffer
const data2 = fs.readFileSync('./some-file.js', 'utf-8'); // This is a string

data1(); // Error: data1 is not a function
JSON.parse(data2)(); // Error: data2 is no valid JSON
2
  • What do you want to do exactly, what's your expected output? Commented Dec 2, 2019 at 14:48
  • I load a file from Amazon S3 that contains JavaScript function (Handlebars template) that I need to execute. Commented Dec 2, 2019 at 14:49

2 Answers 2

2

If you want to execute javascript code, instead of using eval, which can be quite a security risk, you should use built-in module vm

const vm = require('vm');

const sandbox = { x: 2 }; // pass variables or some context if you want
vm.createContext(sandbox); // Contextify the sandbox.

const code = buffer.toString(); // your buffer
vm.runInContext(code, sandbox);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I would never come up with this! The documentation states that this gives no security mechanism, so why consider using vm instead of eval()?
Because it does not give you access to node modules. So they won't be able to use fs or other modules, allowing them to read/write or wipe your disk. It has some settings to prevent infinite loops, and it runs in another context that doesn't have access to your variables.
2

It sounds like you are after something like eval for the function scenario (not the evil version, this one leverages the vm module). The other option here is to save the contents of the buffer to a file and then let require do it's thing (not sure if that's an option for you).

The object scenario is simpler, if Buffer is a JSON string then you should simply be able to call JSON.parse(buffer.toString('utf8'))

3 Comments

Seems like .toString() and then eval() is my only rescue. I was hoping to avoid using eval()
Saving to a file is not an option for me since my code is executed serverless so i dont have a filesystem
@Mick the eval library I've linked too is safer than native eval, it leverages Node's VM module, so a lot safer. Alternatively, you can use this module directly, the library just provides a neater interface for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.