Strange error using socket.io with Node js - node.js

I'm trying to send some messages to a server.
That's what I do
for(var i=0; i<100; i++){
var post={
att1 : var.att[i].att1,
att2 : var.att[i].att2,
att3 : var.att[i].att3,
att4 : var.att[i].att4
}
sock.write(JSON.stringify(post));
}
But I get this strange error
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:904:11)
at Object.afterWrite (net.js:720:19)
logout
Why this happens? Is the buffer of the socket full?

It usually means that the other end closed the connection unexpectedly. In any case, you were writing to the closed socket.
Also, 100.length is not a valid JavaScript.

Related

NodeJS : Error: read ECONNRESET at TCP.onStreamRead (internal/stream_base_commons.js:111:27)

Using Polling like below to check if the content of the file is changed then, other two functions are called
var poll_max_date=AsyncPolling(function (end,err) { if(err) {
console.error(err); } var stmp_node_id=fs.readFileSync(path.join(__dirname,'node_id'),"utf8");
console.log("--------loaded node : "+stmp_node_id);
if(druid_stmp_node_id!=stmp_node_id) {
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// // DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire();
druid_stmp_node_id=stmp_node_id; }
end(); }, 1800000).run();//30 mins
Its working fine for sometime, but then getting below error like after 4 - 5hours :
events.js:167
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
tried using fs.watch to monitor the changes in the file instead of polling like below :
let md5Previous = null; let fsWait = false;
fs.watch(dataSourceLogFile, (event, filename) => { if (filename) {
if (fsWait) return;
fsWait = setTimeout(() => {
fsWait = false;
}, 1000);
const md5Current = md5(fs.readFileSync(dataSourceLogFile));
if (md5Current === md5Previous) {
return;
}
md5Previous = md5Current;
console.log(`${filename} file Changed`);
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire(); } });
Its is also working fine for sometime, but then getting same error like after 4 - 5hours :
events.js:167 throw er; // Unhandled 'error' event ^
Error: read ECONNRESET at TCP.onStreamRead
(internal/stream_base_commons.js:111:27) Emitted 'error' event at: at
emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT
(internal/streams/destroy.js:50:3)
But when run in Local Machine, its working fine. the error occurs only when run in remote Linux Machine.
somebody can help me how I can fix that problem?
Use fs.watchFile once , because fs.watch is not consistent across platforms,
https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener
Change your code according to the requirement.
It has been happening since the users are closing the browser before the data request is received, leading to Connection Reset.
Used PM2 (http://pm2.keymetrics.io/) to run the application, and it is working great now .

node.js - handling TCP socket error ECONNREFUSED

I'm using node.js with socket.io to give my web page access to character data served by a TCP socket. I'm quite new to node.js.
User ----> Web Page <--(socket.io)--> node.js <--(TCP)--> TCP Server
The code is mercifully brief:
io.on('connection', function (webSocket) {
tcpConnection = net.connect(5558, 'localhost', function() {});
tcpConnection.on('error', function(error) {
webSocket.emit('error', error);
tcpConnection.close();
});
tcpConnection.on('data', function(tcpData) {
webSocket.emit('data', { data: String.fromCharCode.apply(null, new Uint8Array(tcpData))});
});
});
It all works just fine in the normal case, but I can't guarantee that the TCP server will be there all the time. When it isn't, the TCP stack returns ECONNREFUSED to node.js - this is entirely expected and I need to handle it gracefully. Currently, I see:
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
... and the whole process ends.
I've done a lot of searching for solutions to this; most hits seem to be from programmers asking why ECONNREFUSED is received in the first place - and the advice is simply to make sure that the TCP server is available. No discussing of handling failure cases.
This post - Node.js connectListener still called on socket error - suggests adding a handler for the 'error' event as I've done in the code above. This is exactly how I would like it to work ... except it doesn't (for me), my program does not trap ECONNREFUSED.
I've tried to RTFM, and the node.js docs at http://nodejs.org/api/net.html#net_event_error_1 suggest that there is indeed an 'error' event - but give little clue how to use it.
Answers to other similar SO posts (such as Node.js Error: connect ECONNREFUSED ) advise a global uncaught exception handler, but this seems like a poor solution to me. This is not my program throwing an exception due to bad code, it's working fine - it's supposed to be handling external failures as it's designed to.
So
Am I approaching this in the right way? (happy to admit this is a newbie error)
Is it possible to do what I want to do, and if so, how?
Oh, and:
$ node -v
v0.10.31
I ran the following code:
var net = require('net');
var client = net.connect(5558, 'localhost', function() {
console.log("bla");
});
client.on('error', function(ex) {
console.log("handled error");
console.log(ex);
});
As I do not have 5558 open, the output was:
$ node test.js
handled error
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
This proves that the error gets handled just fine... suggesting that the error is happening else-where.
As discussed in another answer, the problem is actually this line:
webSocket.emit('error', error);
The 'error' event is special and needs to be handled somewhere (if it isn't, the process ends).
Simply renaming the event to 'problem' or 'warning' results in the whole error object being transmitted back through the socket.io socket up to the web page:
webSocket.emit('warning', error);
The only way I found to fix this is wrapping the net stuff in a domain:
const domain = require('domain');
const net = require('net');
const d = domain.create();
d.on('error', (domainErr) => {
console.log(domainErr.message);
});
d.run(() => {
const client = net.createConnection(options, () => {
client.on('error', (err) => {
throw err;
});
client.write(...);
client.on('data', (data) => {
...
});
});
});
The domain error captures error conditions which arise before the net client has been created, such as an invalid host.
See also: https://nodejs.org/api/domain.html

ForEachLine() in node.js

Referring to slide no 35 in ppt on slideshare
When I run this code
var server = my_http.createServer();
server.on("request", function(request,response){
var chunks = [];
output = fs.createWriteStream("./output");
request.on("data",function(chunk){
chunks = forEachLine(chunks.concat(chunk),function(line){
output.write(parseInt(line,10)*2);
output.write("\n");
})
});
request.on("end",function(){
response.writeHeader(200,{"Content-Type":"plain/text"})
response.end("OK\n");
output.end()
server.close()
})
});
server.listen("8080");
I get error as
chunks = forEachLine(chunks.concat(chunk),function(line){
^
ReferenceError: forEachLine is not defined
Of course I unserstand that I need to include some library but when I googled this I found nothing . Since I am complete newbie to this I have absolutely no idea how to resolve it.
Any suggestions will be appreciable.
EDIT
Using the suggested answer I am getting error as
events.js:72
throw er; // Unhandled 'error' event
^
TypeError: Invalid non-string/buffer chunk
at validChunk (_stream_writable.js:150:14)
at WriteStream.Writable.write (_stream_writable.js:179:12)
at /var/www/html/experimentation/nodejs/first.js:18:20
at Array.forEach (native)
at forEachLine (/var/www/html/experimentation/nodejs/first.js:8:60)
at IncomingMessage.<anonymous> (/var/www/html/experimentation/nodejs/first.js:17:18)
at IncomingMessage.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (_stream_readable.js:736:14)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
Thanks
See proxy_stream.js
function forEachLine(chunks, callback) {
var buffer = chunks.join("")
buffer.substr(0, buffer.lastIndexOf("\n")).split("\n").forEach(callback)
return buffer.substr(buffer.lastIndexOf("\n") + 1).split("\n")
}
The link to the repo was on the first slide.
EDIT BY LET's CODE FOR ERROR MESSAGE
Came to know the actual issue now .
I was using nod v0.10 and it is buggy in getting the streams so I was getting the error. Downgraded to v0.8 and same code is working perfect .

http.request() method not working with urls having subdomains

I am trying to post some data like this
var options={hostname:'www.sub.domain.com',path:'post.php?'+qs.stringify(postData), method:'GET '};
and then calling this object with http.request(). It throws this error
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: Parse Error
at Socket.socketOnData (http.js:1485:20)
at TCP.onread (net.js:404:27)
What may be the issue?
Use host instead hostname in "option" object. Try as follows,
var options = {
host : 'www.sub.domain.com',
path:'/post.php?'+qs.stringify(postData),
method : 'GET'
};

running Hook.io on a different port

I tried to run hook.io with a different port, which killed the autodiscover features of the clients. But when I try to create the clients with the same port, they get an error.
Sever:
var oHook = hookio.createHook( {
'name' :'dispatch-hook',
'hook-port': 9999,
'hook-host': 'localhost'
} );
oHook.start();
Client:
var oHook = hookio.createHook( {
name :'client-hook',
"hook-port":9999,
"hook-host":'localhost'
});
oHook.connect();
Error:
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:781:11)
at Server._listen2._connectionKey (net.js:922:26)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
Why does the client want to start a server?
You shouldn't provide a port for the hook trying to connect to the server hook. The existence of hook-port in options makes that hook a server

Resources