Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在nodejs redis.hget()函数中更新数组值?_Javascript_Node.js_Closures_Node Redis - Fatal编程技术网

Javascript 如何在nodejs redis.hget()函数中更新数组值?

Javascript 如何在nodejs redis.hget()函数中更新数组值?,javascript,node.js,closures,node-redis,Javascript,Node.js,Closures,Node Redis,我想创建聊天日志的二维数组,其中第一个数组表示用户ID,嵌套数组表示与用户相关的聊天日志。但我并没有找到在subscriber.hget()函数的数组中插入“arrChatMembersLog”的方法。当我获取数组值时,它总是空的,否则,如果我试图在subscriber.hget()调用的函数“callbacksubscriberGetMessageTable()”中打印数组,它会显示2d数组,其中除运行循环的消息外,所有数组都为空。您能提供任何解决方案吗?我应该在arrChatMembersL

我想创建聊天日志的二维数组,其中第一个数组表示用户ID,嵌套数组表示与用户相关的聊天日志。但我并没有找到在subscriber.hget()函数的数组中插入“arrChatMembersLog”的方法。当我获取数组值时,它总是空的,否则,如果我试图在subscriber.hget()调用的函数“callbacksubscriberGetMessageTable()”中打印数组,它会显示2d数组,其中除运行循环的消息外,所有数组都为空。您能提供任何解决方案吗?我应该在arrChatMembersLog array()中填充所有聊天日志

方法信息::

获取旧数据():

它是执行开始的主要方法。用户通过点击他/她的名字与想要的朋友聊天。当点击时,它会显示聊天窗口并发送即时消息。消息发送时,它会获取他们之间过去的所有对话。它获取在redis中创建的所有通道

CallbackSubscriberGetAll():

它获取所有消息更改并将所有消息ID存储在一个数组中。使用该数组,我从散列中获取消息

CallbackSubscriberGetMessageTable():

它根据调用callbacksubscriberGetAll()函数创建的数组获取所有消息。这里出现了实际的问题。我想在arrChatMembersLog数组中存储所有消息数据。但由于nodejs的异步特性,我无法在arrChatMembersLog中保存所有数组值

所需的数组格式

第一个索引指示用户ID,第二个索引将是该用户的聊天日志

arr[1][0] = {},
arr[1][1] = {},
arr[1][2] = {},

arr[2][0] = {},
arr[2][1] = {},
arr[2][2] = {},

arr[3][0] = {},
arr[3][1] = {},
arr[3][2] = {},
server.js

/*
* -------------------
*快车
*
* -------------------
*/
var app=require('express')(),
http=require(“http”),
url=require('url'),
cookieParser=require('cookie-parser'),//会话存储在cookie中,因此我们使用它来解析它
session=require('nodephpssessions')。SessionHandler,
sessionHandler=新会话(),
摩根=要求(“摩根”),
expressSession=require(“快速会话”),
phpUnserialize=require(“php非序列化”),
sessionStore=新建expressSession.MemoryStore(),
parseUrl=null,uId=null,uName=null,uEmail=null;
//事务记录器
应用程序使用(摩根(“开发”));
//在expressxSession之前必须使用cookieParser
使用(cookieParser());
应用程序使用(expressSession)({
名字:“神童”,
秘密:“47760ae7-9660-4d4c-b15d-b9986edccbf3ss”,
商店:sessionStore,
saveUninitialized:true,
雷萨夫:是的,
曲奇:{
路径:“/”,
httpOnly:true,
安全:是的,
maxAge:null,
}
}));
//set(app.session({secret:'secret',key:'express.sid'}));
应用程序使用(功能(请求、恢复、下一步){
res.header(“访问控制允许原点”、“*”);
res.header(“访问控制允许标头”、“X请求的标头”);
res.header(“访问控制允许头”,“内容类型”);
res.header(“访问控制允许方法”、“PUT、GET、POST、DELETE、OPTIONS”);
next();
});
app.set('host','localhost');
//var port=normalizePort(process.env.port | |“3000”);
//应用程序集(“端口”,端口);
应用程序集(“端口”,“3000”)//进程环境端口
/*
* -------------------
*插座连接
* -------------------
*/
//var server=require('http')。createServer(应用程序);
var server=http.createServer(函数(req,res){
parseUrl=url.parse(req.url,true).query;
if(“string”==typeof(parseUrl.dataJSON)){
var _objUser=JSON.parse(parseUrl.dataJSON);
uId=(|objUser.user|id==未定义的| | | objUser.user|id===“”| | | objUser.user_id==空)?空:|objUser.user_id;
uName=(|objUser.username==未定义的| | | | | | | | objUser.username==空)?空:|objUser.username;
uEmail=(|objUser.user|email==未定义的| | | | | objUser.user|email====“”| | | | objUser.user| email==空)?空:|objUser.user|email;
}    
res.writeHead(200,{'Content-type':“text/plain”});
res.end(sessionHandler.run(parseUrl));
});
var io=require('socket.io')(服务器);
server.listen(app.get(“端口”)、app.get(“主机”)、函数(){
log(“服务器启动并运行…”);
});
server.on('error',函数(e){
console.log(“发生错误:+e”);
});
//io.set('日志级别',3);
/*
* -------------------
*雷迪斯
* -------------------
*/
var redis=需要(“redis”);
/*
*寄件人
*/
var publisher=redis.createClient();
/*
*接受者
*/
var subscriber=redis.createClient();
/*
*消息计数器
*/
//var messageLen=llen消息;
/*
*所有通道列表(使用Z排序集)
*排序集名称:通道
*/
var通道计数=0;
var channel_name=“channel”;
var用户_通道=0
/*

*所有用户的列表(使用ZIt的太多代码进行排序的集合,请尽量简化到最少。@Jonatas:谢谢。我更新了我的问题,更简要地解释了从何处开始调试代码,实际错误发生在何处,我希望得到什么结果?如果您对问题有任何疑问,请告诉我,我将尝试更简要地解释您。p问题是你一次就把整个应用程序放进去了。每个问题你都会有一个问题。例如“如何插入这个对象/数组…”,等等。代码太多,看不清,请尽量简化到最低程度。@Jonatas:谢谢。我更新了我的问题,更简要地解释了从何处开始调试代码,实际错误发生在何处,我希望得到什么结果?不过,如果您对问题有任何疑问,请告诉我,我将尝试更简要地解释您。问题em是指您一次将整个应用程序放在一起。每个问题都可能有一个问题。例如,“如何插入此对象/数组…”等等。
/*
 * -------------------
 * Express
 *
 * -------------------
 */
var app = require('express')(),
        http = require("http"),
        url = require('url'),
        cookieParser = require('cookie-parser'), // the session is stored in a cookie, so we use this to parse it
        session = require('nodePhpSessions').SessionHandler,
        sessionHandler = new session(),
        morgan = require("morgan"),
        expressSession = require("express-session"),
        phpUnserialize = require("php-unserialize"),
        sessionStore = new expressSession.MemoryStore(),
        parseUrl = null, uId = null, uName = null, uEmail = null;

// Transaction logger
app.use(morgan("dev"));

// must use cookieParser before expressxSession
app.use(cookieParser());
app.use(expressSession({
    name: "Whizchat",
    secret: '47760ae7-9660-4d4c-b15d-b9986edccbf3ss',
    store: sessionStore,
    saveUninitialized: true,
    resave: true,
    cookie: {
        path: "/",
        httpOnly: true,
        secure: true,
        maxAge: null,
    }
}));

//app.set(app.session({secret: 'secret', key: 'express.sid'}));
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
    next();
});
app.set('host', "localhost");
//var port = normalizePort(process.env.PORT || '3000');
//app.set('port', port);
app.set('port', "3000"); //process.env.PORT

/*
 * -------------------
 * Socket Connections
 * -------------------
 */
//var server = require('http').createServer(app);
var server = http.createServer(function (req, res) {
    parseUrl = url.parse(req.url, true).query;

    if ("string" === typeof (parseUrl.dataJSON)) {
       var _objUser = JSON.parse(parseUrl.dataJSON);
        uId = (_objUser.user_id === undefined || _objUser.user_id === "" || _objUser.user_id === null) ? null : _objUser.user_id;
        uName = (_objUser.username === undefined || _objUser.username === "" || _objUser.username === null) ? null : _objUser.username;
        uEmail = (_objUser.user_email === undefined || _objUser.user_email === "" || _objUser.user_email === null) ? null : _objUser.user_email;
    }    
    res.writeHead(200, {'Content-type': "text/plain"});
    res.end(sessionHandler.run(parseUrl));
});

var io = require('socket.io')(server);
server.listen(app.get("port"), app.get("host"), function () {
    console.log("Server up and running...");
});

server.on('error', function (e) {
    console.log("Error occured :" + e);
});
//io.set('log level', 3);

/*
 * -------------------
 * Redis 
 * -------------------
 */
var redis = require("redis");
/*
 *  Sender
 */
var publisher = redis.createClient();
/*
 * Receiver
 */
var subscriber = redis.createClient();

/*
 * Message counter
 */
//var messageLen = llen messages;

/*
 * List of all channels (sorted set using Z<command>)
 * Sorted set name : channels
 */
var channel_Count = 0;
var channel_name = "channel";
var user_channel = 0
/*
 * Lists of all users (sorted set using Z<command)
 * Sorted set name : onlineusers
 */
var userlists = [], usersSocket = [];
var uids = [], socketids = [];
var get_old_communication_channel_name = "";
/*
 * All Users related channels set ( unordered/unsorted set using s<command>)
 * Unsorted set name : userschannel
 */
var usersChannels;
var msgChannel = "messageChannelSet";
var messageTable = "messageTable";
/*
 * Message set (sorted set)
 */
var message_Id = 1;
//global array 
var arr_msg_id = [];
var arr_sender_reciver_msg = [];

var employees = [];
var arr1 = [];
var arr11 = [];
/*
 * User set
 */
var channelSet;
var countMember, countChannel;
var arrChatMembersLog = [];
/*
 * Identified that user_reference_id based set (unordered) is generated or not
 */
/*foreach userSet on <user>
    var countMember = smembers <user>;
    if(countMember is empty set or nil){
        isNewChannelGenerate = true;
    }
endforeach
*/
/*
 * -------------------
 * Mysql
 * -------------------
 */
/*var mysql = require("mysql");
 var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "password",
 database: "whiz"
 });
 connection.connect();*/
/*
 * -------------------
 * functions
 * -------------------
 */
function subscribeMessage(_subscriber) {
  subscriber.subscribe(_subscriber);
  subscriber.on("message", function (channel, message) {
    console.log("redis connection message:" + message);
  });
}
function createNewChannel(){
        //return true;
}
function showArray(){  
  console.log("My data:");
  console.log(" =============================== ");
  console.log(arrChatMembersLog);
  console.log(" =============================== ");
}
function insertDataInArray(index, loopindex, replies2){
  arrChatMembersLog[index][loopindex] = JSON.stringify(replies2);
}
function callBackSubscriberHGETMessageTable(messagesIds, index){
  console.log("messages index of i "+ index + "::" + messagesIds.length);
  console.log("message data:"+messagesIds);  
  arrChatMembersLog[index] = new Array(parseInt(messagesIds.length));  
  for (var j in messagesIds) {    
    var _index = messagesIds[j];
    var loopindex = 0;    
    subscriber.HGET(messageTable, _index, function(err, replies2) {
      //console.log("array index :"+index+":data "+j+":Ids "+_index+":Loopindex "+loopindex+" === "+replies2);
      //arrChatMembersLog[index][loopindex] = JSON.stringify(replies2);
      insertDataInArray(index, loopindex, replies2);
      console.log(arrChatMembersLog);
      loopindex++;
    });
  }
}

function callBackSubscriberHGetAll(i){  
  subscriber.HGETALL("message_channel"+i, function(err, replies1) {
    var k=1;
    for (k in replies1) {
      arr_msg_id.push(JSON.parse(replies1[k]));
    }
    callBackSubscriberHGETMessageTable(arr_msg_id, i);
    arr_msg_id.splice(0,arr_msg_id.length);
  });
}
function get_old_data(){  
    /*
     * Grep total channels created in redis database of all users.
     */
    subscriber.SCARD(msgChannel, function(err, channel_Count) {                
        var i=1, j=1;
        console.log("channel count :"+channel_Count);
        for(i =1; i<=channel_Count; i++){            
          callBackSubscriberHGetAll(i);
        }
    });

}
function setMessageData(msg){
  console.log("message call");  
  arr_sender_reciver_msg.push(JSON.stringify(msg));
}
function pushToRedis(subscriber, data) {
  console.log("push to channel"+JSON.stringify(data));
  console.log(" call first push ..."+data.uId+"==="+data.reciver);
  var msg = data.msg;
  var channel_name;
  if(data.uId && data.reciver){
      subscriber.SINTER("user_"+data.uId, "user_"+data.reciver,  function(err, replies) {
        console.log("get_old_communication_channel_name  :"+get_old_communication_channel_name+"=="+replies);    
        if(get_old_communication_channel_name != replies) {
              arr_msg_id.splice(0,arr_msg_id.length);
              arr_sender_reciver_msg.splice(0,arr_sender_reciver_msg.length); 
        }
        get_old_communication_channel_name = replies;
        //one to one communication in message new create  channels replies == 0 then
        console.log("replies SCARD  :"+replies.length);
        if(replies.length == 0){
            var channel_Count_no;
            subscriber.SCARD(msgChannel, function(err, channel_Count) {
            console.log("channel_Count  :"+channel_Count);
            if(channel_Count == 0){
              channel_name = "channel1";
              subscriber.SADD("user_"+data.uId, "channel1");    
              subscriber.SADD("user_"+data.reciver, "channel1");
              subscriber.SADD("channelSet", "channel1");  
            }else{
              channel_Count_no = channel_Count + 1;
              channel_name = "channel"+channel_Count_no;
              subscriber.SADD("user_"+data.uId, "channel"+channel_Count_no);    
              subscriber.SADD("user_"+data.reciver, "channel"+channel_Count_no);
              subscriber.SADD("channelSet", "channel"+channel_Count_no); 
             // subscriber.SADD(msgChannel, "message_channel"+channel_Count_no); 
            }
          });
        }
        console.log(" call first push1 ...");    
        //one to one communication in message new create  channels replies == 1 then

        if(replies.length == 1){ 
          get_old_communication_channel_name = replies; 
          channel_name = replies;     
          console.log("ch_name :"+replies);
          console.log("data.msg  :"+msg);
          console.log("msgChannel  :"+msgChannel);
          console.log("arr_msg_id.length  :"+arr_msg_id.length);
          if(arr_msg_id.length < 1 ){
            console.log("arr_msg_id.length After  :"+arr_msg_id.length);
            subscriber.HGETALL("message_"+channel_name, function(err, replies1) {
              /*
               * HGETALL  redis command to get all redord and for lop to javascript insert in this arr_msg_id array.
               * After for loop to get all record in messageTable.
               */
              console.log("replies1  :"  +replies1.length);
              for (i in replies1) {
                arr_msg_id.push(JSON.parse(replies1[i]));
              }
              console.log(arr_msg_id.length);
              for (i in arr_msg_id) {
                var _index = arr_msg_id[i];                      
                subscriber.HGET(messageTable, _index, function(err, replies2) {    
                   arr_sender_reciver_msg.push(JSON.parse(replies2));                     
                  //setMessageData(replies2);                  
                });
              }
              console.log("isert arr_sender_reciver_msg cumplited...");
            });
          }
          console.log(" call first push2 ...");
          /*
          * First time Add new messageChannelSet in message_channel1,2,3...
          * Not insert message_channel1,2,3... duplicate
          */
        }

        subscriber.HLEN(messageTable, function(err, replies1) {
          subscriber.SADD(msgChannel, "message_"+channel_name);
          message_Id = replies1 + 1;
          subscriber.HSET(messageTable, message_Id, JSON.stringify(data), function(err, reply) {
            if (err) throw err;
            console.log("Reply : "+ reply);    
          });
          //subscriber.HSET(messageTable, message_Id, "sender:'"+data.uId+"', reciver:'"+data.reciver+"', meg:'"+data.msg+"', time:'"+data.date+"'");  
          /*
          * message_channel1,2,3....
          * that match message_channel in insert ID and massage_text.
          */
          subscriber.HSET("message_"+channel_name, "msg_"+message_Id, message_Id);
          //arr_sender_reciver_msg.push({uId : data.uId,from : data.from,msg : data.msg, reciver : data.reciver,})
        }); 
        console.log(" call first push3 ...");
        //pushTOmessage(subscriber, data);         
      });
  }
}
function getCurrentTime() {
  return Math.floor(new Date().valueOf() / 1000);
}
function accessSecureSessionInfo() {
  //console.log("type:" + typeof (parseUrl.dataJSON));
  if ("string" === typeof (parseUrl.dataJSON)) {
    console.log("step in 1");
    var _objUser = JSON.parse(parseUrl.dataJSON);
    //  console.log("usrname;" + _objUser.username);
    uId = (_objUser.user_id === undefined || _objUser.user_id === "" || _objUser.user_id === null) ? null : _objUser.user_id;
    uName = (_objUser.username === undefined || _objUser.username === "" || _objUser.username === null) ? null : _objUser.username;
    uEmail = (_objUser.user_email === undefined || _objUser.user_email === "" || _objUser.user_email === null) ? null : _objUser.user_email;
  }
}
/* 
 * -------------------
 * Redis Subscriber
 * -------------------
 */
if (uId && uName && uEmail) {
    subscriber.subscribe("whizchannel");
    subscribeMessage("whizchannel");
}
var basket = {};
var index =0;
io.sockets.on('connection', function (socket) {
  var _subscriber = redis.createClient();
  socket.on('connection', function (cma) {
    console.log('Server running on *:' + app.get('port'));      
  });
  console.log("index:"+index++);
  socket.on("join",function(data){
    console.log("before start:"+userlists.length);
    console.log("datauid:"+data.uid);
    if(data.uid !== null && data.uid !== undefined && data.uid !== "") {     
     //console.log("after start:"+userlists.length);
     //console.log("Join called for :"+data.uid);
     //console.log("socketid:"+socket.id);
     //console.log("datuid:"+data.uid);
      var _socketid = socket.id;
      var _uid = data.uid;
      var _findIndex = uids.indexOf(_uid)
      if(_findIndex === -1){
        uids.push(_uid);
        socketids.push(_socketid);        
      }else if(_findIndex !== -1){
        socketids[_findIndex] = _socketid;
      }
      io.sockets.sockets[_uid] = _socketid;
     //userlists[_uid]=_socketid;
     //console.log("user array");
     //console.log(userlists);
     //console.log("users length:"+users.length);
     //console.log("userssocket length:"+usersSocket.length);
    }
  });

  console.log("Userslists:"+userlists);

  socket.on("chat1", function (data) {   
    console.log("frist call chat 1......");
      var _data = {
      uId : data.sender_id,
      from: data.sender_name,
      msg: data.msg,
      reciver : data.reciver,
      //date: getCurrentTime()
    };
    get_old_data();    
   // pushToRedis(_subscriber, _data); 
  });
  socket.on("chat", function (data) {
    console.log("After call chat emited......");
    var dt = new Date();
    var hours = dt.getHours();
    var mid;
    if(hours >= 12){ mid='pm';}
    else{ mid='am';}
    var time = (dt.getHours() < 10?'0':'')+dt.getHours()+ ":" + (dt.getMinutes() < 10?'0':'')+dt.getMinutes() + ":" + (dt.getSeconds() < 10?'0':'')+dt.getSeconds()+" "+mid;
    var _data = {
      uId : data.sender_id,
      from: data.sender_name,
      msg: data.msg,
      reciver : data.reciver,
      //date: time
      //date: getCurrentTime()
    };
     //basket[data.replies] = socket.id;
    // io.sockets.socket(to).emit(data.msg);
    console.log("------------------------------------\n");
    console.log(employees);
    console.log("------------------------------------\n");
    console.log("call pushToredish function");
    arr_sender_reciver_msg.push({uId : data.sender_id,from : data.sender_name,msg : data.msg, reciver : data.reciver})
    // io.sockets.socket(_data.reciver).emit(_data.msg);
    console.log("users:"+userlists.length);
    //socket.emit("publishMessage", arr_sender_reciver_msg); 
    //console.log("user.sender_id"+users[data.sender_id]);
    var _sender_id = data.sender_id;    
    var _uIndex = uids.indexOf(data.reciver.toString());
    console.log(uids);    
    console.log(socketids);
    console.log("senderid:"+_sender_id);
    console.log("receiverid:"+data.reciver);    
    console.log("index:"+_uIndex);
    console.log("receiver:"+uids.indexOf(data.reciver.toString()));

    if(_uIndex !== -1){      
      console.log("call to publish ....");
      var _socketId = socketids[_uIndex];

    }
    socket.emit("Current_publishMessage", _data);
    //socket.broadcast.emit("Current_publishMessage", _data);
  });
  //    socket.onclose = function () {
  //        console.info('Socket is now closed.');
  //    }
  socket.on('disconnect', function () {
  });
});