如何将文件内容解释为模板字符串

How to interpret file content as template string?

本文关键字:字符串 解释 文件      更新时间:2023-09-26

我想知道是否有办法将从文件中读取的内容用作模板字符串?

例如:我的文件hello_world.txt:

hello world from ${name}

然后像这样(使用 nodejs):

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

使用 eval() 函数似乎是可能的,但我不太喜欢这个解决方案。

谢谢

假设您信任正在读取的文件,您可以使用eval来完成此操作:

let message = "${greeting} World",
    greeting = "Hello";
    
alert(eval(`'`${message}'``))