【问题标题】:Replace string in a text file in node.js在 node.js 中替换文本文件中的字符串
【发布时间】:2011-03-01 05:07:40
【问题描述】:

我正在使用 node.js。我想读取带有一些占位符字符串的文件,并在提供文件之前动态替换它们。这不是 HTML 文件,因此模板引擎将无法工作。

我该怎么做?

【问题讨论】:

  • 我尝试将文件加载为字符串并进行正则表达式替换。想知道是否有更优雅的方式。
  • 你试过留胡子吗? mustache.github.com

标签: javascript node.js


【解决方案1】:

如果模板引擎太过分了,只需使用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 对象中的标准方法创建一个通用模板函数。

【讨论】:

    【解决方案2】:

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

    查看:

    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,您可以只渲染模板并使用您喜欢的任何内容类型发送响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 2017-08-28
      • 1970-01-01
      • 2022-07-12
      • 2012-03-24
      • 1970-01-01
      相关资源
      最近更新 更多