用 nodejs 替换文件中的字符串 [英] Replace a string in a file with nodejs
本文介绍了用 nodejs 替换文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 md5 grunt task 来生成 MD5 文件名.现在我想在任务的回调中使用新文件名重命名 HTML 文件中的源.我想知道最简单的方法是什么.
I use the md5 grunt task to generate MD5 filenames. Now I want to rename the sources in the HTML file with the new filename in the callback of the task. I wonder what's the easiest way to do this.
推荐答案
你可以使用简单的正则表达式:
You could use simple regex:
var result = fileAsString.replace(/string to be replaced/g, 'replacement');
所以...
var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(/string to be replaced/g, 'replacement');
fs.writeFile(someFile, result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
这篇关于用 nodejs 替换文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文