0

My plan is to write a Query "class" in NodeJS which connects to a server and sends some data.

The following error occurs: Error

My Query.js

var net = require('net');

function Query(ip,port,user,pass,sid){
        this.ip = ip;
        this.port = port;
        this.user = user;
        this.pass = pass;
        this.sid = sid;
        this.dataString = "";

        this.socket = net.connect(port,ip,function(){
            this.socket.write("login "+user+" "+pass+"\r\n");
            this.socket.write("use "+sid+"\r\n");
        });

        this.socket.on("data", function (data) {
            this.dataString += data.toString();  
        });
}

Query.prototype.test = function(){
    this.socket.write("logview\r\n");
}

module.exports = Query;

This is the part where I create an object (index.js):

var srvleinQ = new Query(config.Serverlein.adress,config.Serverlein.port,config.Serverlein.user,config.Serverlein.pass,config.Serverlein.sid);
srvleinQ.test();
htmlData = srvleinQ.dataString;

IP,Port and login data are correct!

Joba
  • 828
  • 9
  • 28
  • Welcome to the wonderful world of **async**! You should use promises. – SLaks Sep 25 '17 at 18:02
  • Isn't the callback function the correct way, to wait until the connect finished? – Joba Sep 25 '17 at 18:06
  • 1
    Yes, but you then try to access it outside the callback before it finished. That cannot work. You can't escape from callbacks. – SLaks Sep 25 '17 at 18:19
  • Oh well, what you say seems obvious. Thanks, now it works. But: Why did it work in in the callback, when it wasn't in the extra module? First I tested the connection without the module, only in index.js. – Joba Sep 25 '17 at 19:02
  • 1
    Because the callback only runs once the response arrives. – SLaks Sep 25 '17 at 19:12

0 Answers0