我有这个功能
function isPlayerBanned(name,isbanned){
fs.readFile('bans.json', 'utf8', function (err,data) {
if (err) {
console.log(err);
}
var retorna;
var banFile = JSON.parse(data);
var isBanned = false;
if ( banFile[name] !== undefined ) {
isBanned = true;
}
if (isBanned){
var banExpiration = banFile[name];
var actualTime = new Date();
var banDate = new Date(banExpiration);
var timeban = banDate.getTime();
var time = actualTime.getTime();
if (time > timeban){
console.log("oi");
retorna = false;
} else {
console.log("falhou denovo :(");
retorna = true;
}
} else {
console.log('fail 2');
retorna = false;
}
return isbanned(retorna);
});
}
当我使用时:
isPlayerBanned(WHOIS.account, function(banned){
if (banned){
bot.say(channel,from + ": You can't add because you are banned. Use !isbanned [yourauthname] to know when the ban will expire.");
} else {
节点抛出该错误:“undefined不是函数” 为什么说'isbanned'是未定义的,如果它在函数上?
答案 0 :(得分:0)
这样的事情可能是:
function parse(str){
try {
var parsed = JSON.parse(str);
} catch(e) {
return false;
}
return parsed;
}
// pay attention to the use of "return" to evade indentation!
// returns 2 arguments in callback
// 1. error (== null, if no error)
// 2. true (user is banned) or false (user is not banned)
function isPlayerBanned(name, cb){
fs.readFile('bans.json', 'utf8', function (err,data) {
if (err) return cb(err);
var bans = parse(data);
if (!bans) return cb("JSON.parse failed");
// if username not in ban list, he is not banned!
if (!bans[name]) return cb(null, false);
// username in ban list, check if ban still active
var bannedTil = bans[name]; // UNIX timestamp in millisecs
var now = Date.now(); // UNIX timestamp in millisecs
// if ban is set to last till a lter point in time
// than the current time! User is still banned!
if (bannedTil > now) return cb(null, true);
// ban has expired, user not banned anymore
cb(null, false);
// TODO: delete the user from the bans.json file
// if his ban has expired
// tip: use an event, it's not relevant to the user
});
}
isPlayerBanned(WHOIS.account, function(err, banned){
if (err) return cb(err);
// banned is true or false, see isPlayerBanned
if (banned){
bot.say(channel,from + ": You can't add because you are banned.
Use !isbanned [yourauthname] to know when the ban will expire.");
} else {
// ...
}
}