Saturday 3 June 2017

Cannot enqueue Query after invoking quit

According to the Node MySQL documentation (https://github.com/mysqljs/mysql#introduction):

Every method you invoke on a connection is queued and executed in sequence.

and

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

Nevertheless, the code below doesn't work, because the connection.end() method is called before the SQL queries can run. If I comment out the connection.end() line, it works, but the script hangs (doesn't close/end) when it completes, requiring me to hit ctrl-c to end it.

If I move the MySQL connection object and the connection.end() call into the lineReader.createInterface block, it works - the script correctly terminates at the end...but it's creating a new connection for every INSERT statement.

It doesn't seem right to close and reconnect each time like that. Am I misunderstanding the Node MySQL documentation? Is there a better way?

let lineReader  = require('readline');
let file        = require('fs');
let mysql       = require('mysql');

let connection  = mysql.createConnection({
    host: '127.0.0.1',
    port: 33060,
    user: 'homestead',
    password: 'secret',
    database: 'sentinel',
});

lineReader.createInterface({
        input: file.createReadStream('proxies/proxies.txt')
    }).on('line', function (line) {
        let ary = line.split(/[:, ]/);
        let insert_sql;

        if (typeof ary[2] !== 'undefined' && typeof  ary[3] !== 'undefined') {
            insert_sql =
                'INSERT INTO proxies (host, port, username, password) ' +
                'VALUES ("' + ary[0] + '", "' + ary[1] + '", "' + ary[2] + '", "' + ary[3] + '")';
        } else {
            insert_sql =
                'INSERT INTO proxies (host, port) ' +
                'VALUES ("' + ary[0] + '", "' + ary[1] + '")';
        }

        connection.query(insert_sql, function (error, results, fields) {
            if (error) {
                console.log('error: ' + error);
            } else {
                console.log('success: ' + insert_sql);
            }
        });

    });

connection.end();



via CJG

No comments:

Post a Comment