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');
}
});
});
}
2 个解决方案
#1
1
You have a scoping issue.
你有一个范围问题。
By the time you are writing the files, key
is already at the last point.
当您编写文件时,密钥已经在最后一点。
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]);
}
#2
0
Or you could simply use the Array.prototype.forEach() (MDN Docs) without having to resort to a closure or an IIFE (Immediately Invoked Function Expression):
或者您可以简单地使用Array.prototype.forEach()(MDN Docs)而无需求助于闭包或IIFE(立即调用函数表达式):
fileArr.forEach(function(file) {
// do stuff
});
#1
1
You have a scoping issue.
你有一个范围问题。
By the time you are writing the files, key
is already at the last point.
当您编写文件时,密钥已经在最后一点。
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]);
}
#2
0
Or you could simply use the Array.prototype.forEach() (MDN Docs) without having to resort to a closure or an IIFE (Immediately Invoked Function Expression):
或者您可以简单地使用Array.prototype.forEach()(MDN Docs)而无需求助于闭包或IIFE(立即调用函数表达式):
fileArr.forEach(function(file) {
// do stuff
});