socket hanging and node crashing - node.js

I have a node app that posts data to remote apis and fetches the responses. It works fine but at times the node server crashes and generates the following errror:
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1264:15)
at Socket.socketCloseListener (http.js:1315:23)
at Socket.EventEmitter.emit (events.js:126:20)
at Socket._destroy.destroyed (net.js:358:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
I googled and found that it happens due to some timeout thing but i am not really sure as to how to overcome this.
Here is the required code in my server.js:
if(request.body.company=="CQ")
{
var postData={firstName:request.body.firstname,lastName:request.body.lastname,Email:request.body.email,DayPhoneNumber:request.body.daytimePhone,Address1:request.body.addressOne,city:request.body.city,state:request.body.State,postalCode:request.body.zip,AreaOfIntrest:request.body.areaOfInterest,VendorLocationId:"38404",Notes:request.body.Notes,GraduationYear:request.body.graduationYear,AffiliateLocationId:"12345",LocationId:"12345",CampaignId:"12345"};
var options={hostname:'webservices.someapi.com', path:'/ILM/Default.ashx?'+qs.stringify(postData), method:'GET'};
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
edModel.find({$and:[{daytimePhone:request.body.daytimePhone},{company:"CQ"}]},function(err,count){
if(count.length==0)
{
var sr='RESPONSE: ' + chunk;
if(sr.indexOf('status="Error"')==-1)
{
request.body.leadid=sr;
var sr=sr.slice(sr.indexOf("leadid"));
sr=sr.slice(0,sr.indexOf(">"));
edDoc=new edModel(request.body);
edDoc.save();
response.send({response:sr});
}
else
{
response.send({response:sr});
}
}
else
{
response.send({response:"<span style='color:red'>Duplicate Lead.<br> A lead with this number already exists in our database</span>"});
}
});
});
});
// write data to request body
req.write('data\n');
req.end();
}
I have several such if else conditions in the server.js file.

in node 0.8.20 there was a bug about that problem. try using http.get instead of http.request. or just dont use 0.8.20 if you use that version.

Related

Unable to gracefully close http2 client stream in nodejs

I have the following code which has been heavily inspired from nodejs official documentation of a client-side example
import http2 from 'http2';
// The `http2.connect` method creates a new session with example.com
const session = http2.connect('https://somedomain.com');
// Handle errors
session.on('error', (err) => console.error(err))
const req = session.request({
':authority': 'somedomain.com',
':path': '/some-path',
':method': 'GET',
':scheme': 'https',
'accept': 'text/html',
});
// To fetch the response body, we set the encoding
// we want and initialize an empty data string
req.setEncoding('utf8')
let data = ''
// append response data to the data string every time
// we receive new data chunks in the response
req.on('data', (chunk) => { data += chunk })
// Once the response is finished, log the entire data
// that we received
req.on('end', () => {
console.log(`\n${data}`)
session.close();
});
req.on('error', (error) => {
console.log(error);
});
req.end();
Please note that the actual hostname has been replaced with somedomain.com. Running this, results in data getting logged, as expected, however, the process doesn't shut down gracefully. I get the following unhandled error in the terminal.
node:events:504
throw er; // Unhandled 'error' event
^
Error [ERR_HTTP2_STREAM_ERROR]: Stream closed with error code NGHTTP2_FLOW_CONTROL_ERROR
at new NodeError (node:internal/errors:371:5)
at ClientHttp2Stream._destroy (node:internal/http2/core:2330:13)
at _destroy (node:internal/streams/destroy:102:25)
at ClientHttp2Stream.destroy (node:internal/streams/destroy:64:5)
at Http2Stream.onStreamClose (node:internal/http2/core:544:12)
Emitted 'error' event on ClientHttp2Stream instance at:
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ERR_HTTP2_STREAM_ERROR'
}
I understand it is possible that the server is behaving incorrectly. However, there should be a way on the nodejs client to close the session gracefully. Regardless, what would be the ideal way to handle such errors? I've already tried listening to session.on('error') and req.on('error') but that doesn't work.

Node.js - The "listener" argument must be of type Function

I am trying to create a proxy update code with node.js, and im getting this error:
events.js:180
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'Function');
^
TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type Function
at _addListener (events.js:180:11)
at WriteStream.addListener (events.js:240:10)
at WriteStream.close (fs.js:2298:10)
at WriteStream.<anonymous> (/Users/camden/Desktop/proxyupdate/u.js:9:15)
at WriteStream.emit (events.js:164:20)
at finishMaybe (_stream_writable.js:616:14)
at afterWrite (_stream_writable.js:467:3)
at onwrite (_stream_writable.js:457:7)
at fs.write (fs.js:2242:5)
at FSReqWrap.wrapper [as oncomplete] (fs.js:703:5)
here is my code:
var UpdateProxyList = function(sourceURL, destinationPath) {
var HTTP = require("http");
var FS = require("fs");
var File = FS.createWriteStream(destinationPath);
HTTP.get(sourceURL, function(response) {
response.pipe(File);
File.on('finish', function() {
File.close();
});
File.on('error', function(error) {
FS.unlink(destinationPath);
})
});
}
UpdateProxyList("http://www.example.com/proxy.txt", "myproxylist.txt");
Im on MacOS Sierra with node.js v9.3.0.
apparently, when I use node.js v8.9.3, it works fine
Between v8.9.3 and v9.3.0, the implementation of WriteStream.prototype.close has changed.
In v8.9.3, it was a reference to ReadStream.prototype.close, for which a callback argument was optional.
In v9.3.0, it is now a separate method that, amongst other things, emits a close event:
WriteStream.prototype.close = function(cb) {
if (this._writableState.ending) {
this.on('close', cb);
return;
}
...
};
The error that you get is caused by this.on('close', cb), which requires a Function second argument that isn't being passed in your code.
I'm not sure if you actually need to use a finish handler at all in your situation, as writable handling will be done internally by the .pipe() code.

NodeJS -> Error: write after end (only after first request)

In my express app i have the route below:
router.get('/generatedData', function (req, res) {
res.setHeader('Connection' , 'Transfer-Encoding');
res.setHeader('Content-Type' , 'text/html; charset=utf-8');
res.setHeader('Transfer-Encoding' , 'chunked');
var Client = someModule.client;
var client = Client();
client.on('start', function() {
console.log('start');
});
client.on('data', function(str) {
console.log('data');
res.write(str);
});
client.on('end', function(msg) {
client.stop();
res.end();
});
client.on('err', function(err) {
client.stop();
res.end(err);
});
client.on('end', function() {
console.log('end');
});
client.start();
});
On first call everything works fine (console)
We've got ourselves a convoy on port 3000
start
data
data
data
data
data
...
data
end
GET /generatedData 200 208.426 ms - -
I get all the data and res.end() is being called and successfully closes the request.
The problem starts after first request. I make the exact same request (new one of course) and i get the following error (console):
start
data
data
data
events.js:160
throw er; // Unhandled 'error' event
^
Error: write after end
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:439:15)
at Client.<anonymous> (/Users/xxxx/projects/xxxx/routes/index.js:33:17)
at emitOne (events.js:96:13)
at Client.emit (events.js:188:7)
at FSWatcher.<anonymous> (/Users/xxxx/projects/xxxx/lib/someModule.js:116:32)
at emitTwo (events.js:106:13)
at FSWatcher.emit (events.js:191:7)
at FSEvent.FSWatcher._handle.onchange (fs.js:1412:12)
[nodemon] app crashed - waiting for file changes before starting...
This happens without res.end() being called.
I manage to get some data before the crash.
How can i get this error without res.end() being called at all?
Do i somehow save the previous res instance?
Thanks,
Asaf
Have the same problem. My module was extened by EventEmitter and each time i catch event in router - it stays there, end on second call there are two eventlisteners not one. Setting "once" instead of "on" - worked for me.
client.once('start', function() {
console.log('start');
});
instead of
client.on('start', function() {
console.log('start');
});

ECONNREFUSED in Node http module

When a remote site is off-line I am getting this error in my consuming client (Node.js v0.12.0 with the http module):
Uncaught exception: connect ECONNREFUSED
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
The code I'm currently using looks like this:
var req = http.request(options, function (res) {
res.on('socket', function (socket) {
socket.setKeepAlive(true, 0);
socket.setNoDelay(true);
});
res.on('end', function () {
log.debug('Success');
}).on('error', function () {
log.error('Response parsing failed');
});
}).on('error', function () {
log.error('HTTP request failed');
});
req.write(packet);
req.end();
The "error" event is never fired when the ECONNREFUSED occurs, I've tried using the "clientError" event but this is not fired either.
How can I capture this error?
Extracted from: https://stackoverflow.com/a/4328705/4478897
NOTE: This post is a bit old
The next example is with the http.createClient but i think it could be the same
Unfortunately, at the moment there's no way to catch these exceptions directly, since all the stuff happens asynchronously in the background.
All you can do is to catch the uncaughtException's on your own:
process.on('uncaughtException', function (err) {
console.log(err);
});
Maybe that helps you!
More this: https://stackoverflow.com/a/19793797/4478897
UPDATE:
did you tried to change log.error() to console.error() ???

Getting ETIMEDOUT error when I try to do a simple Get request?

Hi I am trying to call a simple web API which returns a string as response. I want to use node for this. Since I am new to node so I tried reffering to many blog post and got a code snippet which I used but I am getting same error for all urls whether its google.com or anything else.
My Node code is as follows
var http = require('http');
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
Error:
F:\nodejs>node ..\NodeLearning\TestServer1\test.js
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
Can Any one tell me what has gone wrong here?
Can you try one more time by setting a proxy like mentioned below
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new',
proxy:'add your proxy setting'
};

Resources