Node.js imap connection handling - javascript

I need to write a node.js application to keep checking if there is new email from the imap server.
I am trying to write an object handling the imap connection.
var Imap = require('imap'),
inspect = require('util').inspect;
const fs = require('fs');
var MailParser = require("mailparser").MailParser;
var Promise = require("bluebird");
function ImapConnection(config){
if (!(this instanceof ImapConnection))
return new ImapConnection(config);
this._imap = new Imap(config);
this._config = config;
}
ImapConnection.prototype.getImap = function(){
self = this;
if(this._imap.state !== 'authenticated'){
return new Promise(function(resolve,reject){
self._imap.connect();
self._imap.once('ready', function(){
resolve(self._imap);
});
});
}else{
return new Promise(function(resolve,reject){resolve(this._imap);});
}
}
But when I call the object after I called the end() function of the imap object it never connects again and always gives the timeout error:
{ [Error: Timed out while connecting to server] source: 'timeout' }
[connection] Closed
events.js:141
throw er; // Unhandled 'error' event
^
Error: Timed out while connecting to server
at null._onTimeout
(/home/ctw/Documents/nodejsmail/node_modules/imap/lib/Connection.js:280:15)
at Timer.listOnTimeout (timers.js:92:15)
Can anyone tell me what's wrong on my code or any other better practice? Thanks.

Related

Failed to construct 'WebSocket': The URL '{{.}}' is invalid

gorilla/websocket example
In this example:
https://github.com/gorilla/websocket/blob/e8629af678b7fe13f35dff5e197de93b4148a909/examples/echo/server.go#L79
The WebSocket is created by:
ws = new WebSocket("{{.}}");
The example works fine.
Problem
But, then I want to use the same code in another JS code like:
var ws;
ws = new WebSocket("{{.}}");
ws.onopen = function(evt) {
console.log("OPEN SOCKET");
}
ws.onclose = function(evt) {
console.log("CLOSE SOCKET");
ws = null;
}
ws.onmessage = function(evt) {
console.log("RESPONSE SOCKET: RECEIVED");
}
ws.onerror = function(evt) {
console.log("ERROR: " + evt.data);
}
ws.send(positions);
ws.close();
I'm getting this error:
Uncaught (in promise) DOMException: Failed to construct 'WebSocket': The URL '{{.}}' is invalid.
at AddObjectCommand.execute
I changed WebSocket like this:
ws = new WebSocket("ws://127.0.0.1:8080/echo");
But I'm still getting an error:
WebSocket connection to 'ws://127.0.0.1:8080/echo' failed: Error during WebSocket handshake: Unexpected response code: 403
I cannot figure out what I'm doing wrong. What did I miss?
Fix 403
The 403 error got resolved by this suggestion:
https://github.com/gorilla/websocket/issues/367#issuecomment-375971418
By adding:
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
Before:
c, err := upgrader.Upgrade(w, r, nil)
It's not safe to trust all origins, of course. Just a temporary fix.
Yet another error
But another error is thrown:
Uncaught (in promise) DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
The error of:
Uncaught (in promise) DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
Got resolved by sending data through WebSocket, by its .onopen callback:
var positions = ...
var ws;
ws = new WebSocket("ws://127.0.0.1:8080/echo");
ws.onopen = function(evt) {
console.log("OPEN SOCKET");
console.log("SEND: START");
ws.send(positions);
ws.close();
}

Uncaught Error: connect ETIMEDOUT (net.Socket)

I am trying to send text to my network printer via tcp connection.
function print(buf2){
var printer = new net.Socket();
printer.connect(printer_port, printer_name, function() {
console.log('Connected');
printer.write(buf2);
printer.end()
});
}
Everything works fine, but after some time my application throws me the error Uncaught Error: connect ETIMEDOUT and it doesn't connect with my printer.
To fix it, I open a browser and navigate to my printers address(192.168.1.111) and then my application connects again but after some time it stops connecting and throws the same error (Uncaught Error: connect ETIMEDOUT).
The applications is written with electron and i use the net npm
var net = require('net');
In my application every 3 seconds i call a get request and then i call the print method
function proxy() {
var client = new HttpClient();
client.get('my_link', function(response) {
var jsonItem = JSON.parse(response)
if(jsonItem.items.length > 0)
{
var text_to_print = jsonItem.items[0].text
print(text_to_print,text_id);
}
Any suggestions what could cause this error?
This should help you to debug.
function print(printer_port, printer_name, buf2) {
var printer = net.createConnection(printer_port, printer_name, function () {
//'connect' listener
console.log("Connected!");
printer.end(buf2);
});
printer.setTimeout(60 * 1000); //1 minute
printer.on("end", function () {
console.log("Disconnected from server!");
});
printer.on("timeout", function () {
console.log("Timeout!");
printer.destroy();
});
}

nodejs + mqlight connection error

I am using nodejs with mqlight to run a sample code which is provided by https://www.npmjs.com/package/mqlight.
I am using nodejs 5.5.0 and npm version is 3.3.12.
I installed mqlight using npm install mqlight.
var mqlight = require('mqlight');
var recvClient = mqlight.createClient({service: 'amqp://localhost'});
var topicPattern = 'public';
recvClient.on('started', function() {
recvClient.subscribe(topicPattern);
recvClient.on('message', function(data, delivery) {
console.log('Recv: %s', data);
});
});
var sendClient = mqlight.createClient({service: 'amqp://localhost'});
var topic = 'public';
sendClient.on('started', function() {
sendClient.send(topic, 'Hello World!', function (err, data) {
console.log('Sent: %s', data);
sendClient.stop();
});
});
While I am running above code I got below error.
E:\nodejs>node mqtest.js
events.js:154
throw er; // Unhandled 'error' event
^
NetworkError: CONNECTION ERROR (localhost:5672): Connect failure: The remote co
mputer refused the network connection.
at Socket.connError (E:\nodejs\node_modules\mqlight\mqlight.js:1437:19)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at emitErrorNT (net.js:1255:8)
at nextTickCallbackWith2Args (node.js:474:9)
at process._tickCallback (node.js:388:17)
Please help to solve this problem. I am using window 7 64 bit os.
Are you sure the service amqp is running? You can follow the below script to start amqp service.
START SERVICE(SYSTEM.AMQP.SERVICE)
START CHANNEL(SYSTEM.DEF.AMQP)
REFRESH SECURITY TYPE(CONNAUTH)
DISPLAY CHSTATUS(SYSTEM.DEF.AMQP) CHLTYPE(AMQP)

How to handle invalid URL / IP's in websockets?

I'm using HTML / Javascript web sockets to communicate with a python server program. Now I have the option to change the server's IP via clean UI and I have a .onerror function that handles with connection errors, however this doesn't handle initial errors. What I mean by this is if I were to enter a completely invalid address, it wont even attempt to connect with it (which is fine) and spit out and error like: [Error] WebSocket network error: The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 2.). How can I handle this error so I can say, popup a message for example?
Here's a brief overview of my JS script.
function updateDevice(id, ipUI){
if ("WebSocket" in window){
var ws = new WebSocket(serverIP);
// Here is where I need to handle the bad address right?
ws.onopen = function(){
ws.send(id);
};
ws.onmessage = function (evt){
var received_msg = evt.data;
};
// This function ws.onerror doesnt handle bad addresses.
ws.onerror = function(){
document.getElementById("error_msg").style.display='block';
};
}else{
alert("This site doesnt support your browser...");
};
};
You could wrap the new WebSocket in a try/catch:
try {
new WebSocket(serverIP);
} catch (e) {
if (e instanceof DOMException) {
alert('Invalid address!');
} else {
throw e;
}
}

Unhandled ''error'' event in Node.JS

I'm trying to active an RFID reader through node.js and then send the tag back.
It works great. It reads the tag, responds with an ID, then send the ID to the pinging node client.
However, every time the node.JS program picks up a set of data from an RFID tag, after it sends, it closes down with the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: EBADF, read
This causes the node process to quit all the time. What could be the problem here?
My code is the following;
// Socket.io server details
var io = require('socket.io').listen(3000);
// Serialport plugin declared and made a serialport variable
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
// Variable containing technical USB port details
var serialPort = new SerialPort("/dev/ttyUSB0",
{baudrate: 2400, parser: serialport.parsers.readline("\n")},
false); // this is the openImmediately flag [default is true]
io.sockets.on('connection', function (socket) {
console.log('user connected');
socket.on('ping', function (data) {
serialPort.open(function () {
// Open notification
console.log('open');
//Start listening
serialPort.on('data', function(data) {
// If content is empty, filter out
if (data.trim() !== '') {
line = data;
//Execute function again, get tag, handle tag and end process
serialPort.close(function () {
console.log('De uiteindelijke tag is ' + data);
console.log('Ping received with data: ' + data);
socket.emit('pong', data);
console.log('closing');
});
console.log('hallo');
}
});
});
});
});
Add a listener to handle the error in the serial port, like the code below:
serialPort.on('error', function(error) {
console.log('The error: '+error);
//...
});

Categories

Resources