【发布时间】:2016-01-18 08:50:47
【问题描述】:
我有很长的 HTML 文件,我使用它转换为字符串
var str = fs.readFile(path, 'utf8', callBabk);
比我想用其他东西替换部分字符串:
str = str.replace('toReplace', 'replaceWithThis');
但这不起作用。
有什么想法吗?
编辑:
完整代码为:
exports.fileToString = function(path){
return new Promise(function(resolve, reject){
fs.readFile(path, 'utf8', function(err, data) {
if (err) {
return reject(err);
}
return resolve(data);
});
});
};
然后在另一个文件中:
var htmlString = '';
Promise.all([
htmlString = fileUtils.fileToString('../file.html'),
]).then(function() {
htmlString = htmlString.replace('toReplace', 'replaceWithThis');
console.log('htmlString: ' + htmlString); //This never prints
}. reject);
【问题讨论】:
-
添加完整代码。 minimal reproducible example
-
如果你想替换所有出现的文本,你需要使用正则表达式与
g标志/toReplace/g -
另外 readFile 不返回字符串,你在回调中得到字符串形式。
标签: javascript node.js string