My question is: How does the "http.get()", on.("end",callback) event work?
What is the hierarchy of the code execution?
I'm asking because I have this code
var http = require("http")
var str = ""
http.get(process.argv[2],function(res){
res.setEncoding("utf8")
res.on("data",function(data){
str+= data
})
res.on("end",function(){
console.log(str.length)
console.log(str)
})
})
is the on.end part would print me the str.length every time its called?
To start with,
function(res) is called when the connection is established.
on('data') is called when there's a chunk of data (this almost certainly will be more than once)
on('end') is called when the connection closes.
on('error') is called when there is some sort of error.
This code means that till the data is incoming (in chunks), the response will be appended every time it is received from data to str and when the receiving has ended it will console str.length and str.
You can read this for better understanding: colmsjo.com/130721_Streams_in_NodeJS
Related
I'm struggling to find out why TcpClient don't receive any data in server side if it has called through ajax.
However, if I put breakpoint in my server side code it works fine even if I have called it with ajax.
I also investigated to find out if my JavaScript function is asynchronous but it seems my JavaScript function is fine.
JavaScript function:
$('#btnGO').click(function () {
var url = 'Home/Command';
var data = { Location: $('#Location').val() };
$.when($.getJSON(url, data)).then(function (result) {
$('.Console').html(result);
});
});
Server side:
TcpClient tc = new TcpClient("Host Address", 23);
return Json(tc.Connected + " " + tc.Available, JsonRequestBehavior.AllowGet);
Output if I put breakpoint in serverside:
true 22
Output if I don't put breakpoint in serverside:
true 0
I think you'd want to call GetStream(), and then call Read() on the returned NetworkStream. Read() is blocking, and won't allow your action method to return prematurely. Right now, there are no blocking calls to prevent your action method from instantly returning (faster than your tcp client receives data), which is why you get 22 when you put in a break point - it doesn't instantly return. It seems awkward that your UI responsiveness depends on somebody sending data to your API via a socket though....
let me emphasize this more: It's really strange what you're doing. Your UI will be waiting for a client to send data to your API via a socket. Having said that, check out the following link: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream(v=vs.110).aspx
Maybe this is simple, maybe this is a bug on Parse - would like to know if anyone has had the same problem and a possible solution.
What I'm trying to do:
I'm sending a JSON request from an app called FormEntry to my Parse app
The body comes in like this: json={"someLabel" : "someValue"}
I would like to take the entire body and create a Parse.Cloud.httpRequest over to Zapier to perform some functions.
Now, the problem seems to be this:
On random occasions (i.e. I have no idea why), the body is sent (as shown by the logs) where there is a trailing comma at the end of the last pair in the JSON object. e.g. like this json={"lastLabel" : "lastValue",}
The number of elements in 'normal' and 'incorrect' objects seem to be the same, so it's simply just another comma added. And I have no idea why.
My setup:
Using app.use(parseExpressRawBody()); only and not the standard app.use(express.bodyParser()); which doesn't provide access to the raw body.
Because parseExpressRawBody converts the body to a buffer I need to turn it back into a string to send it in the HTTP request in a meaningful way. Therefore I use: var body = req.body.toString();
When logging this var to the Parse console it looks to be format back from the buffer fine.
And that's about it. Nothing complex going on here but a real annoying bug that I just haven't found a sensible way of understanding. Would SUPER appreciate anyone who has seen this before or who could point me in a direction to focus on.
Just an update on this. Not a solution that answers why there is malformed JSON but a hack to get the right result.
The purpose of the HTTP request was to point over to Zapier so I wrote a Zapier script that would deal with the malformed JSON. Added here for anyone else who needs it.
"use strict";
var Zap = { newSubmission_catch_hook: function(bundle) {
var body = bundle.request.content;
var cleanTop = body.substring(5,body.length);
var cleanChar = cleanTop.length;
var condition = cleanTop.substring(cleanChar-2,cleanChar);
function testCase(condition,cleanTop) {
if (condition != ",}"){
console.log("Everything is fine, returning JSON");
return cleanTop;
}
else {
console.log("Nope! We have an error, cleaning end");
var cleanEnd = cleanTop.substr(0,cleanChar-2) + '}';
console.log("The object now ends with: " + cleanEnd.substr(-10));
return cleanEnd;
}
}
var newBody = JSON.parse(testCase(condition,cleanTop));
return newBody;
}
};
My situation is like this, I have a server like this and inside I am calling another callback function which gets multiple values:
var http = require('http');
var server = http.createServer(req,resp) {
var finalVal = "";
consumer.on('message',function(message) {
finalVal = message;
console.log(finalVal);
});
resp.end(finalVal);
});
My finalVal should display all the multiple values it fetches and send it as a response, but problem is it's sending only first value where as console.log displays all the values. I do understand that by the time consumer.on ends response would have committed. Can someone please help me how to handle this scenario since I'm very new to Node.js ? Currently due to heavy deadlines I don't have time to read full information about callbacks. But defnitely I would take time to learn about callbacks.
Edit: Here consumer.on calls multiple times till it fetches all the data from backend, I need to send all those data in a final response. I am using node-kafka to consume to kafka messages.
There must be an end event or something like that which tells that consumer has finished the message, you can use that
I am not sure what is consumer here, but in most of cases we go with something like bellow
var finalVal = '';
consumer.on('message',function(message) {
finalVal += message; // So on each message you will just update the final value
console.log(finalVal);
});
consumer.on('end',function(){ // And at the end send the response
resp.end(finalVal);
});
I am using jquery $.post method to send a string to a servlet.
var temp = "hsad d jad a....sad";
var str="testServlet?param="+temp;
$.post(str, function(data) {
alert("saved");
});
testServlet receives a call when the temp has less characters, say 5000. But when it has more no. of characters i.e. > 5000 it is not called. Firebug says 'Aborted'.
I could not understand why.
I thought that this might be because the above code is sending temp in the get form so I wrote like this -
var temp = "hsad d jad a....sad";
var str="testServlet";
$.post(str, {param:temp}, function(data) {
alert("saved");
});
But in this case the servlet was called but param was null.
1. Is there any difference between the above two methods ?
2. If first method is get then why jquery has $.get ?
There are limitations on maximum URL length, depends on web browser, webserver e.t.c.
When your pass some parameters in url will have problem with too long parameters even if your use POST request.
In your code only {param:temp} will be stored in request body. str is url so it's has max length restriction.
How to read event.data completely from a WebSocket using JavaScript?
onMessage: function(event) {
var msg = event.data;
alert(msg);
}
In the above code, the variable msg shows only the partial data. How to receive the complete data from the WebSocket server?
event.data contains the full information; it just depends on your output how much you'll see. An alert box can only contain up to a specific amount of characters, because more characters simply wouldn't fit in the alert box. alerting is not a good practice for displaying large data.
A more convenient way is to save the length and check that, e.g.:
onMessage: function(event) {
var msg = event.data;
alert(msg.length);
}
The length should just be the correct length, i.e. the length of the characters you sent.
WebSockets is a message based transport. If the server has broken the "stream" into several message chunks then you will receive several message events and the first message event won't have all the data that you are expecting.
Also, the WebSocket definition requires that the onmessage handler is called for full messages. You can't get partial messages (unless the browser's WebSocket implementation is broken).
I would try something asynchronous instead of alert() to log the messages you receive. For example, try console.log() if you have Firebug or the Chrome Javascript console. Are you accumulating your message data in the HTML text box or just overwriting it as you receive messages?