将stringreplace为node.js中的文本文件

我正在使用node.js 我想用一些占位符string读取文件,并在提供文件之前dynamicreplace它们。 这不是一个HTML文件,所以模板引擎将无法正常工作。

我怎样才能做到这一点?

如果模板引擎过度使用string.replace()

 temp = "Hello %NAME%, would you like some %DRINK%?"; temp = temp.replace("%NAME%","Michael Dillon"); temp = temp.replace("%DRINK%","tea"); console.log(temp); 

只需要更多的工作,就可以根据String对象中的标准方法创build一个通用模板函数。

模板引擎不仅适用于HTML。 例如,如果您使用Express,则可以设置自己的标题并指定一个内容types:

视图:

 var foo = "{{ bar }}"; 

渲染:

 app.get('/file.js', function(req, res, next) { res.render('templateName', { locals: {bar: 'quux'}, headers: {'content-type': 'text/javascript'} }); }) 

会产生:

 var foo = "quux"; 

如果您不使用Express,则只需呈现模板并使用您喜欢的任何内容types发送响应。