I'm trying to have the user be able to click a button, which sends a request to my node server and then with the data sent, it fires a function thats in another file. My problem isn't with the code, I'm just new to javascript so I'm not quite sure how i should be returning this object back to the client, i'm quite lost i'll explain more in the code below. I'm not sure if I should be doing something as simple as
return obj;
or If i should be using async/await, i've tried doing this but couldn't quite understand it.
http.createServer(function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With")
//res.writeHead(200, { 'Content-Type': 'text/plain' });
var data = []
if (req.method == "POST") {
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (dat) {
data.push(dat)
})
req.on('end', function () {
var gamedata = Buffer.concat(data).toString();
var game = JSON.parse(gamedata)
games.getPing(game.placeId, 0)<--This is the function that gets fired in the other file
res.end(/*some how get games.gameservers here to send back to client*/)
})
}
}).listen(9999)
This is my node server that is in a file called server.js.
Now here is the function that gets fired. This function is in a file called api.js
games = {
gameservers: [],
getPing: function (id,index,callback) {
var keepAliveAgent = new https.Agent({ keepAlive: true })
var r = https.request(options, function (res) {
var data = []
res.on('data', function (d) {
data.push(d)
}).on('end', function () {
var buf = Buffer.concat(data)
var encodingheader = res.headers['content-encoding']
if (encodingheader == 'gzip') {
zlib.gunzip(buf, function (err, buffer) {
var o = JSON.parse(buffer.toString())
// o is what is returned
if (index < o.TotalCollectionSize) {
index = index + 10;
//console.log(index, o.TotalCollectionSize)
try {
let lowest = o.c.reduce((lowest, item) => item.x < lowest.x ? item : lowest)
if (lowest.q != lowest.p) {
// console.log(lowest)
games.gameservers.push(lowest)
}
games.getPing(id, index)
} catch (e) {
if (e) {
console.log(games.gameservers)
/*
This is where my function ends, I need to be able to send the games.gameservers array, back to the client in cloud.js
*/
}
}
}
})
}
})
})
r.end()
}
}
Inside the error of the try/catch, is where the function ends. Basically, the res.end() in server.js needs to have the games.gameservers object in it to go back to the client.
I'm pretty new to javascript as a whole, so i'm not sure if I should be using return, async/await, callbacks. I've been at this for awhile and cant seem to get it.