Node.js无法更新文件中的项目

时间:2018-01-29 05:20:49

标签: javascript json node.js

我在更新用户时遇到了麻烦,我的目标是每隔x秒不断向用户添加积分。每次进入循环时,它只向最后一个用户添加10个点,即使我通过循环中的每个用户...任何帮助将不胜感激!

setInterval(function(){            
        var fs = require("fs");
        var data = fs.readFileSync('updatedPoints.txt', 'utf-8');
        fs.readFile("updatedPoints.txt", {encoding: "utf8"}, function(error, data){
        var i = 0;
        var currentUser = "";
        //Reads until nothing left in the file
        while(data[i] != null){                 
            currentUser += data[i]
            i++;
        }
        var splitUsers = currentUser.split(",");
        for(var i = 0; i < splitUsers.length - 1; i++){
            //Splits up the name right until the first bracket which holds the users current points
            var name = String(splitUsers[i].match(/^[^\(]+/g));     
            //Gets the users points         
            var userPoints = Number(splitUsers[i].match(/\(([^)]+)\)/)[1]);                 
            console.log(name);
            console.log(userPoints);                                                
            var test = userPoints + 10;
            var newValue = data.replace(name+"("+userPoints+")", name+"("+test+")");
            fs.writeFileSync('updatedPoints.txt', newValue, 'utf-8');
            console.log('readFileSync complete');                    
        }
    });
    }, 3000);

1 个答案:

答案 0 :(得分:1)

你应该在data.replace,
之后重置数据值 像那样

&#13;
&#13;
var newValue = data.replace ...

data = newValue
&#13;
&#13;
&#13;

因为string.replace不能直接重置字符串