3

I'm trying to interpolate a string loaded from a file in node.js without success.

The file contains template substitutions like: ${js-stuff}, which I want to resolve in the scope of whenever I evaluate the variable within the backticks.

I'm calling the string which contains the text loaded from the file 'template'.

I hoped console.log(`${template}`) would recursively resolve the template substitutions inside the template variable and print the result, but it seems as if I'm wrong as only the template-string get's printed out without it's template substitutions being resolved.

As the string interpolation doesn't work recursively, I would have to do something like console.log(``${template}``), but I'm not quite sure how.

Using the eval function I got it working like this:

console.log(eval(`\`${template}\``));

But this doesn't seem like the best way to do this?

TDLR; I don't want to evaluate a single variable using string interpolating, I want to evaluate a variable which contains a string consisting of a template substitution.

Jasper Catthoor
  • 595
  • 1
  • 6
  • 22
  • Are you preforming the `console.log` within loaded Javascript or in the actual console itself? – Xotic750 Sep 10 '16 at 10:22
  • `require('vm')` .. will help u .. best regards – Abdennour TOUMI Sep 10 '16 at 11:02
  • Template literals are compile-time things, there's no way to evaluate them apart from calling the js compiler, i.e. `eval` – georg Sep 10 '16 at 12:27
  • Another good resource is http://stackoverflow.com/questions/34882100/can-you-dumb-down-es6-template-strings-to-normal-strings/34883543#34883543. –  Sep 10 '16 at 18:34

0 Answers0