Reputation: 8913
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
Upvotes: 1
Views: 1996
Reputation: 82096
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'))
Upvotes: 2
Reputation: 40404
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);
Upvotes: 2