Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
How to compile and run a javascript code from string using node server

The scenario

I am planning to develop a small online judge site for hiring purpose, where I can create contests and participants can solve and submit their solutions.

For that I will provide them an online code editor, where they write their codes and submit. After the submission the source code will send to a node server using a POST request and the source code will send as a string.

Now the problem is how to compile and run the javascript code from string and get the result.

What have I tried

function runCode(code) {
    let input = 5;
    const wrap = source => `{ return ${source} };`;
    const fn = new Function(wrap(code));
    const output = fn.call(null).call(null, input); // The output is n * n = 5 * 5 = 25
  console.log(output);
}

runCode(`function myFunction(n) { return n * n; }`);

What am I seeking for-

The code is working perfectly, but I don't understand is this a good way to implement the scenario? Is there any other better & secure way? I've heard about the node's vm package.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda