用nodejs替换文件中的字符串 [英] Replace a string in a file with nodejs
本文介绍了用nodejs替换文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 md5 grunt任务生成MD5文件名。现在我想用任务回调中的新文件名重命名html文件中的源文件。我想知道最简单的方法是什么。
I use the md5 grunt task to generate MD5 filenames. Now I wanna rename the sources in the html file with the new filename in the callback of the task. I wonder whats the easiest way to do this.
推荐答案
您可以使用简单的正则表达式:
You could use simple regex:
var result = fileAsString.replace(/string to be replaced/g, 'replacement');
所以...
So...
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屋!
查看全文