1

I want to execute ES6 code at runtime using Node.js. Given a string of code:

const es6code = 'const square = (b) => { return b * b; }';
es6Eval(es6code)(5)

The es6Eval function would transpile es6 to es5 and evaluate the code at runtime.

How do I do this?

4
  • 1
    Given the const in your const es6code, you're running this code in an "ES6" (which is to say, ES2015+) environment. So...const f = eval(es6code) and then f(5) as necessary -- IF you trust the source of the code and are happy to run that code in your environment. Commented Feb 19, 2018 at 8:53
  • var fn = Function("alert('hello world')"); fn(); Commented Feb 19, 2018 at 8:54
  • 1
    Since you're using Node.js which does support ES6 just well, why not use the native eval function? Commented Feb 19, 2018 at 8:57
  • My comment above isn't quite right for that es6code; I've posted an answer that is. Commented Feb 19, 2018 at 9:02

1 Answer 1

6

First, let's get this out of the way: You MUST TRUST THE SOURCE OF THAT CODE. You're asking how to run arbitrary code from a string in your environment. If that code is malicious, bad things can happen. So you must trust the source of the code (e.g., whoever gave it to you).

Assuming you trust whomever you're getting the code from:

  1. Given the const in your const es6code, you're running this code in an "ES6" (which is to say, ES2015+) environment. So...

    const f = new Function(es6code + "; return square;")();
    // Note ----------------------^^^^^^^^^^^^^^^^^^^^^ ^^
    // And --------------------------------------------/
    

    then

    console.log(f(5)); // 25
    
  2. If you need to transpile it first, use the Node API for Babel to transform the code first:

    var code = require("babel-core").transform(es6code, options);
    

    ...and then do #1 on the result.

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

Comments

Your Answer

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