简体   繁体   English

如何在Node.js中同时替换多个文件的内容?

[英]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]);
}

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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM