'node js'에 해당되는 글 2건

  1. 2016.10.26 [Node js] - MKMysql 1.0.0 for Node js
  2. 2016.02.22 [Node js] - 로컬 폴더 리스트, 파일 검색 ( fs module )

[Node js] - MKMysql 1.0.0 for Node js

Node js 2016. 10. 26. 17:31
반응형

프로젝트명     : MKMysql

사용 플러그인 : mysql, generic-pool, log4js

설명             : connection pool, transaction, log 보다 쉽게 쓸라고만든겁니다 ( 사용시 이상있을경우 메일로 연락 바랍니다 )

저작권          : 알아서 변경해서 상업으로 쓰든 뭘하든 상관없습니다

첨부파일 하단


/**

 * FileName    : MKMysql.js

 * CreatedBy   : swahn

 * Version       : 1.0.0

 * UpdateDate : 2016. 10. 26

 */


var mysql  = require("mysql");

var gPool  = require("generic-pool");

var log4js = require("log4js"); 


MKMysql = module.exports = function(){

  var $this = this;

  

  $this.logPath        = "/log/mysql/";

  $this.logFileName = "mkmysql.log";

  $this.logMax        = 5;

  $this.logMaxSize  = 102400;

  $this.logger      = "";

  

  $this.tag   = "[MKMysql]";

  $this.type  = "mysql";

  $this.min   = 1;

  $this.max   = 3;

  $this.pool  = false;

  $this.log   = false;

  $this.idle  = 60;

  

  $this.color = {

    normal : "\u001b[33m",

    error  : "\u001b[31m",

    white  : "\033[39m"

  };

  

  var __init = function(){

    log4js.configure({

      appenders: [

        { type        : "file", 

          filename    : $this.logPath + $this.logFileName, 

          category    : $this.tag,

          maxLogSize  : $this.logMaxSize,

          backups     : $this.logMax }

      ]

    });

    

    $this.logger = log4js.getLogger( $this.tag );

    $this.logger.setLevel(log4js.levels.ALL);

  }();

};


/**

 * Function : MKMysql.connect

 * @type    : return mysql object

 * @parm    : (String) host, (int)    port,   (String)   user, 

 *            (String) pass, (String) dbName, (Boolean)  pool,

 *            (int)    min,  (int)    max,    (Function) cb

 * @call    : mkmysql.connect( "localhost", 3306, "root", "1234", "mysql", false, 0, 0, callBack );

 */

MKMysql.prototype.connect = function( host, port, user, pass, dbName, pool, min, max, cb ){

  var $this = this;

  var ndate = function(){

    var date  = new Date();

    var year  = date.getFullYear();

    var month = date.getMonth() + 1;

    var day   = date.getDate();

    var hour  = date.getHours();

    var min   = date.getMinutes();

    var sec   = date.getSeconds();

    var mis   = date.getMilliseconds();


    if( month < 10 ) {

      month = "0" + month;

    };

    if( day < 10 ) {

      day = "0" + day;

    };

    if( hour < 10 ) {

      hour = "0" + hour;

    };

    if( min < 10 ) {

      min = "0" + min;

    };

    if( sec < 10 ) {

      sec = "0" + sec;

    };

    

    return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;

  };

  

  if( typeof pool == "undefined" || pool == "" ) {

    pool = false;

  };

  

  $this.pool = pool;

  

  if( pool ) {

    if( typeof min == "undefined" ) {

      min = $this.min;

    };

    

    if( typeof max == "undefined" ) {

      max = $this.max;

    };

    

    if( min < 1 ) {

      min = 1;

    };

    

    if( max < 1 ) {

      max = 1;

    };

    

    if( max < min ) {

      max = min;

    };

    

    var jj = 0;

    

    $this.mysql = gPool.Pool({

      name    : $this.type,

      min     : min,

      max     : max,

      log     : $this.log,

      idleTimeoutMillis : $this.idle,

      create  : function( callBack ){

        var config = {

          host      : host,

          port      : port,

          user      : user,

          password  : pass,

          database  : dbName

        };

        

        var client = mysql.createConnection( config );

        

        client.connect(function( error ){

          if( error ) {

            $this.logger.error( error );

            console.log( $this.color.error + $this.tag + $this.color.white + " " + ndate() + " Connection Pool : failed ");

            console.error(err);

          } else {

            $this.logger.info( "connection pool success thread Id : " + client.threadId );

            console.log( $this.color.normal + $this.tag + $this.color.white + " " + ndate() + " Connection Pool : success ( " + client.threadId + " )" );

          };

          

          if( jj == min - 1 ) {

            if( typeof cb == "function" ) {

              cb( $this.mysql );

            };

          };

          

          jj++;

          callBack( error, client );

        });

      },

      destroy : function( client ){

        console.log( $this.color.normal + $this.tag + $this.color.white + " " + ndate() + " Disconnection Pool : disconnect ( " + client.threadId + " )" );

        client.end();

      }

    });

  } else {

    $this.mysql = mysql.createConnection({

      host      : host,

      port      : port,

      user      : user,

      password  : pass,

      database  : dbName

    });

    

    $this.mysql.connect(function( err ) {

      if( err ) {

        $this.logger.error( error );

        

        console.log( $this.color.error + $this.tag + $this.color.white + " " + ndate() + " Connection : failed ");

        console.error(err);

        throw err;

      } else {

        $this.logger.info( "connection success" );

        

        console.log( $this.color.normal + $this.tag + $this.color.white + " " + ndate() + " Connection : success ");

        

        if( typeof cb == "function" ) {

          cb( $this.mysql );

        };

      };

    });

  };

  

  process.on("exit", function() {

    $this.mysql.drain(function() {

      $this.mysql.destroyAllNow();

    });

    

    $this.disconnect();

  });

};


/**

 * Function : MKMysql.disconnect

 * @type    : void

 * @call    : mkmysql.disconnect();

 */

MKMysql.prototype.disconnect = function(){

  var $this = this;

  

  if( $this.pool ) {

    $this.release();

  };

  

  $this.mysql.close();

  

  $this.logger.info( "disconnect" );

};


/**

 * Function : MKMysql.release

 * @type    : void

 * @call    : mkmysql.release( client );

 */

MKMysql.prototype.release = function( client ){

  var $this = this;

  

  $this.mysql.release( client );

  

  $this.logger.info( "pool release" );

};


/**

 * Function : MKMysql.query

 * @type    : (Object) row

 * @parm    : (String) sql, (Object) parm, (Booleans) trans, (Function) cb

 * @call    : mkmysql.query(sql, parm, false, function( err, res ){ });

 */

MKMysql.prototype.query = function( sql, parm, trans, cb ){

  var $this = this;

  

  if( typeof trans == "undefined" ) {

    trans = false;

  };

  

  if( typeof trans != "boolean" ) {

    throw "`trans` must boolean type";

  };

  

  if( $this.pool == false ) {

    $this.logger.info( "Query start" );

    $this.logger.info( "Query : " + sql );

    $this.logger.info( "Parm : ", parm );

    

    if( trans ) {

      $this.logger.info( "Transaction start" );

      

      $this.mysql.beginTransaction(function(err) {

        if( err ) {

          $this.logger.error( err );

          

          throw err;

        } else {

          $this.mysql.query(sql, parm, function( err1, row, cols ){

            if( err1 ) {

              $this.logger.error( err1 );

              

              $this.mysql.rollback(function(){

                $this.logger.error( "Rollback error" );

                

                throw err1;

              });

            } else {

              $this.mysql.commit(function( err2 ){

                if( err2 ) {

                  $this.logger.error( err2 );

                  

                  $this.mysql.rollback(function(){

                    $this.logger.error( "Rollback error" );

                    

                    throw err2;

                  });

                  

                  $this.logger.info( "Rollback" );

                } else {

                  $this.logger.info( "Commit" );

                };

                

                $this.logger.info( "Transaction End" );

                $this.logger.info( "Query End" );

              });

            };

          });

        };

      });

    } else {

      $this.mysql.query(sql, parm, function( err, row, cols ){

        if( err ) {

          $this.logger.error( err );

          throw err;

        } else {

          if( typeof cb == "function" ) {

            cb( err, row );

          };

          

          $this.logger.info( "Query End" );

        };

      });

    };

  } else {

    $this.logger.info( "Query start" );

    $this.logger.info( "Query : " + sql );

    $this.logger.info( "Parm : ", parm );

    

    if( trans ) {

      $this.mysql.acquire(function( error, client ){

        $this.logger.info( "Transaction start" );

        

        client.beginTransaction(function(err) {

          if( err ) {

            $this.logger.error( err );

            

            throw err;

          } else {

            client.query(sql, parm, function( err1, row, cols ){

              if( err1 ) {

                $this.logger.error( err1 );

                

                client.rollback(function(){

                  $this.logger.error( "Rollback error" );

                  

                  throw err1;

                });

              } else {

                client.commit(function( err2 ){

                  if( err2 ) {

                    $this.logger.error( err2 );

                    

                    client.rollback(function(){

                      $this.logger.error( "Rollback error" );

                      

                      throw err2;

                    });

                    

                    $this.logger.info( "Rollback" );

                  } else {

                    $this.logger.info( "Commit" );

                  };

                  

                  $this.logger.info( "Transaction End" );

                  $this.logger.info( "Query End" );

                });

              };

            });

          };

        });

      });

    } else {

      $this.mysql.acquire(function( error, client ){

        if( error ) {

          $this.logger.error( error );

          $this.release();

          

          throw error;

        } else {

          client.query(sql, parm, function( err, rows, cols ) {

            $this.release();

            

            if( typeof cb == "function") {

              cb( err, rows );

            };

            

            $this.logger.info( "Query End" );

          });

        };

      });

    };

  };

};


첨부파일 : MKMysql 플러그인 파일, mysql 테스트 파일


MKMysql.js

mysql.js


반응형

'Node js' 카테고리의 다른 글

[Node js] - 로컬 폴더 리스트, 파일 검색 ( fs module )  (0) 2016.02.22
:

[Node js] - 로컬 폴더 리스트, 파일 검색 ( fs module )

Node js 2016. 2. 22. 10:39
반응형

var $this = this;


$this.fs    = require("fs");

$this.path = "/folderPath";


$this.fs.readdir($this.path, function( err, folders ){

  for( var i = 0; i < folders.length; i++ ) {

    var folder = folders[i];

    var fPath  = $this.path + "/" + folder;  // 하위 폴더 경로 반환

    var files  = $this.fs.readdirSync( fPath );  // 하위 폴더 내 파일 검색


    console.log( fPath );

    console.log( files );

  };

});

반응형

'Node js' 카테고리의 다른 글

[Node js] - MKMysql 1.0.0 for Node js  (0) 2016.10.26
: