[英]How do you replace content of multiple files at the same time in Node.js?
The problem here is only the last file is being modified. 这里的问题是仅修改了最后一个文件。 But all of the files returns success messages.
但是所有文件都返回成功消息。 What's wrong with it?
它出什么问题了? Thanks.
谢谢。
var fs = require('fs'),
fileArr = [
'base/general.css',
'components/bootstrap_icons.css',
'components/fullpage_slider.css'
];
for(var key in fileArr) {
fs.readFile(fileArr[key],'utf8', function(err,data) {
if(err){
return console.log(err);
} else {
console.log('success');
}
var result = data.replace(/([^\/][.*]|[(.]).*?(\bimages\b)/g,'(images');
fs.writeFile(fileArr[key], result, 'utf8', function(err) {
if(err) {
return console.log(err);
} else {
console.log('success');
}
});
});
}
You have a scoping issue. 您有范围问题。
By the time you are writing the files, key
is already at the last point. 在编写文件时,
key
已经在最后一点。
Try this instead: 尝试以下方法:
for (var key in fileArr) {
(function (file) {
//new scope for this file
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
return console.log(err);
} else {
console.log('success');
}
var result = data.replace(/([^\/][.*]|[(.]).*?(\bimages\b)/g, '(images');
fs.writeFile(file, result, 'utf8', function (err) {
if (err) {
return console.log(err);
} else {
console.log('success');
}
});
});
})(fileArr[key]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.