3

I was wondering if there was a way to use the content read from a file as a template string?

Ex: my file hello_world.txt :

hello world from ${name}

And then something like (with nodejs) :

var name = 'Jérémie';
var fileContent = fs.readFileSync('./hello_world.txt');
debug(fileContent); // Hello word from Jérémie

It seems possible, using the eval() function, but I don't really like this solution.

Thanks

Gnujeremie
  • 570
  • 3
  • 17
  • 1
    You should probably look into a real template library if you want something like this. I like [Handlebars.js](http://handlebarsjs.com/), as it's pretty light and easy to use. – ssube Feb 11 '16 at 16:55
  • @ssube I'm already using mustache, your solution would be to use it instead of a template string? – Gnujeremie Feb 11 '16 at 16:57
  • @apsillers yeah I saw this thread, but not sure I was really the target :-/ – Gnujeremie Feb 11 '16 at 16:59
  • 2
    @Gnujeremie if you're loading a string (not code) from a file, you have to either treat it as a mustache template or as code. Mustache will have better error handling and generally be safer than `eval`. – ssube Feb 11 '16 at 16:59
  • 2
    Why was this marked as a duplicate? The linked thread didn't deal at ALL with reading files and writing them after interpolating their content. – Developer Dave Aug 20 '18 at 17:56

1 Answers1

2

Assuming you trust the files you are reading, you can accomplish this with eval:

let message = "${greeting} World",
    greeting = "Hello";
    
alert(eval(`\`${message}\``))
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • 2
    As I said in my question, I know it is possible using eval() but I was looking for a solution without the eval() function. – Gnujeremie Feb 12 '16 at 07:44