Pergunta

I am trying to write a simple POP3 client for gmail in node.js. I initially wrote one where I enter the POP3 commands and they get sent to the server, and the server responds. This works fine because I can wait for the server's response before entering the next command.

But I want to make an automated conversation, where the program itself sends the commands and awaits its own responses. Simply doing:

stream.write('USER ***&@gmail.com');
stream.write('PASS *****');
stream.write('LIST');

doesn't work, because of the asynchronous nature of streams in node. I have to wait for the stream's 'data' event before sending the next message, otherwise, nothing happens at all. So tried it like this:

var tls =require ('tls');

var stream = tls.connect(995,'pop.gmail.com', function() {
    console.log ('Conexion establecida');
});

stream.on('data', function(data)
{
    var str = data.toString();
    console.log(str.substr(0,14));
    if(str.substr(0,14)=="+OK Gpop ready")
    {
        console.log('Sending username...');
        process.nextTick(function() {
            stream.write ('USER ***********@gmail.com');
        });
    }

    if(str.substr(0,14)=="+OK send PASS")
    {
        console.log('Recieving list of email...');
        process.nextTick(function(){
            stream.write('PASS *********');
        });
    }
});

The idea is that the 'data' event listener handles the sending of the next command depending on the last reply recieved. Again, doing stream.write alone did not seem to work, so I wrapped the write() calls in process.nextTick() calls. It seems that the USER command is sent, but never the PASS command. Can someone tell me why? Or if there is a more effective way to do this? Thanks for any information.

Foi útil?

Solução

Your commands are being sent, however they are not being recognized, as they are missing the newline character, which denotes the end of a command. Adding a newline character to the end of your commands should get it working.

Additionally, you can simplify your commands by implementing a queue like so:

var tls = require('tls');
var commands = [];

commands.push('USER ***********@gmail.com\n');
commands.push('PASS *********\n');

var stream = tls.connect(995, 'pop.gmail.com', function () {
    console.log('Conexion establecida');
});

stream.on('data', function (data) {
    if (data.toString().indexOf('OK') > -1 && commands.length) {
        stream.write(commands.shift());
    }
});

Outras dicas

Without seeing all the code, it is a bit difficult to answer.

However I noticed that in your first example, you write

stream.write('USER *&@gmail.com');

with an ampersand "&"

However in the second example there is no ampersand - could that be the source of the issue?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top