Code coverage report for index.js

Statements: 99.26% (805 / 811)      Branches: 98.81% (416 / 421)      Functions: 98.72% (77 / 78)      Lines: 99.26% (802 / 808)      Ignored: 13 statements, 2 functions, 4 branches     

All files » __root__/ » index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321    13 13 13 13 13 13 13 13 13 13 13 13 13   13 4060 69943   13     13 13     1     13   13   2018 2018 2018 2018 176 176   1842 1842 1842 1842     2018 96   2018 2018 2018 2018 2018 2018 1946   2018 1994   2018 32   2018 2018   2018 4 4   2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018   2018 2017   13     13 2229     2229 216 216       2229 56   2173     2229 68 4 4         2229 2229 2081 2081     2229   5659 5659     2229 140       2229 1     2229 572     2229 364     2229 126       13 13   13 24 24 24 12   24 24 24     13 4075 4075 4075 4075 4075     13 24 12 12   12 12 12           13 2213 2213 2213 4394 712 588 588     4394       13 140 8     132   132   132 132 132     132     13 13   13 120   120   120 120 120   32   1 1 1   1 32 8 8 8 24 12 12 12   12 12       96 96   96 12 12       96 96   96 12   84     120     13 2081   2081 2081 2081 2081 2081 2057     2081 2081   2081 120   1961 1961   1961 44   1917         13 2018   2018 1909 2864 1908 1908 1908         1     109 109         2017     2017 200   2017 18362       13 1997   1997   1997 128 128 128 128     1997 1997           1997 450 450 450   1997 458     1997     1997     12 12 12 12   1997   32 32 44 44 28     32 4   28 44 44 44 44 44   28     1965 12   1953   1965     13 1973 28 4 4 4   24 24 12         1945 1 1 1 1     1945 1945 1945 1945 1945   1945 180183 180183 145173       1945   1945 1945 5835       1945 1235 1235 1235 3705 3705   1235 1235       1945   1945 1937 1937   8 8 4   8 8 8         13 2009   2009   2009 2009 1973   2009     13 1953   1953 1479 1479   1953   1953     13 216   216         216 216 216 216 216     13 1072   1072 264     808 808 808   808 808   808 540         540 540 540 540       808 540 540       808 376 376 376     432 48     48 48 48 48 48 48       384 32 32           32 32 32     384 12 372   8     384   384     13 200   200 188   12     200   200 196     200   200 180   20       13 2079 2079     13 18562   5206 5206       13 18362         18362 248     18362 44   18318     18362   18362   18362 18078 16562 16251     15941       16251 112     16562   1516   284 248 248 240   248   248 36 212 8 204 204 44 44   160       204 88   204                 36 36 27     36 36 36 36 108   36   1 1 1       13 21081               21081 12 21069 7737 5201 2536 308       21081 12     21081   2440 16 16 16 16   16       21065 54112 10160 10160 2608 2608   43952 2440   41512 24 24 24 12 12       21065 4776     21065   21065 1915 356 356 36     36   320   356 356   1559 1559 1559     1915     19150 192 18958 36 18922 188   19150   19150 28   19150 116 116 116 84 84         19150   19150 9094 21411 21411   9094 9094   10056 10056   10056 30068 30068 19984   10084 10084 10084   30068     19150     13 284 284 1048   284     13 162 162 15376   162     13 69386 52516 52516     16870 16870 446 446     16424 16424     13 192   192 92   192 192   192 192 192 140 132   8   140 152     52 44   8   52 20         13 1969     1969 88 88   1969     1969 1757     1969 1969 1969 1969     13 515 515 515 515 64 200 200 200 16   184           13   2236 7293 480   6813 68 68     6745 6745 1740   5005 1184   3821     2236 10987 84 24   84 10903 20 16   20     10883 10883 392 10491 10060   431     10987       13 387 387 387     13 128       13 24 24 24 12   24 16 8 4         13 396 352 352     44         13 96 24 24 24 24   72 72   72 12   60 60     13 216 216 16   200 8   192           40 4   40 40 40 2076   40   152     13 88 88 24 8   24 64 16 8   16 48 32 16   32 32 32 80 80   32 8     16 16   88 88     13 11134 11134 11134 308 104   308 308         13 12 8   4     13 375 375 375 375 375 375 375 375   375 10759 10759 10759 220   10539     10759 36 10723 10477   246 246 460 20 20       10759     375 375   375 375 375     13 375   375   64 64 64 28   36 4   64     311 303   10451 32   32 24   32 10419 10406 10350   10406   20       10451 104 4   100     10451       311 307       13 304 304 304 12   292   304 108             13 124 124 124 124 124 28   24 24     28   96 96 96 92 92 92     96 304 304 304 108   196   304 92   304 304   96 96 96     13 1998 1612 1612 1612 386 200 200 200 36 12   36 4   32 32   164   186 182 182   1994 4   1990     13 13 13 13      
'use strict';
 
var net = require('net');
var tls = require('tls');
var URL = require('url');
var util = require('util');
var utils = require('./lib/utils');
var Queue = require('double-ended-queue');
var Command = require('./lib/command');
var events = require('events');
var parsers = [];
var commands = require('redis-commands');
var connection_id = 0;
var default_port = 6379;
var default_host = '127.0.0.1';
 
function noop () {}
function clone (obj) { return JSON.parse(JSON.stringify(obj || {})); }
function debug (msg) { if (exports.debug_mode) { console.error(msg); } }
 
exports.debug_mode = /\bredis\b/i.test(process.env.NODE_DEBUG);
 
// Hiredis might not be installed
try {
    parsers.push(require('./lib/parsers/hiredis'));
} catch (err) {
    /* istanbul ignore next: won't be reached with tests */
    debug('Hiredis parser not installed.');
}
 
parsers.push(require('./lib/parsers/javascript'));
 
function RedisClient (options) {
    // Copy the options so they are not mutated
    options = clone(options);
    events.EventEmitter.call(this);
    var cnx_options = {};
    if (options.path) {
        cnx_options.path = options.path;
        this.address = options.path;
    } else {
        cnx_options.port = +options.port || default_port;
        cnx_options.host = options.host || default_host;
        cnx_options.family = (!options.family && net.isIP(cnx_options.host)) || (options.family === 'IPv6' ? 6 : 4);
        this.address = cnx_options.host + ':' + cnx_options.port;
    }
    /* istanbul ignore next: travis does not work with stunnel atm. Therefor the tls tests are skipped on travis */
    for (var tls_option in options.tls) { // jshint ignore: line
        cnx_options[tls_option] = options.tls[tls_option];
    }
    this.connection_options = cnx_options;
    this.connection_id = ++connection_id;
    this.connected = false;
    this.ready = false;
    this.connections = 0;
    if (options.socket_nodelay === undefined) {
        options.socket_nodelay = true;
    }
    if (options.socket_keepalive === undefined) {
        options.socket_keepalive = true;
    }
    for (var command in options.rename_commands) { // jshint ignore: line
        options.rename_commands[command.toLowerCase()] = options.rename_commands[command];
    }
    options.return_buffers = !!options.return_buffers;
    options.detect_buffers = !!options.detect_buffers;
    // Override the detect_buffers setting if return_buffers is active and print a warning
    if (options.return_buffers && options.detect_buffers) {
        console.warn('>> WARNING: You activated return_buffers and detect_buffers at the same time. The return value is always going to be a buffer.');
        options.detect_buffers = false;
    }
    this.should_buffer = false;
    this.max_attempts = options.max_attempts | 0;
    this.command_queue = new Queue(); // Holds sent commands to de-pipeline them
    this.offline_queue = new Queue(); // Holds commands issued but not able to be sent
    this.connect_timeout = +options.connect_timeout || 3600000; // 60 * 60 * 1000 ms
    this.enable_offline_queue = options.enable_offline_queue === false ? false : true;
    this.retry_max_delay = +options.retry_max_delay || null;
    this.initialize_retry_vars();
    this.pub_sub_mode = false;
    this.subscription_set = {};
    this.monitoring = false;
    this.closing = false;
    this.server_info = {};
    this.auth_pass = options.auth_pass;
    this.parser_module = null;
    this.selected_db = null; // Save the selected db here, used when reconnecting
    this.old_state = null;
    this.pipeline = 0;
    this.options = options;
    // Init parser once per instance
    this.init_parser();
    this.create_stream();
}
util.inherits(RedisClient, events.EventEmitter);
 
// Attention: the function name "create_stream" should not be changed, as other libraries need this to mock the stream (e.g. fakeredis)
RedisClient.prototype.create_stream = function () {
    var self = this;
 
    // On a reconnect destroy the former stream and retry
    if (this.stream) {
        this.stream.removeAllListeners();
        this.stream.destroy();
    }
 
    /* istanbul ignore if: travis does not work with stunnel atm. Therefor the tls tests are skipped on travis */
    if (this.options.tls) {
	    this.stream = tls.connect(this.connection_options);
    } else {
	    this.stream = net.createConnection(this.connection_options);
	}
 
    if (this.options.connect_timeout) {
        this.stream.setTimeout(this.connect_timeout, function () {
            self.retry_totaltime = self.connect_timeout;
            self.connection_gone('timeout');
        });
    }
 
    /* istanbul ignore next: travis does not work with stunnel atm. Therefor the tls tests are skipped on travis */
    var connect_event = this.options.tls ? "secureConnect" : "connect";
    this.stream.once(connect_event, function () {
        this.removeAllListeners("timeout");
        self.on_connect();
    });
 
    this.stream.on('data', function (buffer_from_socket) {
        // The buffer_from_socket.toString() has a significant impact on big chunks and therefor this should only be used if necessary
        debug('Net read ' + self.address + ' id ' + self.connection_id); // + ': ' + buffer_from_socket.toString());
        self.reply_parser.execute(buffer_from_socket);
    });
 
    this.stream.on('error', function (err) {
        self.on_error(err);
    });
 
    /* istanbul ignore next: travis does not work with stunnel atm. Therefor the tls tests are skipped on travis */
    this.stream.on('clientError', function (err) {
        self.on_error(err);
    });
 
    this.stream.once('close', function () {
        self.connection_gone('close');
    });
 
    this.stream.once('end', function () {
        self.connection_gone('end');
    });
 
    this.stream.on('drain', function () {
        self.drain();
    });
};
 
RedisClient.prototype.cork = noop;
RedisClient.prototype.uncork = noop;
 
RedisClient.prototype.duplicate = function (options) {
    var existing_options = clone(this.options);
    options = clone(options);
    for (var elem in options) { // jshint ignore: line
        existing_options[elem] = options[elem];
    }
    var client = new RedisClient(existing_options);
    client.selected_db = this.selected_db;
    return client;
};
 
RedisClient.prototype.initialize_retry_vars = function () {
    this.retry_timer = null;
    this.retry_totaltime = 0;
    this.retry_delay = 200;
    this.retry_backoff = 1.7;
    this.attempts = 1;
};
 
RedisClient.prototype.unref = function () {
    if (this.connected) {
        debug("Unref'ing the socket connection");
        this.stream.unref();
    } else {
        debug('Not connected yet, will unref later');
        this.once('connect', function () {
            this.unref();
        });
    }
};
 
// Flush provided queues, erroring any items with a callback first
RedisClient.prototype.flush_and_error = function (error, queue_names) {
    var command_obj;
    queue_names = queue_names || ['offline_queue', 'command_queue'];
    for (var i = 0; i < queue_names.length; i++) {
        while (command_obj = this[queue_names[i]].shift()) {
            if (typeof command_obj.callback === 'function') {
                error.command = command_obj.command.toUpperCase();
                command_obj.callback(error);
            }
        }
        this[queue_names[i]] = new Queue();
    }
};
 
RedisClient.prototype.on_error = function (err) {
    if (this.closing) {
        return;
    }
 
    err.message = 'Redis connection to ' + this.address + ' failed - ' + err.message;
 
    debug(err.message);
 
    this.connected = false;
    this.ready = false;
    this.emit('error', err);
    // 'error' events get turned into exceptions if they aren't listened for. If the user handled this error
    // then we should try to reconnect.
    this.connection_gone('error');
};
 
var noPasswordIsSet = /no password is set/;
var loading = /LOADING/;
 
RedisClient.prototype.do_auth = function () {
    var self = this;
 
    debug('Sending auth to ' + self.address + ' id ' + self.connection_id);
 
    self.send_anyway = true;
    self.send_command('auth', [this.auth_pass], function (err, res) {
        if (err) {
            /* istanbul ignore if: this is almost impossible to test */
            Iif (loading.test(err.message)) {
                // If redis is still loading the db, it will not authenticate and everything else will fail
                debug('Redis still loading, trying to authenticate later');
                setTimeout(function () {
                    self.do_auth();
                }, 333);
                return;
            } else if (noPasswordIsSet.test(err.message)) {
                debug('Warning: Redis server does not require a password, but a password was supplied.');
                err = null;
                res = 'OK';
            } else if (self.auth_callback) {
                self.auth_callback(err);
                self.auth_callback = null;
                return;
            } else {
                self.emit('error', err);
                return;
            }
        }
 
        res = res.toString();
        debug('Auth succeeded ' + self.address + ' id ' + self.connection_id);
 
        if (self.auth_callback) {
            self.auth_callback(null, res);
            self.auth_callback = null;
        }
 
        // Now we are really connected
        self.emit('connect');
        self.initialize_retry_vars();
 
        if (self.options.no_ready_check) {
            self.on_ready();
        } else {
            self.ready_check();
        }
    });
    self.send_anyway = false;
};
 
RedisClient.prototype.on_connect = function () {
    debug('Stream connected ' + this.address + ' id ' + this.connection_id);
 
    this.connected = true;
    this.ready = false;
    this.connections += 1;
    this.emitted_end = false;
    if (this.options.socket_nodelay) {
        this.stream.setNoDelay();
    }
    this.stream.setKeepAlive(this.options.socket_keepalive);
    this.stream.setTimeout(0);
 
    if (typeof this.auth_pass === 'string') {
        this.do_auth();
    } else {
        this.emit('connect');
        this.initialize_retry_vars();
 
        if (this.options.no_ready_check) {
            this.on_ready();
        } else {
            this.ready_check();
        }
    }
};
 
RedisClient.prototype.init_parser = function () {
    var self = this;
 
    if (this.options.parser) {
        if (!parsers.some(function (parser) {
            if (parser.name === self.options.parser) {
                self.parser_module = parser;
                debug('Using parser module: ' + self.parser_module.name);
                return true;
            }
        })) {
            // Do not emit this error
            // This should take down the app if anyone made such a huge mistake or should somehow be handled in user code
            throw new Error("Couldn't find named parser " + self.options.parser + " on this system");
        }
    } else {
        debug('Using default parser module: ' + parsers[0].name);
        this.parser_module = parsers[0];
    }
 
    // return_buffers sends back Buffers from parser to callback. detect_buffers sends back Buffers from parser, but
    // converts to Strings if the input arguments are not Buffers.
    this.reply_parser = new this.parser_module.Parser(self.options.return_buffers || self.options.detect_buffers);
    // Important: Only send results / errors async.
    // That way the result / error won't stay in a try catch block and catch user things
    this.reply_parser.send_error = function (data) {
        self.return_error(data);
    };
    this.reply_parser.send_reply = function (data) {
        self.return_reply(data);
    };
};
 
RedisClient.prototype.on_ready = function () {
    var self = this;
 
    this.ready = true;
 
    if (this.old_state !== null) {
        this.monitoring = this.old_state.monitoring;
        this.pub_sub_mode = this.old_state.pub_sub_mode;
        this.selected_db = this.old_state.selected_db;
        this.old_state = null;
    }
 
    var cork;
    if (!this.stream.cork) {
    I    cork = function (len) {
            self.pipeline = len;
            self.pipeline_queue = new Queue(len);
        };
    } else {
        cork = function (len) {
            self.pipeline = len;
            self.pipeline_queue = new Queue(len);
            self.stream.cork();
        };
        this.uncork = function () {
            self.stream.uncork();
        };
    }
    this.cork = cork;
 
    // magically restore any modal commands from a previous connection
    if (this.selected_db !== null) {
        // this trick works if and only if the following send_command
        // never goes into the offline queue
        var pub_sub_mode = this.pub_sub_mode;
        this.pub_sub_mode = false;
        this.send_command('select', [this.selected_db]);
        this.pub_sub_mode = pub_sub_mode;
    }
    if (this.pub_sub_mode === true) {
        // only emit 'ready' when all subscriptions were made again
        var callback_count = 0;
        var callback = function () {
            callback_count--;
            if (callback_count === 0) {
                self.emit('ready');
            }
        };
        if (this.options.disable_resubscribing) {
            return;
        }
        Object.keys(this.subscription_set).forEach(function (key) {
            var space_index = key.indexOf(' ');
            var parts = [key.slice(0, space_index), key.slice(space_index + 1)];
            debug('Sending pub/sub on_ready ' + parts[0] + ', ' + parts[1]);
            callback_count++;
            self.send_command(parts[0] + 'scribe', [parts[1]], callback);
        });
        return;
    }
 
    if (this.monitoring) {
        this.send_command('monitor', []);
    } else {
        this.send_offline_queue();
    }
    this.emit('ready');
};
 
RedisClient.prototype.on_info_cmd = function (err, res) {
    if (err) {
        if (err.message === "ERR unknown command 'info'") {
            this.server_info = {};
            this.on_ready();
            return;
        } else {
            err.message = 'Ready check failed: ' + err.message;
            this.emit('error', err);
            return;
       }
    }
 
    /* istanbul ignore if: some servers might not respond with any info data. This is just a safety check that is difficult to test */
    if (!res) {
    I    debug('The info command returned without any data.');
        this.server_info = {};
        this.on_ready();
        return;
    }
 
    var obj = {};
    var lines = res.toString().split('\r\n');
    var i = 0;
    var key = 'db' + i;
    var line, retry_time, parts, sub_parts;
 
    for (i = 0; i < lines.length; i++) {
        parts = lines[i].split(':');
        if (parts[1]) {
            obj[parts[0]] = parts[1];
        }
    }
 
    obj.versions = [];
    /* istanbul ignore else: some redis servers do not send the version */
    if (obj.redis_version) {
    E    obj.redis_version.split('.').forEach(function (num) {
            obj.versions.push(+num);
        });
    }
 
    while (obj[key]) {
        parts = obj[key].split(',');
        obj[key] = {};
        while (line = parts.pop()) {
            sub_parts = line.split('=');
            obj[key][sub_parts[0]] = +sub_parts[1];
        }
        i++;
        key = 'db' + i;
    }
 
    // Expose info key/vals to users
    this.server_info = obj;
 
    if (!obj.loading || obj.loading === '0') {
        debug('Redis server ready.');
        this.on_ready();
    } else {
        retry_time = obj.loading_eta_seconds * 1000;
        if (retry_time > 1000) {
            retry_time = 1000;
        }
        debug('Redis server still loading, trying again in ' + retry_time);
        setTimeout(function (self) {
            self.ready_check();
        }, retry_time, this);
    }
};
 
RedisClient.prototype.ready_check = function () {
    var self = this;
 
    debug('Checking server ready state...');
 
    this.send_anyway = true;  // secret flag to send_command to send something even if not 'ready'
    this.info(function (err, res) {
        self.on_info_cmd(err, res);
    });
    this.send_anyway = false;
};
 
RedisClient.prototype.send_offline_queue = function () {
    var command_obj;
 
    while (command_obj = this.offline_queue.shift()) {
        debug('Sending offline command: ' + command_obj.command);
        this.send_command(command_obj.command, command_obj.args, command_obj.callback);
    }
    this.drain();
    // Even though items were shifted off, Queue backing store still uses memory until next add, so just get a new Queue
    this.offline_queue = new Queue();
};
 
var retry_connection = function (self) {
    debug('Retrying connection...');
 
    self.emit('reconnecting', {
        delay: self.retry_delay,
        attempt: self.attempts
    });
 
    self.retry_totaltime += self.retry_delay;
    self.attempts += 1;
    self.retry_delay = Math.round(self.retry_delay * self.retry_backoff);
    self.create_stream();
    self.retry_timer = null;
};
 
RedisClient.prototype.connection_gone = function (why) {
    var error;
    // If a retry is already in progress, just let that happen
    if (this.retry_timer) {
        return;
    }
 
    debug('Redis connection is gone from ' + why + ' event.');
    this.connected = false;
    this.ready = false;
    // Deactivate cork to work with the offline queue
    this.cork = noop;
    this.pipeline = 0;
 
    if (this.old_state === null) {
        var state = {
            monitoring: this.monitoring,
            pub_sub_mode: this.pub_sub_mode,
            selected_db: this.selected_db
        };
        this.old_state = state;
        this.monitoring = false;
        this.pub_sub_mode = false;
        this.selected_db = null;
    }
 
    // since we are collapsing end and close, users don't expect to be called twice
    if (!this.emitted_end) {
        this.emit('end');
        this.emitted_end = true;
    }
 
    // If this is a requested shutdown, then don't retry
    if (this.closing) {
        debug('Connection ended from quit command, not retrying.');
        this.flush_and_error(new Error('Redis connection gone from ' + why + ' event.'));
        return;
    }
 
    if (this.max_attempts !== 0 && this.attempts >= this.max_attempts || this.retry_totaltime >= this.connect_timeout) {
        var message = this.retry_totaltime >= this.connect_timeout ?
            'connection timeout exceeded.' :
            'maximum connection attempts exceeded.';
        error = new Error('Redis connection in broken state: ' + message);
        error.code = 'CONNECTION_BROKEN';
        this.flush_and_error(error);
        this.emit('error', error);
        this.end();
        return;
    }
 
    // Flush all commands that have not yet returned. We can't handle them appropriatly
    if (this.command_queue.length !== 0) {
        error = new Error('Redis connection lost and command aborted in uncertain state. It might have been processed.');
        error.code = 'UNCERTAIN_STATE';
        // TODO: Evaluate to add this
        // if (this.options.retry_commands) {
        //     this.offline_queue.unshift(this.command_queue.toArray());
        //     error.message = 'Command aborted in uncertain state and queued for next connection.';
        // }
        this.flush_and_error(error, ['command_queue']);
        error.message = 'Redis connection lost and commands aborted in uncertain state. They might have been processed.';
        this.emit('error', error);
    }
 
    if (this.retry_max_delay !== null && this.retry_delay > this.retry_max_delay) {
        this.retry_delay = this.retry_max_delay;
    } else if (this.retry_totaltime + this.retry_delay > this.connect_timeout) {
        // Do not exceed the maximum
        this.retry_delay = this.connect_timeout - this.retry_totaltime;
    }
 
    debug('Retry connection in ' + this.retry_delay + ' ms');
 
    this.retry_timer = setTimeout(retry_connection, this.retry_delay, this);
};
 
RedisClient.prototype.return_error = function (err) {
    var command_obj = this.command_queue.shift(), queue_len = this.command_queue.length;
    // send_command might have been used wrong => catch those cases too
    if (command_obj.command && command_obj.command.toUpperCase) {
        err.command = command_obj.command.toUpperCase();
    } else {
        err.command = command_obj.command;
    }
 
    var match = err.message.match(utils.errCode);
    // LUA script could return user errors that don't behave like all other errors!
    if (match) {
        err.code = match[1];
    }
 
    this.emit_idle(queue_len);
 
    if (command_obj.callback) {
        command_obj.callback(err);
    } else {
        this.emit('error', err);
    }
};
 
RedisClient.prototype.drain = function () {
    this.emit('drain');
    this.should_buffer = false;
};
 
RedisClient.prototype.emit_idle = function (queue_len) {
    if (this.pub_sub_mode === false && queue_len === 0) {
        // Free the queue capacity memory by using a new queue
        this.command_queue = new Queue();
        this.emit('idle');
    }
};
 
RedisClient.prototype.return_reply = function (reply) {
    var command_obj, len, type, timestamp, argindex, args, queue_len;
 
    // If the 'reply' here is actually a message received asynchronously due to a
    // pubsub subscription, don't pop the command queue as we'll only be consuming
    // the head command prematurely.
    if (this.pub_sub_mode && Array.isArray(reply) && reply[0]) {
        type = reply[0].toString();
    }
 
    if (this.pub_sub_mode && (type === 'message' || type === 'pmessage')) {
        debug('Received pubsub message');
    } else {
        command_obj = this.command_queue.shift();
    }
 
    queue_len = this.command_queue.length;
 
    this.emit_idle(queue_len);
 
    if (command_obj && !command_obj.sub_command) {
        if (typeof command_obj.callback === 'function') {
            if ('exec' !== command_obj.command) {
                if (command_obj.buffer_args === false) {
                    // If detect_buffers option was specified, then the reply from the parser will be Buffers.
                    // If this command did not use Buffer arguments, then convert the reply to Strings here.
                    reply = utils.reply_to_strings(reply);
                }
 
                // TODO - confusing and error-prone that hgetall is special cased in two places
                if ('hgetall' === command_obj.command) {
                    reply = utils.reply_to_object(reply);
                }
            }
            command_obj.callback(null, reply);
        } else {
            debug('No callback for reply');
        }
    } else if (this.pub_sub_mode || command_obj && command_obj.sub_command) {
        if (Array.isArray(reply)) {
        E    if ((!command_obj || command_obj.buffer_args === false) && !this.options.return_buffers) {
                reply = utils.reply_to_strings(reply);
            }
            type = reply[0].toString();
 
            if (type === 'message') {
                this.emit('message', reply[1], reply[2]); // channel, message
            } else if (type === 'pmessage') {
                this.emit('pmessage', reply[1].toString(), reply[2], reply[3]); // pattern, channel, message
            } else if (type === 'subscribe' || type === 'unsubscribe' || type === 'psubscribe' || type === 'punsubscribe') {
                if E(reply[2] === 0) {
                    this.pub_sub_mode = false;
                    debug('All subscriptions removed, exiting pub/sub mode');
                } else {
                    this.pub_sub_mode = true;
                }
                // Subscribe commands take an optional callback and also emit an event, but only the first response is included in the callback
                // TODO - document this or fix it so it works in a more obvious way
                if (command_obj && typeof command_obj.callback === 'function') {
                    command_obj.callback(null, reply[1]);
                }
                this.emit(type, reply[1], reply[2]); // channel, count
            } else {
                this.emit('error', new Error('subscriptions are active but got unknown reply type ' + type));
            }
        } else if (!this.closing) {
            this.emit('error', new Error('subscriptions are active but got an invalid reply: ' + reply));
        }
    }
    /* istanbul ignore else: this is a safety check that we should not be able to trigger */
    else if (this.monitoring) {
        iEf (typeof reply !== 'string') {
            reply = reply.toString();
        }
        // If in monitoring mode only two commands are valid ones: AUTH and MONITOR wich reply with OK
        len = reply.indexOf(' ');
        timestamp = reply.slice(0, len);
        argindex = reply.indexOf('"');
        args = reply.slice(argindex + 1, -1).split('" "').map(function (elem) {
            return elem.replace(/\\"/g, '"');
        });
        this.emit('monitor', timestamp, args);
    } else {
        var err = new Error('node_redis command queue state error. If you can reproduce this, please report it.');
        err.command_obj = command_obj;
        this.emit('error', err);
    }
};
 
RedisClient.prototype.send_command = function (command, args, callback) {
    var arg, command_obj, i, err,
        stream = this.stream,
        command_str = '',
        buffer_args = false,
        big_data = false,
        prefix_keys,
        buffer = this.options.return_buffers;
 
    if (args === undefined) {
        args = [];
    } else if (!callback) {
        if (typeof args[args.length - 1] === 'function') {
            callback = args.pop();
        } else if (typeof args[args.length - 1] === 'undefined') {
            args.pop();
        }
    }
 
    if (callback && process.domain) {
        callback = process.domain.bind(callback);
    }
 
    if (command === 'set' || command === 'setex') {
        // if the value is undefined or null and command is set or setx, need not to send message to redis
        if (args[args.length - 1] === undefined || args[args.length - 1] === null) {
            command = command.toUpperCase();
            err = new Error('send_command: ' + command + ' value must not be undefined or null');
            err.command = command;
            this.callback_emit_error(callback, err);
            // Singal no buffering
            return true;
        }
    }
 
    for (i = 0; i < args.length; i += 1) {
        if (Buffer.isBuffer(args[i])) {
            buffer_args = true;
            if (this.pipeline !== 0) {
                this.pipeline += 2;
                this.writeDefault = this.writeBuffers;
            }
        } else if (typeof args[i] !== 'string') {
            args[i] = String(args[i]);
        // 30000 seemed to be a good value to switch to buffers after testing and checking the pros and cons
        } else if (args[i].length > 30000) {
            big_data = true;
            args[i] = new Buffer(args[i]);
            if (this.pipeline !== 0) {
                this.pipeline += 2;
                this.writeDefault = this.writeBuffers;
            }
        }
    }
    if (this.options.detect_buffers) {
        buffer = buffer_args;
    }
 
    command_obj = new Command(command, args, false, buffer, callback);
 
    if (!this.ready && !this.send_anyway || !stream.writable) {
        if (this.closing || !this.enable_offline_queue) {
            command = command.toUpperCase();
            if (!this.closing) {
                var msg = !stream.writable ?
                    'Stream not writeable.' :
                    'The connection is not yet established and the offline queue is deactivated.';
                err = new Error(command + " can't be processed. " + msg);
            } else {
                err = new Error(command + " can't be processed. The connection has already been closed.");
            }
            err.command = command;
            this.callback_emit_error(callback, err);
        } else {
            debug('Queueing ' + command + ' for next server connection.');
            this.offline_queue.push(command_obj);
            this.should_buffer = true;
        }
        // Return false to signal buffering
        return !this.should_buffer;
    }
 
    if (command === 'subscribe' || command === 'psubscribe' || command === 'unsubscribe' || command === 'punsubscribe') {
        this.pub_sub_command(command_obj);
    } else if (command === 'monitor') {
        this.monitoring = true;
    } else if (command === 'quit') {
        this.closing = true;
    }
    this.command_queue.push(command_obj);
 
    if (typeof this.options.rename_commands !== 'undefined' && this.options.rename_commands[command]) {
        command = this.options.rename_commands[command];
    }
    if (this.options.prefix) {
        prefix_keys = commands.getKeyIndexes(command, args);
        i = prefix_keys.pop();
        while (i !== undefined) {
            args[i] = this.options.prefix + args[i];
            i = prefix_keys.pop();
        }
    }
    // Always use 'Multi bulk commands', but if passed any Buffer args, then do multiple writes, one for each arg.
    // This means that using Buffers in commands is going to be slower, so use Strings if you don't already have a Buffer.
    command_str = '*' + (args.length + 1) + '\r\n$' + command.length + '\r\n' + command + '\r\n';
 
    if (!buffer_args && !big_data) { // Build up a string and send entire command in one write
        for (i = 0; i < args.length; i += 1) {
            arg = args[i];
            command_str += '$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n';
        }
        debug('Send ' + this.address + ' id ' + this.connection_id + ': ' + command_str);
        this.write(command_str);
    } else {
        debug('Send command (' + command_str + ') has Buffer arguments');
        this.write(command_str);
 
        for (i = 0; i < args.length; i += 1) {
            arg = args[i];
            if (typeof arg === 'string') {
                this.write('$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n');
            } else {
                this.write('$' + arg.length + '\r\n');
                this.write(arg);
                this.write('\r\n');
            }
            debug('send_command: buffer send ' + arg.length + ' bytes');
        }
    }
    return !this.should_buffer;
};
 
RedisClient.prototype.writeDefault = RedisClient.prototype.writeStrings = function (data) {
    var command, str = '';
    while (command = this.pipeline_queue.shift()) {
        str += command;
    }
    this.should_buffer = !this.stream.write(str + data);
};
 
RedisClient.prototype.writeBuffers = function (data) {
    var command;
    while (command = this.pipeline_queue.shift()) {
        this.stream.write(command);
    }
    this.should_buffer = !this.stream.write(data);
};
 
RedisClient.prototype.write = function (data) {
    if (this.pipeline === 0) {
        this.should_buffer = !this.stream.write(data);
        return;
    }
 
    this.pipeline--;
    if (this.pipeline === 0) {
        this.writeDefault(data);
        return;
    }
 
    this.pipeline_queue.push(data);
    return;
};
 
RedisClient.prototype.pub_sub_command = function (command_obj) {
    var i, key, command, args;
 
    if (this.pub_sub_mode === false) {
        debug('Entering pub/sub mode from ' + command_obj.command);
    }
    this.pub_sub_mode = true;
    command_obj.sub_command = true;
 
    command = command_obj.command;
    args = command_obj.args;
    if (command === 'subscribe' || command === 'psubscribe') {
        if (command === 'subscribe') {
            key = 'sub';
        } else {
            key = 'psub';
        }
        for (i = 0; i < args.length; i++) {
            this.subscription_set[key + ' ' + args[i]] = true;
        }
    } else {
        if (command === 'unsubscribe') {
            key = 'sub';
        } else {
            key = 'psub';
        }
        for (i = 0; i < args.length; i++) {
            delete this.subscription_set[key + ' ' + args[i]];
        }
    }
};
 
RedisClient.prototype.end = function (flush) {
    this.stream._events = {};
 
    // Clear retry_timer
    if (this.retry_timer){
        clearTimeout(this.retry_timer);
        this.retry_timer = null;
    }
    this.stream.on('error', noop);
 
    // Flush queue if wanted
    if (flush) {
        this.flush_and_error(new Error("The command can't be processed. The connection has already been closed."));
    }
 
    this.connected = false;
    this.ready = false;
    this.closing = true;
    return this.stream.destroySoon();
};
 
function Multi(client, args) {
    this._client = client;
    this.queue = new Queue();
    var command, tmp_args;
    if (Array.isArray(args)) {
        for (var i = 0; i < args.length; i++) {
            command = args[i][0];
            tmp_args = args[i].slice(1);
            if (Array.isArray(command)) {
                this[command[0]].apply(this, command.slice(1).concat(tmp_args));
            } else {
                this[command].apply(this, tmp_args);
            }
        }
    }
}
 
commands.list.forEach(function (command) {
// var command;
// while (command = commands.list.pop()) {
 
    RedisClient.prototype[command.toUpperCase()] = RedisClient.prototype[command] = function (command, key, arg, callback) {
        console.log(this);
        if (Array.isArray(key)) {
            return this.send_command(command, key, arg);
        }
        if (Array.isArray(arg)) {
            arg = [key].concat(arg);
            return this.send_command(command, arg, callback);
        }
        // Speed up the common case
        var len = arguments.length;
        if (len === 2) {
            return this.send_command(command, [key, arg]);
        }
        if (len === 3) {
            return this.send_command(command, [key, arg, callback]);
        }
        return this.send_command(command, utils.to_array(arguments));
    }; //.bind(RedisClient, command);
 
    Multi.prototype[command.toUpperCase()] = Multi.prototype[command] = function (command, key, arg, callback) {
        if (Array.isArray(key)) {
            if (arg) {
                key = key.concat([arg]);
            }
            this.queue.push([command].concat(key));
        } else if (Array.isArray(arg)) {
            if (callback) {
                arg = arg.concat([callback]);
            }
            this.queue.push([command, key].concat(arg));
        } else {
            // Speed up the common case
            var len = arguments.length;
            if (len === 2) {
                this.queue.push([command, key, arg]);
            } else if (len === 3) {
                this.queue.push([command, key, arg, callback]);
            } else {
                this.queue.push([command].concat(utils.to_array(arguments)));
            }
        }
        return this;
    }; //.bind(Multi, command);
});
 
RedisClient.prototype.multi = RedisClient.prototype.MULTI = function (args) {
    var multi = new Multi(this, args);
    multi.exec = multi.EXEC = multi.exec_transaction;
    return multi;
};
 
RedisClient.prototype.batch = RedisClient.prototype.BATCH = function (args) {
    return new Multi(this, args);
};
 
// Store db in this.select_db to restore it on reconnect
RedisClient.prototype.select = RedisClient.prototype.SELECT = function (db, callback) {
    var self = this;
    return this.send_command('select', [db], function (err, res) {
        if (err === null) {
            self.selected_db = db;
        }
        if (typeof callback === 'function') {
            callback(err, res);
        } else if (err) {
            self.emit('error', err);
        }
    });
};
 
RedisClient.prototype.callback_emit_error = function (callback, err) {
    if (callback) {
        setImmediate(function () {
            callback(err);
        });
    } else {
        this.emit('error', err);
    }
};
 
// Stash auth for connect and reconnect. Send immediately if already connected.
RedisClient.prototype.auth = RedisClient.prototype.AUTH = function (pass, callback) {
    if (typeof pass !== 'string') {
        var err = new Error('The password has to be of type "string"');
        err.command = 'AUTH';
        this.callback_emit_error(callback, err);
        return true;
    }
    this.auth_pass = pass;
    debug('Saving auth as ' + this.auth_pass);
    // Only run the callback once. So do not safe it if already connected
    if (this.connected) {
        return this.send_command('auth', [this.auth_pass], callback);
    }
    this.auth_callback = callback;
    return true;
};
 
RedisClient.prototype.hmset = RedisClient.prototype.HMSET = function (key, args, callback) {
    var field, tmp_args;
    if (Array.isArray(key)) {
        return this.send_command('hmset', key, args);
    }
    if (Array.isArray(args)) {
        return this.send_command('hmset', [key].concat(args), callback);
    }
    if (typeof args === 'object') {
        // User does: client.hmset(key, {key1: val1, key2: val2})
        // assuming key is a string, i.e. email address
 
        // if key is a number, i.e. timestamp, convert to string
        // TODO: This seems random and no other command get's the key converted => either all or none should behave like this
        if (typeof key !== 'string') {
            key = key.toString();
        }
        tmp_args = [key];
        var fields = Object.keys(args);
        while (field = fields.shift()) {
            tmp_args.push(field, args[field]);
        }
        return this.send_command('hmset', tmp_args, callback);
    }
    return this.send_command('hmset', utils.to_array(arguments));
};
 
Multi.prototype.hmset = Multi.prototype.HMSET = function (key, args, callback) {
    var tmp_args, field;
    if (Array.isArray(key)) {
        if (args) {
            key = key.concat([args]);
        }
        tmp_args = ['hmset'].concat(key);
    } else if (Array.isArray(args)) {
        if (callback) {
            args = args.concat([callback]);
        }
        tmp_args = ['hmset', key].concat(args);
    } else if (typeof args === 'object') {
        if (typeof key !== 'string') {
            key = key.toString();
        }
        tmp_args = ['hmset', key];
        var fields = Object.keys(args);
        while (field = fields.shift()) {
            tmp_args.push(field);
            tmp_args.push(args[field]);
        }
        if (callback) {
            tmp_args.push(callback);
        }
    } else {
        tmp_args = utils.to_array(arguments);
        tmp_args.unshift('hmset');
    }
    this.queue.push(tmp_args);
    return this;
};
 
Multi.prototype.send_command = function (command, args, index, cb) {
    var self = this;
    this._client.send_command(command, args, function (err, reply) {
        if (err) {
            if (cb) {
                cb(err);
            }
            err.position = index;
            self.errors.push(err);
        }
    });
};
 
Multi.prototype.exec_atomic = function (callback) {
    if (this.queue.length < 2) {
        return this.exec_batch(callback);
    }
    return this.exec(callback);
};
 
Multi.prototype.exec_transaction = function (callback) {
    var self = this;
    var len = this.queue.length;
    var cb;
    this.errors = [];
    this.callback = callback;
    this._client.cork(len + 2);
    this.wants_buffers = new Array(len);
    this.send_command('multi', []);
    // Drain queue, callback will catch 'QUEUED' or error
    for (var index = 0; index < len; index++) {
        var args = this.queue.get(index).slice(0);
        var command = args.shift();
        if (typeof args[args.length - 1] === 'function') {
            cb = args.pop();
        } else {
            cb = undefined;
        }
        // Keep track of who wants buffer responses:
        if (this._client.options.return_buffers) {
            this.wants_buffers[index] = true;
        } else if (!this._client.options.detect_buffers) {
            this.wants_buffers[index] = false;
        } else {
            this.wants_buffers[index] = false;
            for (var i = 0; i < args.length; i += 1) {
                if (Buffer.isBuffer(args[i])) {
                    this.wants_buffers[index] = true;
                    break;
                }
            }
        }
        this.send_command(command, args, index, cb);
    }
 
    this._client.send_command('exec', [], function(err, replies) {
        self.execute_callback(err, replies);
    });
    this._client.uncork();
    this._client.writeDefault = this._client.writeStrings;
    return !this._client.should_buffer;
};
 
Multi.prototype.execute_callback = function (err, replies) {
    var i = 0, args;
 
    if (err) {
        // The errors would be circular
        var connection_error = ['CONNECTION_BROKEN', 'UNCERTAIN_STATE'].indexOf(err.code) !== -1;
        err.errors = connection_error ? [] : this.errors;
        if (this.callback) {
            this.callback(err);
            // Exclude connection errors so that those errors won't be emitted twice
        } else if (!connection_error) {
            this._client.emit('error', err);
        }
        return;
    }
 
    if (replies) {
        while (args = this.queue.shift()) {
            // If we asked for strings, even in detect_buffers mode, then return strings:
            if (replies[i] instanceof Error) {
                var match = replies[i].message.match(utils.errCode);
                // LUA script could return user errors that don't behave like all other errors!
                if (match) {
                    replies[i].code = match[1];
                }
                replies[i].command = args[0].toUpperCase();
            } else if (replies[i]) {
                if (this.wants_buffers[i] === false) {
                    replies[i] = utils.reply_to_strings(replies[i]);
                }
                if (args[0] === 'hgetall') {
                    // TODO - confusing and error-prone that hgetall is special cased in two places
                    replies[i] = utils.reply_to_object(replies[i]);
                }
            }
 
            if (typeof args[args.length - 1] === 'function') {
                if (replies[i] instanceof Error) {
                    args[args.length - 1](replies[i]);
                } else {
                    args[args.length - 1](null, replies[i]);
                }
            }
            i++;
        }
    }
 
    if (this.callback) {
        this.callback(null, replies);
    }
};
 
Multi.prototype.callback = function (cb, i) {
    var self = this;
    return function (err, res) {
        if (err) {
            self.results[i] = err;
        } else {
            self.results[i] = res;
        }
        if (cb) {
            cb(err, res);
        }
        // Do not emit an error here. Otherwise each error would result in one emit.
        // The errors will be returned in the result anyway
    };
};
 
Multi.prototype.exec = Multi.prototype.EXEC = Multi.prototype.exec_batch = function (callback) {
    var len = this.queue.length;
    var self = this;
    var index = 0;
    var args;
    if (len === 0) {
        if (callback) {
            // The execution order won't be obtained in this case
            setImmediate(function () {
                callback(null, []);
            });
        }
        return true;
    }
    this.results = new Array(len);
    this._client.cork(len);
    var lastCallback = function (cb) {
        return function (err, res) {
            cb(err, res);
            callback(null, self.results);
        };
    };
    while (args = this.queue.shift()) {
        var command = args.shift();
        var cb;
        if (typeof args[args.length - 1] === 'function') {
            cb = this.callback(args.pop(), index);
        } else {
            cb = this.callback(undefined, index);
        }
        if (callback && index === len - 1) {
            cb = lastCallback(cb);
        }
        this._client.send_command(command, args, cb);
        index++;
    }
    this._client.uncork();
    this._client.writeDefault = this._client.writeStrings;
    return !this._client.should_buffer;
};
 
var createClient = function (port_arg, host_arg, options) {
    if (typeof port_arg === 'number' || typeof port_arg === 'string' && /^\d+$/.test(port_arg)) {
        options = clone(options);
        options.host = host_arg;
        options.port = port_arg;
    } else if (typeof port_arg === 'string' || port_arg && port_arg.url) {
        options = clone(port_arg.url ? port_arg : host_arg || options);
        var parsed = URL.parse(port_arg.url || port_arg, true, true);
        if (parsed.hostname) {
            if (parsed.auth) {
                options.auth_pass = parsed.auth.split(':')[1];
            }
            if (parsed.protocol !== 'redis:') {
                throw new Error('Connection string must use the "redis:" protocol');
            }
            options.host = parsed.hostname;
            options.port = parsed.port;
        } else {
            options.path = port_arg;
        }
    } else if (typeof port_arg === 'object' || port_arg === undefined) {
        options = clone(port_arg || options);
        options.host = options.host || host_arg;
    }
    if (!options) {
        throw new Error('Unknown type of connection in createClient()');
    }
    return new RedisClient(options);
};
 
exports.createClient = createClient;
exports.RedisClient = RedisClient;
exports.print = utils.print;
exports.Multi = Multi;