mongodb insert into collection with nodejs - node.js

I'm trying to insert into collection but I get error not sure why. here is what I tried to do
db.collection("book", function(err, collection){
if(err){
console.log(err);
}
collection.insert({"name":req.query.file.split(".")[0],"length":response}, function(err,book) {
if(err){
console.log(err);
}
return callback(null);
console.log(book);
});
return callback(null);
});
I'm trying to insert a "book" into book collection... as I saw in mongo document .collection and .insert requires callback.
and my error is
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:900:11)
at Server._listen2 (net.js:1038:14)
at listen (net.js:1060:10)
at net.js:1134:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
and I'm not sure what I'm doing wrong, thanks!

Are you sure that it is because of insert? It is typical unhandled exception in case you try to start node.js process that listens for the same port as other process( or the same copy of this node.js process)

Related

Retry connection postgres Nodejs

I am using a postgres database for my express web server.
I am using the 'pg' library to execute queries on this database.
Here is my connection method :
const db = new Client({
user: 'xxx',
host: 'xxx',
database: 'xxx',
password: 'xxx',
port: xxx,
})
db.connect(err => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
}
Then to execute a request I do this:
db.query(MY_REQUEST, function (err, data) {
if (err) throw err;
res.render('hello/world', {
title: 'Hello',
data: data.rows
});
});`
It all works perfectly. But after several minutes without using my website, my connection to the db times out, and I get the following error:
node:events:355
throw er; // Unhandled 'error' event
^
Error: Connection terminated unexpectedly
at Connection.<anonymous> (/usr/src/app/node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:484:28)
at Connection.emit (node:events:378:20)
at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:58:12)
at Socket.emit (node:events:378:20)
at TCP.<anonymous> (node:net:665:12)
Emitted 'error' event on Client instance at:
at Client._handleErrorEvent (/usr/src/app/node_modules/pg/lib/client.js:319:10)
at Connection.<anonymous> (/usr/src/app/node_modules/pg/lib/client.js:149:16)
at Object.onceWrapper (node:events:484:28)
[... lines matching original stack trace ...]
at TCP.<anonymous> (node:net:665:12)
How could I do to reconnect automatically when the connection is cut or when a request fails?
You should attach an error-handler in order to prevent the unhandled error crashing your app. It's as simple as:
db.on('error', e => {
console.error('DB error', e);
});
As to why the error happens we need more details, looks like it could be a connection reset due to idle-timeout?
You can create a function to control if you're connected to database or not, before you continue with your main function.
Create a function for controlling database connection status, reconnecting etc. and before you run a database related function, first start that middle function and wait for result, after that you can continue using database again.
If you want(which should be prefered way mostly), create that middle function as an async function and return a promise, when using that function wait for that function.

How can I gracefully handle a failed tcpSocket.connect attempt?

The following code causes an error when there is no existing TCP server to communicate with on the specified host:
const net = require('net');
const argv = require('minimist')(process.argv.slice(2));
try {
var tcpSocket = new net.Socket();
tcpSocket.connect(argv.tcpport, argv.tcphost, function onConnected() {
console.log('connected');
tcpSocket.on('data', function onIncoming(data) {
console.log(data);
});
tcpSocket.on('close', function onClose(data) {
tcpSocketConnected = false;
});
tcpSocketConnected = true;
});
} catch (err) {
console.log("PRINT ME: ", err);
}
Error:
events.js:183
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:1906
at Object._errnoException (util.js:992:11)
at _exceptionWithHostPort (util.js:1014:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
I am unable to catch the error even though I wrap the code in a try...catch.
Why does my catch block not catch the error?
How can I gracefully handle the error?
You should be able to explicitly handle the error event using event emitter api (same way as you handled close and data):
tcpSocket.on('error', handleError)
From Docs:
Event: 'error'#
Added in: v0.1.90
<Error>
Emitted when an error occurs. Unlike net.Socket, the 'close' event
will not be emitted directly following this event unless server.close()
is manually called. See the example in discussion of server.listen().

node-watch ECONNRESET on network drive

I have a small app that uses node-watch to watch 2 network drives and moves files between them when a change occurs. But the network often goes down, how do I prevent ECONNRESET crashes?
The code:
watch(directories.SQL_XML_IN, {
recursive: false,
filter: function (name) {
return /\.xml$/i.test(name);
}
}, function (evt, name) {
if (evt == 'update') {
// move files
}
});
And the error:
events.js:141
throw er; // Unhandled 'error' event
^
Error: watch null ECONNRESET
at exports._errnoException (util.js:870:11)
at FSEvent.FSWatcher._handle.onchange (fs.js:1217:21)
Try something like this:
var watcher = watch('...');
watcher.on('error', function(err) {
// handle errors
// close it if necessary
watcher.close()
});

Mongoose ValidationError thrown instead of passed to callback,

Mongoose has started throwing errors for me instead of passing them to my callback?
var newsArticle = new NewsArticle(fields);
newsArticle.save(function(err, newsArticle) {
if(err) return next(err);
res.status(201).json(newsArticle);
});
the callback is never called, and the ValidationError is thrown, crashing the app. Why is this?
events.js:85
throw er; // Unhandled 'error' event
^
No listeners detected, throwing. Consider adding an error listener to your connection.
ValidationError: NewsArticle validation failed

Reconnect to TCP/IP socket on NodeJS

I use "net" library to create TCP connection on my nodeJs.
root.socket = net.createConnection(root.config.port, root.config.server);
I'm trying to handle error when remote server is down and reconnect in Cycle.
root.socket.on('error', function(error) {
console.log('socket error ' + error);
root.reconnectId = setInterval(function () {
root.socket.destroy();
try {
console.log('trying to reconnect');
root.socket = net.createConnection(root.config.port, root.config.server);
} catch (err) {
console.log('ERROR trying to reconnect', err);
}
}, 200);
}
The trouble is that in case of remote server shutdown I still get en error and my nodeJS server stops.
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)
You will need something like this:
var net = require('net');
var c = createConnection(/* port, server */);
function createConnection(port, server) {
c = net.createConnection(port, server);
console.log('new connection');
c.on('error', function (error) {
console.log('error, trying again');
c = createConnection(port, server);
});
return c;
}
In your case you are creating a new connection but you don't attach any error listener, the error is raised somewhere else in the execution loop and can not be caught by the "try / catch" statement.
P.S. try to avoid using "try / catch" statement, error handling in Node.JS is made using error listeners and domains, it can be useful only for JSON.parse() or other functions that are executed synchronously.

Resources