Javascript 在 node.js 中替换文本文件中的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5150710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:51:48  来源:igfitidea点击:

Replace string in a text file in node.js

javascriptnode.js

提问by Sridatta Thatipamala

I am using node.js. I want to read a file with some placeholder strings and replace them dynamically before I serve the file. This is not an HTML file, so a templating engine will not work.

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

How can I do this?

我怎样才能做到这一点?

回答by Michael Dillon

If a template engine is overkill just use string.replace().

如果模板引擎是矫枉过正,只需使用string.replace().

temp = "Hello %NAME%, would you like some %DRINK%?";

temp = temp.replace("%NAME%","Michael Dillon");
temp = temp.replace("%DRINK%","tea");
console.log(temp);

With only a bit more work you could make a general purpose template function based on just the standard methods in the String object.

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

回答by Linus Gustav Larsson Thiel

Templating engines are not only for html. If you are using Express, for instance, you can set your own headers and specify a content-type:

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

View:

看法:

var foo = "{{ bar }}";

Rendering:

渲染:

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

Will yield:

将产生:

var foo = "quux";

If you are not using Express, you can just render the template and send the response with any content-type you like.

如果您不使用 Express,您可以只渲染模板并使用您喜欢的任何内容类型发送响应。