I would like to allow the users of my site (my colleagues) to create and run arbitrary functions on a Node.js server. The function can be uploaded to the server, where it is stored and when someone access a URL on that server, it should execute the function. The function needn't be checked or be executed in a sandbox and the code should be considered as trusted. How can I achieve something like this? I know this is very close to FaaS but I don't think it's the same... I still need the server to run some pre-processing on the request, etc.
I would like to allow the users of my site (my colleagues) to create and run arbitrary functions on a Node.js server. The function can be uploaded to the server, where it is stored and when someone access a URL on that server, it should execute the function. The function needn't be checked or be executed in a sandbox and the code should be considered as trusted. How can I achieve something like this? I know this is very close to FaaS but I don't think it's the same... I still need the server to run some pre-processing on the request, etc.
Share Improve this question asked Sep 13, 2017 at 8:59 riyaz-aliriyaz-ali 9,1122 gold badges25 silver badges39 bronze badges1 Answer
Reset to default 6If you truly understand all consequences, you can use form eval
function to run the code stored as text/string on server.
See here - https://nodejs/api/vm.html , e.g. like specified there:
Example: Running an HTTP Server within a VM
When using either script.runInThisContext()
or vm.runInThisContext()
, the code is executed within the current V8 global context. The code passed to this VM context will have its own isolated scope.
In order to run a simple web server using the http module the code passed to the context must either call require('http')
on its own, or have a reference to the http module passed to it. For instance:
'use strict';
const vm = require('vm');
const code = `
(function(require) {
const http = require('http');
http.createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('Hello World\\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
})`;
vm.runInThisContext(code)(require);
Note: The require()
in the above case shares the state with the context it is passed from. This may introduce risks when untrusted code is executed, e.g. altering objects in the context in unwanted ways.