1

I am writing my first NodeJs script. Below is some code I have set up to test a database connection.

When I include process.exit() at the very end of the script, nothing is logged to the console - however, when I simply remove that line of code, the function logs the query results appropriately (output included also).

I am wondering why the process.exit() at the very end of the code prevents the function from functioning and if I am using the exit method wrong.

Code:

/*
 * Runs every minute on an uptime agent
 * Checks list of sites to see if they're up
 */

// strict mode (see http://stackoverflow.com/questions/8651415/what-is-strict-mode-and-how-is-it-used for information)
'use strict';

// cuz im lazy
String.prototype.lc = function() { return this.toLowerCase(); }
String.prototype.uc = function() { return this.toUpperCase(); }


/** EXCEPTIONS  **/
var DbConnectError = function(m) {
    this.name = 'DbConnectError';
    this.message = m;
}
var DbConfigError = function(m) {
    this.name = 'DbConfigError';
    this.message = m;
}

/**     DATABSE     **/
/*
 * change log
 * 08/07/2015   Tyler J Barnes
 *  -- init dev
 */
var db = function() {
    // error messages
    this._errors = [];

    // connection state
    this._isConnected = false;

    // db configuration
    this._config = {
        host: '',
        user: '',
        password: '',
        database: ''
    };

    // reference
    this._db = null;

    // connection obj ref
    this._con = null;

    // sql statement
    this._sqlStmt = '';

    // is prepared statement -- needs data binded
    this._isPrepared = false;

    // data to bind to prepared stmts
    this._sqlData = null;

    // query result set
    this._result = null;

    /*
     * initialize
     * @param (object) : cofig prop and values
     * @return void
     */
    this.ini = function(config) {
        // make sure config was passed
        if(!config || (typeof config).lc() != 'object') {
            throw new DbConnectError('Invalid DB Configuration');
        }
        // check for appropriate properties
        // if exist, store value
        for(var p in this._config) {
            if(!(p in config)) {
                this._errors.push('Missing database config: '+p+'\n');
            } else {
                this._config[p] = config[p];
            }
        }
        // throw any errors before continue
        if(this._errors.length > 0) {
            var tmp = '';
            for(var i = 0; i < this._errors.length; i++) {
                tmp+=this._errors[i];
            }
            throw new DbConfigError(tmp);
        }

        this._db = require('mysql');
    };

    // create connection -- returns thread id
    this.con = function() {
        this._con = this._db.createConnection(this._config);
        this._con.connect();
        this._isConnected = true;
    };

    // sets sql statement
    this.setSqlStmt = function(str, prepared, bindData) {
        this._sqlStmt = str;
        if(prepared) {
            this._isPrepared = true;
            this._sqlData = bindData;
        } else {
            this._isPrepared = false;
            this._sqlData = null;
        }
    };

    // kills connection
    this.die = function() {
        if(this._isConnected) {
            this._con.end();
        }
    };
}

var c = {
    host: 'asdfasdf',
    user: 'asdfasdf',
    password: 'asdfasdf',
    database: 'asdfasdf'
};
var d = new db();
d.ini(c);
d.con();
d._con.query('SELECT * FROM Agents', function(err,rows,fields) {
    if(err) console.log(err);
    console.log(rows);
});
d._con.end();

// this is what upsets me
process.exit();

Output when process.exit() is removed:

[{agentid:1, host: 'asdfasdfadf'....etc}]
Tyler
  • 183
  • 9

1 Answers1

5

The database query operation is asynchronous. This means that it will only be concluded after the program executes all of the main module, including the exit system call.

Instead, you should only terminate the process when the results are obtained from the database:

var d = new db();
d.ini(c);
d.con();
d._con.query('SELECT * FROM Agents', function(err,rows,fields) {
    if(err) console.log(err);
    console.log(rows);
    process.exit();
});
d._con.end();

This is one of the typical misunderstandings of how JavaScript's asynchronous function calls work. I would advise you to read on the subject. These two questions may have some useful content:

Community
  • 1
  • 1
E_net4
  • 27,810
  • 13
  • 101
  • 139