diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000000..6d3c020b60 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,10 @@ +{ + "extends": "standard", + "parser": "babel-eslint", + "rules": { + "yoda": 0, + "semi": [2, "always"], + "no-extra-semi": 2, + "semi-spacing": [2, { "before": false, "after": true }] + } +} diff --git a/examples/latency/index.js b/examples/latency/index.js index bcaae71469..2622a1a13f 100644 --- a/examples/latency/index.js +++ b/examples/latency/index.js @@ -3,28 +3,28 @@ * Module dependencies. */ -var express = require('express') - , app = express() - , server = require('http').createServer(app) - , enchilada = require('enchilada') - , io = require('engine.io').attach(server); +var express = require('express'); +var app = express(); +var server = require('http').createServer(app); +var enchilada = require('enchilada'); +var io = require('engine.io').attach(server); app.use(enchilada({ src: __dirname + '/public', debug: true })); app.use(express.static(__dirname + '/public')); -app.get('/', function(req, res, next){ +app.get('/', function (req, res, next) { res.sendfile('index.html'); }); -io.on('connection', function(socket){ - socket.on('message', function(v){ +io.on('connection', function (socket) { + socket.on('message', function (v) { socket.send('pong'); }); }); var port = process.env.PORT || 3000; -server.listen(port, function(){ - console.log('\033[96mlistening on localhost:' + port + ' \033[39m'); +server.listen(port, function () { + console.log('\x1B[96mlistening on localhost:' + port + ' \x1B[39m'); }); diff --git a/examples/latency/public/index.js b/examples/latency/public/index.js index 5251218940..d64f8efd2f 100644 --- a/examples/latency/public/index.js +++ b/examples/latency/public/index.js @@ -3,21 +3,20 @@ * Module dependencies. */ -var SmoothieChart = require("smoothie").SmoothieChart - , TimeSeries = require("smoothie").TimeSeries - , eio = require("engine.io-client"); - +var SmoothieChart = require('smoothie').SmoothieChart; +var TimeSeries = require('smoothie').TimeSeries; +var eio = require('engine.io-client'); // helper -function $(id){ return document.getElementById(id); } +function $ (id) { return document.getElementById(id); } // chart var smoothie; var time; -function render(){ +function render () { if (smoothie) smoothie.stop(); $('chart').width = document.body.clientWidth; smoothie = new SmoothieChart(); @@ -33,25 +32,25 @@ function render(){ // socket var socket = new eio.Socket(); var last; -function send(){ - last = new Date; +function send () { + last = new Date(); socket.send('ping'); $('transport').innerHTML = socket.transport.name; } -socket.on('open', function(){ +socket.on('open', function () { if ($('chart').getContext) { render(); window.onresize = render; } send(); }); -socket.on('close', function(){ +socket.on('close', function () { if (smoothie) smoothie.stop(); $('transport').innerHTML = '(disconnected)'; }); -socket.on('message', function(){ - var latency = new Date - last; +socket.on('message', function () { + var latency = new Date() - last; $('latency').innerHTML = latency + 'ms'; - if (time) time.append(+new Date, latency); + if (time) time.append(+new Date(), latency); setTimeout(send, 100); }); diff --git a/gulpfile.js b/gulpfile.js index 9fb1494383..a81586b034 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,39 +1,52 @@ -var gulp = require('gulp'); -var mocha = require('gulp-mocha'); -var babel = require("gulp-babel"); -var nsp = require('gulp-nsp'); +const gulp = require('gulp'); +const mocha = require('gulp-mocha'); +const babel = require('gulp-babel'); +const nsp = require('gulp-nsp'); +const eslint = require('gulp-eslint'); -var TESTS = 'test/*.js'; -var REPORTER = 'dot'; +const TESTS = 'test/*.js'; +const REPORTER = 'dot'; -gulp.task("default", ["transpile"]); +gulp.task('default', ['transpile']); -gulp.task('test', ['nsp'], function(){ - if (parseInt(process.versions.node) < 4 && process.env.EIO_WS_ENGINE == 'uws') { - console.info("Node version < 4, skipping tests with uws engine"); - process.exit(); - } - return gulp.src(TESTS, {read: false}) +gulp.task('test', ['nsp', 'lint'], function () { + if (parseInt(process.versions.node, 10) < 4 && process.env.EIO_WS_ENGINE === 'uws') { + console.info('Node version < 4, skipping tests with uws engine'); + process.exit(); + } + return gulp.src(TESTS, {read: false}) .pipe(mocha({ slow: 500, reporter: REPORTER, bail: true })) - .once('error', function(){ + .once('error', function (err) { + console.error(err.stack); process.exit(1); }) - .once('end', function(){ + .once('end', function () { process.exit(); }); }); +gulp.task('lint', function () { + return gulp.src([ + '*.js', + 'lib/**/*.js', + 'test/**/*.js' + ]) + .pipe(eslint()) + .pipe(eslint.format()) + .pipe(eslint.failAfterError()); +}); + // By default, individual js files are transformed by babel and exported to /dist -gulp.task("transpile", function(){ - return gulp.src(["lib/*.js","lib/transports/*.js"], { base: 'lib' }) - .pipe(babel({ "presets": ["es2015"] })) - .pipe(gulp.dest("dist")); +gulp.task('transpile', function () { + return gulp.src(['lib/**/*.js'], { base: 'lib' }) + .pipe(babel({ 'presets': ['es2015'] })) + .pipe(gulp.dest('dist')); }); gulp.task('nsp', function (cb) { - nsp({package: __dirname + '/package.json'}, cb) -}) + nsp({package: __dirname + '/package.json'}, cb); +}); diff --git a/lib/engine.io.js b/lib/engine.io.js index dbec1de06e..c97edd615f 100644 --- a/lib/engine.io.js +++ b/lib/engine.io.js @@ -17,7 +17,7 @@ var http = require('http'); * @api public */ -exports = module.exports = function() { +exports = module.exports = function () { // backwards compatible use as `.attach` // if first argument is an http server if (arguments.length && arguments[0] instanceof http.Server) { @@ -88,8 +88,8 @@ exports.parser = require('engine.io-parser'); exports.listen = listen; -function listen(port, options, fn) { - if ('function' == typeof options) { +function listen (port, options, fn) { + if ('function' === typeof options) { fn = options; options = {}; } @@ -106,7 +106,7 @@ function listen(port, options, fn) { engine.httpServer = server; return engine; -}; +} /** * Captures upgrade requests for a http.Server. @@ -119,8 +119,8 @@ function listen(port, options, fn) { exports.attach = attach; -function attach(server, options) { +function attach (server, options) { var engine = new exports.Server(options); engine.attach(server, options); return engine; -}; +} diff --git a/lib/server.js b/lib/server.js index 6af518ec64..45a1370338 100644 --- a/lib/server.js +++ b/lib/server.js @@ -3,15 +3,14 @@ * Module dependencies. */ -var qs = require('querystring') - , parse = require('url').parse - , readFileSync = require('fs').readFileSync - , crypto = require('crypto') - , base64id = require('base64id') - , transports = require('./transports') - , EventEmitter = require('events').EventEmitter - , Socket = require('./socket') - , debug = require('debug')('engine'); +var qs = require('querystring'); +var parse = require('url').parse; +var base64id = require('base64id'); +var transports = require('./transports'); +var EventEmitter = require('events').EventEmitter; +var Socket = require('./socket'); +var util = require('util'); +var debug = require('debug')('engine'); /** * Module exports. @@ -26,7 +25,7 @@ module.exports = Server; * @api public */ -function Server(opts){ +function Server (opts) { if (!(this instanceof Server)) { return new Server(opts); } @@ -60,7 +59,7 @@ function Server(opts){ } // initialize compression options - ['perMessageDeflate', 'httpCompression'].forEach(function(type) { + ['perMessageDeflate', 'httpCompression'].forEach(function (type) { var compression = self[type]; if (true === compression) self[type] = compression = {}; if (compression && null == compression.threshold) { @@ -103,7 +102,7 @@ Server.errorMessages = { * Inherits from EventEmitter. */ -Server.prototype.__proto__ = EventEmitter.prototype; +util.inherits(Server, EventEmitter); /** * Hash of open clients. @@ -120,7 +119,7 @@ Server.prototype.clients; * @api public */ -Server.prototype.upgrades = function(transport){ +Server.prototype.upgrades = function (transport) { if (!this.allowUpgrades) return []; return transports[transport].upgradesTo || []; }; @@ -133,7 +132,7 @@ Server.prototype.upgrades = function(transport){ * @api private */ -Server.prototype.verify = function(req, upgrade, fn){ +Server.prototype.verify = function (req, upgrade, fn) { // transport check var transport = req._query.transport; if (!~this.transports.indexOf(transport)) { @@ -144,15 +143,16 @@ Server.prototype.verify = function(req, upgrade, fn){ // sid check var sid = req._query.sid; if (sid) { - if (!this.clients.hasOwnProperty(sid)) + if (!this.clients.hasOwnProperty(sid)) { return fn(Server.errors.UNKNOWN_SID, false); + } if (!upgrade && this.clients[sid].transport.name !== transport) { debug('bad request: unexpected transport without upgrade'); return fn(Server.errors.BAD_REQUEST, false); } } else { // handshake is GET only - if ('GET' != req.method) return fn(Server.errors.BAD_HANDSHAKE_METHOD, false); + if ('GET' !== req.method) return fn(Server.errors.BAD_HANDSHAKE_METHOD, false); if (!this.allowRequest) return fn(null, true); return this.allowRequest(req, fn); } @@ -166,7 +166,7 @@ Server.prototype.verify = function(req, upgrade, fn){ * @api private */ -Server.prototype.prepare = function(req){ +Server.prototype.prepare = function (req) { // try to leverage pre-existing `req._query` (e.g: from connect) if (!req._query) { req._query = ~req.url.indexOf('?') ? qs.parse(parse(req.url).query) : {}; @@ -179,7 +179,7 @@ Server.prototype.prepare = function(req){ * @api public */ -Server.prototype.close = function(){ +Server.prototype.close = function () { debug('closing all open clients'); for (var i in this.clients) { if (this.clients.hasOwnProperty(i)) { @@ -202,13 +202,13 @@ Server.prototype.close = function(){ * @api public */ -Server.prototype.handleRequest = function(req, res){ +Server.prototype.handleRequest = function (req, res) { debug('handling "%s" http request "%s"', req.method, req.url); this.prepare(req); req.res = res; var self = this; - this.verify(req, false, function(err, success) { + this.verify(req, false, function (err, success) { if (!success) { sendErrorMessage(req, res, err); return; @@ -231,21 +231,21 @@ Server.prototype.handleRequest = function(req, res){ * @api private */ - function sendErrorMessage(req, res, code) { - var headers = { 'Content-Type': 'application/json' }; +function sendErrorMessage (req, res, code) { + var headers = { 'Content-Type': 'application/json' }; - if (req.headers.origin) { - headers['Access-Control-Allow-Credentials'] = 'true'; - headers['Access-Control-Allow-Origin'] = req.headers.origin; - } else { - headers['Access-Control-Allow-Origin'] = '*'; - } - res.writeHead(400, headers); - res.end(JSON.stringify({ - code: code, - message: Server.errorMessages[code] - })); - } + if (req.headers.origin) { + headers['Access-Control-Allow-Credentials'] = 'true'; + headers['Access-Control-Allow-Origin'] = req.headers.origin; + } else { + headers['Access-Control-Allow-Origin'] = '*'; + } + res.writeHead(400, headers); + res.end(JSON.stringify({ + code: code, + message: Server.errorMessages[code] + })); +} /** * generate a socket id. @@ -255,7 +255,7 @@ Server.prototype.handleRequest = function(req, res){ * @api public */ -Server.prototype.generateId = function(req){ +Server.prototype.generateId = function (req) { return base64id.generateId(); }; @@ -267,17 +267,17 @@ Server.prototype.generateId = function(req){ * @api private */ -Server.prototype.handshake = function(transportName, req){ +Server.prototype.handshake = function (transportName, req) { var id = this.generateId(req); debug('handshaking client "%s"', id); try { var transport = new transports[transportName](req); - if ('polling' == transportName) { + if ('polling' === transportName) { transport.maxHttpBufferSize = this.maxHttpBufferSize; transport.httpCompression = this.httpCompression; - } else if ('websocket' == transportName) { + } else if ('websocket' === transportName) { transport.perMessageDeflate = this.perMessageDeflate; } @@ -286,8 +286,7 @@ Server.prototype.handshake = function(transportName, req){ } else { transport.supportsBinary = true; } - } - catch (e) { + } catch (e) { sendErrorMessage(req, req.res, Server.errors.BAD_REQUEST); return; } @@ -295,9 +294,9 @@ Server.prototype.handshake = function(transportName, req){ var self = this; if (false !== this.cookie) { - transport.on('headers', function(headers){ + transport.on('headers', function (headers) { var cookie = self.cookie + '=' + id; - if(false !== self.cookiePath) { + if (false !== self.cookiePath) { cookie += '; path=' + self.cookiePath; } headers['Set-Cookie'] = cookie; @@ -309,7 +308,7 @@ Server.prototype.handshake = function(transportName, req){ this.clients[id] = socket; this.clientsCount++; - socket.once('close', function(){ + socket.once('close', function () { delete self.clients[id]; self.clientsCount--; }); @@ -323,12 +322,12 @@ Server.prototype.handshake = function(transportName, req){ * @api public */ -Server.prototype.handleUpgrade = function(req, socket, upgradeHead){ +Server.prototype.handleUpgrade = function (req, socket, upgradeHead) { this.prepare(req); var self = this; - this.verify(req, true, function(err, success) { - if (!success) { + this.verify(req, true, function (err, success) { + if (err) { socket.end(); return; } @@ -338,7 +337,7 @@ Server.prototype.handleUpgrade = function(req, socket, upgradeHead){ upgradeHead = null; // delegate to ws - self.ws.handleUpgrade(req, socket, head, function(conn){ + self.ws.handleUpgrade(req, socket, head, function (conn) { self.onWebSocket(req, conn); }); }); @@ -351,7 +350,7 @@ Server.prototype.handleUpgrade = function(req, socket, upgradeHead){ * @api private */ -Server.prototype.onWebSocket = function(req, socket){ +Server.prototype.onWebSocket = function (req, socket) { socket.on('error', onUpgradeError); if (!transports[req._query.transport].prototype.handlesUpgrades) { @@ -399,7 +398,7 @@ Server.prototype.onWebSocket = function(req, socket){ this.handshake(req._query.transport, req); } - function onUpgradeError(){ + function onUpgradeError () { debug('websocket error before upgrade'); // socket.close() not needed } @@ -413,19 +412,18 @@ Server.prototype.onWebSocket = function(req, socket){ * @api public */ -Server.prototype.attach = function(server, options){ +Server.prototype.attach = function (server, options) { var self = this; - var options = options || {}; + options = options || {}; var path = (options.path || '/engine.io').replace(/\/$/, ''); - var destroyUpgrade = (options.destroyUpgrade !== undefined) ? options.destroyUpgrade : true; var destroyUpgradeTimeout = options.destroyUpgradeTimeout || 1000; // normalize path path += '/'; function check (req) { - return path == req.url.substr(0, path.length); + return path === req.url.substr(0, path.length); } // cache and clean up listeners @@ -434,7 +432,7 @@ Server.prototype.attach = function(server, options){ server.on('close', self.close.bind(self)); // add request handler - server.on('request', function(req, res){ + server.on('request', function (req, res) { if (check(req)) { debug('intercepting request for path "%s"', path); self.handleRequest(req, res); @@ -445,7 +443,7 @@ Server.prototype.attach = function(server, options){ } }); - if(~self.transports.indexOf('websocket')) { + if (~self.transports.indexOf('websocket')) { server.on('upgrade', function (req, socket, head) { if (check(req)) { self.handleUpgrade(req, socket, head); @@ -454,11 +452,11 @@ Server.prototype.attach = function(server, options){ // but by adding a handler, we prevent that // and if no eio thing handles the upgrade // then the socket needs to die! - setTimeout(function() { - if (socket.writable && socket.bytesWritten <= 0) { - return socket.end(); - } - }, options.destroyUpgradeTimeout); + setTimeout(function () { + if (socket.writable && socket.bytesWritten <= 0) { + return socket.end(); + } + }, destroyUpgradeTimeout); } }); } diff --git a/lib/socket.js b/lib/socket.js index 57838f6159..be97d3d352 100644 --- a/lib/socket.js +++ b/lib/socket.js @@ -3,6 +3,7 @@ */ var EventEmitter = require('events').EventEmitter; +var util = require('util'); var debug = require('debug')('engine:socket'); /** @@ -44,7 +45,7 @@ function Socket (id, server, transport, req) { * Inherits from EventEmitter. */ -Socket.prototype.__proto__ = EventEmitter.prototype; +util.inherits(Socket, EventEmitter); /** * Called upon transport considered open. @@ -58,10 +59,10 @@ Socket.prototype.onOpen = function () { // sends an `open` packet this.transport.sid = this.id; this.sendPacket('open', JSON.stringify({ - sid: this.id - , upgrades: this.getAvailableUpgrades() - , pingInterval: this.server.pingInterval - , pingTimeout: this.server.pingTimeout + sid: this.id, + upgrades: this.getAvailableUpgrades(), + pingInterval: this.server.pingInterval, + pingTimeout: this.server.pingTimeout })); this.emit('open'); @@ -76,7 +77,7 @@ Socket.prototype.onOpen = function () { */ Socket.prototype.onPacket = function (packet) { - if ('open' == this.readyState) { + if ('open' === this.readyState) { // export packet event debug('packet'); this.emit('packet', packet); @@ -151,10 +152,10 @@ Socket.prototype.setTransport = function (transport) { this.transport.on('packet', onPacket); this.transport.on('drain', flush); this.transport.once('close', onClose); - //this function will manage packet events (also message callbacks) + // this function will manage packet events (also message callbacks) this.setupSendCallback(); - this.cleanupFn.push(function() { + this.cleanupFn.push(function () { transport.removeListener('error', onError); transport.removeListener('packet', onPacket); transport.removeListener('drain', flush); @@ -181,18 +182,18 @@ Socket.prototype.maybeUpgrade = function (transport) { self.upgradeTimeoutTimer = setTimeout(function () { debug('client did not complete upgrade - closing transport'); cleanup(); - if ('open' == transport.readyState) { + if ('open' === transport.readyState) { transport.close(); } }, this.server.upgradeTimeout); - function onPacket(packet){ - if ('ping' == packet.type && 'probe' == packet.data) { + function onPacket (packet) { + if ('ping' === packet.type && 'probe' === packet.data) { transport.send([{ type: 'pong', data: 'probe' }]); self.emit('upgrading', transport); clearInterval(self.checkIntervalTimer); self.checkIntervalTimer = setInterval(check, 100); - } else if ('upgrade' == packet.type && self.readyState != 'closed') { + } else if ('upgrade' === packet.type && self.readyState !== 'closed') { debug('got upgrade packet - upgrading'); cleanup(); self.transport.discard(); @@ -202,7 +203,7 @@ Socket.prototype.maybeUpgrade = function (transport) { self.emit('upgrade', transport); self.setPingTimeout(); self.flush(); - if (self.readyState == 'closing') { + if (self.readyState === 'closing') { transport.close(function () { self.onClose('forced close'); }); @@ -214,14 +215,14 @@ Socket.prototype.maybeUpgrade = function (transport) { } // we force a polling cycle to ensure a fast upgrade - function check(){ - if ('polling' == self.transport.name && self.transport.writable) { + function check () { + if ('polling' === self.transport.name && self.transport.writable) { debug('writing a noop packet to polling for fast upgrade'); self.transport.send([{ type: 'noop' }]); } } - function cleanup() { + function cleanup () { self.upgrading = false; clearInterval(self.checkIntervalTimer); @@ -236,19 +237,19 @@ Socket.prototype.maybeUpgrade = function (transport) { self.removeListener('close', onClose); } - function onError(err) { + function onError (err) { debug('client did not complete upgrade - %s', err); cleanup(); transport.close(); transport = null; } - function onTransportClose(){ - onError("transport closed"); + function onTransportClose () { + onError('transport closed'); } - function onClose() { - onError("socket closed"); + function onClose () { + onError('socket closed'); } transport.on('packet', onPacket); @@ -266,10 +267,16 @@ Socket.prototype.maybeUpgrade = function (transport) { Socket.prototype.clearTransport = function () { var cleanup; - while (cleanup = this.cleanupFn.shift()) cleanup(); + + var toCleanUp = this.cleanupFn.length; + + for (var i = 0; i < toCleanUp; i++) { + cleanup = this.cleanupFn.shift(); + cleanup(); + } // silence further transport errors and prevent uncaught exceptions - this.transport.on('error', function(){ + this.transport.on('error', function () { debug('error triggered by discarded transport'); }); @@ -286,7 +293,7 @@ Socket.prototype.clearTransport = function () { */ Socket.prototype.onClose = function (reason, description) { - if ('closed' != this.readyState) { + if ('closed' !== this.readyState) { this.readyState = 'closed'; clearTimeout(this.pingTimeoutTimer); clearInterval(this.checkIntervalTimer); @@ -295,7 +302,7 @@ Socket.prototype.onClose = function (reason, description) { var self = this; // clean writeBuffer in next tick, so developers can still // grab the writeBuffer on 'close' event - process.nextTick(function() { + process.nextTick(function () { self.writeBuffer = []; }); this.packetsFn = []; @@ -315,21 +322,21 @@ Socket.prototype.setupSendCallback = function () { var self = this; this.transport.on('drain', onDrain); - this.cleanupFn.push(function() { + this.cleanupFn.push(function () { self.transport.removeListener('drain', onDrain); }); - //the message was sent successfully, execute the callback - function onDrain() { + // the message was sent successfully, execute the callback + function onDrain () { if (self.sentCallbackFn.length > 0) { - var seqFn = self.sentCallbackFn.splice(0,1)[0]; - if ('function' == typeof seqFn) { + var seqFn = self.sentCallbackFn.splice(0, 1)[0]; + if ('function' === typeof seqFn) { debug('executing send callback'); seqFn(self.transport); } else if (Array.isArray(seqFn)) { debug('executing batch send callback'); for (var l = seqFn.length, i = 0; i < l; i++) { - if ('function' == typeof seqFn[i]) { + if ('function' === typeof seqFn[i]) { seqFn[i](self.transport); } } @@ -349,7 +356,7 @@ Socket.prototype.setupSendCallback = function () { */ Socket.prototype.send = -Socket.prototype.write = function(data, options, callback){ +Socket.prototype.write = function (data, options, callback) { this.sendPacket('message', data, options, callback); return this; }; @@ -364,7 +371,7 @@ Socket.prototype.write = function(data, options, callback){ */ Socket.prototype.sendPacket = function (type, data, options, callback) { - if ('function' == typeof options) { + if ('function' === typeof options) { callback = options; options = null; } @@ -372,7 +379,7 @@ Socket.prototype.sendPacket = function (type, data, options, callback) { options = options || {}; options.compress = false !== options.compress; - if ('closing' != this.readyState) { + if ('closing' !== this.readyState) { debug('sending packet "%s" (%s)', type, data); var packet = { @@ -386,7 +393,7 @@ Socket.prototype.sendPacket = function (type, data, options, callback) { this.writeBuffer.push(packet); - //add send callback to object + // add send callback to object this.packetsFn.push(callback); this.flush(); @@ -400,8 +407,9 @@ Socket.prototype.sendPacket = function (type, data, options, callback) { */ Socket.prototype.flush = function () { - if ('closed' != this.readyState && this.transport.writable - && this.writeBuffer.length) { + if ('closed' !== this.readyState && + this.transport.writable && + this.writeBuffer.length) { debug('flushing buffer to transport'); this.emit('flush', this.writeBuffer); this.server.emit('flush', this, this.writeBuffer); @@ -430,7 +438,7 @@ Socket.prototype.getAvailableUpgrades = function () { var allUpgrades = this.server.upgrades(this.transport.name); for (var i = 0, l = allUpgrades.length; i < l; ++i) { var upg = allUpgrades[i]; - if (this.server.transports.indexOf(upg) != -1) { + if (this.server.transports.indexOf(upg) !== -1) { availableUpgrades.push(upg); } } @@ -446,7 +454,7 @@ Socket.prototype.getAvailableUpgrades = function () { */ Socket.prototype.close = function (discard) { - if ('open' != this.readyState) return; + if ('open' !== this.readyState) return; this.readyState = 'closing'; diff --git a/lib/transport.js b/lib/transport.js index fdd65db708..0da2716ded 100644 --- a/lib/transport.js +++ b/lib/transport.js @@ -3,9 +3,10 @@ * Module dependencies. */ -var EventEmitter = require('events').EventEmitter - , parser = require('engine.io-parser') - , debug = require('debug')('engine:transport'); +var EventEmitter = require('events').EventEmitter; +var parser = require('engine.io-parser'); +var util = require('util'); +var debug = require('debug')('engine:transport'); /** * Expose the constructor. @@ -37,7 +38,7 @@ function Transport (req) { * Inherits from EventEmitter. */ -Transport.prototype.__proto__ = EventEmitter.prototype; +util.inherits(Transport, EventEmitter); /** * Flags the transport as discarded. @@ -68,7 +69,7 @@ Transport.prototype.onRequest = function (req) { */ Transport.prototype.close = function (fn) { - if ('closed' == this.readyState || 'closing' == this.readyState) return; + if ('closed' === this.readyState || 'closing' === this.readyState) return; this.readyState = 'closing'; this.doClose(fn || noop); diff --git a/lib/transports/index.js b/lib/transports/index.js index e15cb78387..fcff3223a8 100644 --- a/lib/transports/index.js +++ b/lib/transports/index.js @@ -28,7 +28,7 @@ exports.polling.upgradesTo = ['websocket']; */ function polling (req) { - if ('string' == typeof req._query.j) { + if ('string' === typeof req._query.j) { return new JSONP(req); } else { return new XHR(req); diff --git a/lib/transports/polling-jsonp.js b/lib/transports/polling-jsonp.js index fe9fae61fb..62e66e779c 100644 --- a/lib/transports/polling-jsonp.js +++ b/lib/transports/polling-jsonp.js @@ -7,6 +7,7 @@ var Polling = require('./polling'); var qs = require('querystring'); var rDoubleSlashes = /\\\\n/g; var rSlashes = /(\\)?\\n/g; +var util = require('util'); /** * Module exports. @@ -25,13 +26,13 @@ function JSONP (req) { this.head = '___eio[' + (req._query.j || '').replace(/[^0-9]/g, '') + ']('; this.foot = ');'; -}; +} /** * Inherits from Polling. */ -JSONP.prototype.__proto__ = Polling.prototype; +util.inherits(JSONP, Polling); /** * Handles incoming data. @@ -44,10 +45,10 @@ JSONP.prototype.onData = function (data) { // we leverage the qs module so that we get built-in DoS protection // and the fast alternative to decodeURIComponent data = qs.parse(data).d; - if ('string' == typeof data) { - //client will send already escaped newlines as \\\\n and newlines as \\n + if ('string' === typeof data) { + // client will send already escaped newlines as \\\\n and newlines as \\n // \\n must be replaced with \n and \\\\n with \\n - data = data.replace(rSlashes, function(match, slashes) { + data = data.replace(rSlashes, function (match, slashes) { return slashes ? match : '\n'; }); Polling.prototype.onData.call(this, data.replace(rDoubleSlashes, '\\n')); diff --git a/lib/transports/polling-xhr.js b/lib/transports/polling-xhr.js index d2f2136031..d745846928 100644 --- a/lib/transports/polling-xhr.js +++ b/lib/transports/polling-xhr.js @@ -4,8 +4,7 @@ */ var Polling = require('./polling'); -var Transport = require('../transport'); -var debug = require('debug')('engine:polling-xhr'); +var util = require('util'); /** * Module exports. @@ -19,7 +18,7 @@ module.exports = XHR; * @api public */ -function XHR(req){ +function XHR (req) { Polling.call(this, req); } @@ -27,7 +26,7 @@ function XHR(req){ * Inherits from Polling. */ -XHR.prototype.__proto__ = Polling.prototype; +util.inherits(XHR, Polling); /** * Overrides `onRequest` to handle `OPTIONS`.. @@ -37,7 +36,7 @@ XHR.prototype.__proto__ = Polling.prototype; */ XHR.prototype.onRequest = function (req) { - if ('OPTIONS' == req.method) { + if ('OPTIONS' === req.method) { var res = req.res; var headers = this.headers(req); headers['Access-Control-Allow-Headers'] = 'Content-Type'; @@ -56,7 +55,7 @@ XHR.prototype.onRequest = function (req) { * @api private */ -XHR.prototype.headers = function(req, headers){ +XHR.prototype.headers = function (req, headers) { headers = headers || {}; if (req.headers.origin) { diff --git a/lib/transports/polling.js b/lib/transports/polling.js index 36b9222e6b..17e84a54fa 100644 --- a/lib/transports/polling.js +++ b/lib/transports/polling.js @@ -3,11 +3,12 @@ * Module requirements. */ -var Transport = require('../transport') - , parser = require('engine.io-parser') - , zlib = require('zlib') - , accepts = require('accepts') - , debug = require('debug')('engine:polling'); +var Transport = require('../transport'); +var parser = require('engine.io-parser'); +var zlib = require('zlib'); +var accepts = require('accepts'); +var util = require('util'); +var debug = require('debug')('engine:polling'); var compressionMethods = { gzip: zlib.createGzip, @@ -40,7 +41,7 @@ function Polling (req) { * @api public. */ -Polling.prototype.__proto__ = Transport.prototype; +util.inherits(Polling, Transport); /** * Transport name @@ -60,9 +61,9 @@ Polling.prototype.name = 'polling'; Polling.prototype.onRequest = function (req) { var res = req.res; - if ('GET' == req.method) { + if ('GET' === req.method) { this.onPollRequest(req, res); - } else if ('POST' == req.method) { + } else if ('POST' === req.method) { this.onDataRequest(req, res); } else { res.writeHead(500); @@ -130,7 +131,7 @@ Polling.prototype.onDataRequest = function (req, res) { return; } - var isBinary = 'application/octet-stream' == req.headers['content-type']; + var isBinary = 'application/octet-stream' === req.headers['content-type']; this.dataReq = req; this.dataRes = res; @@ -153,7 +154,7 @@ Polling.prototype.onDataRequest = function (req, res) { function onData (data) { var contentLength; - if (typeof data == 'string') { + if (typeof data === 'string') { chunks += data; contentLength = Buffer.byteLength(chunks); } else { @@ -198,8 +199,8 @@ Polling.prototype.onDataRequest = function (req, res) { Polling.prototype.onData = function (data) { debug('received "%s"', data); var self = this; - var callback = function(packet) { - if ('close' == packet.type) { + var callback = function (packet) { + if ('close' === packet.type) { debug('got xhr close packet'); self.onClose(); return false; @@ -243,8 +244,8 @@ Polling.prototype.send = function (packets) { } var self = this; - parser.encodePayload(packets, this.supportsBinary, function(data) { - var compress = packets.some(function(packet) { + parser.encodePayload(packets, this.supportsBinary, function (data) { + var compress = packets.some(function (packet) { return packet.options && packet.options.compress; }); self.write(data, { compress: compress }); @@ -262,7 +263,7 @@ Polling.prototype.send = function (packets) { Polling.prototype.write = function (data, options) { debug('writing "%s"', data); var self = this; - this.doWrite(data, options, function() { + this.doWrite(data, options, function () { self.req.cleanup(); }); }; @@ -277,7 +278,7 @@ Polling.prototype.doWrite = function (data, options, callback) { var self = this; // explicit UTF-8 is required for pages not served under utf - var isString = typeof data == 'string'; + var isString = typeof data === 'string'; var contentType = isString ? 'text/plain; charset=UTF-8' : 'application/octet-stream'; @@ -303,7 +304,7 @@ Polling.prototype.doWrite = function (data, options, callback) { return; } - this.compress(data, encoding, function(err, data) { + this.compress(data, encoding, function (err, data) { if (err) { self.res.writeHead(500); self.res.end(); @@ -315,8 +316,8 @@ Polling.prototype.doWrite = function (data, options, callback) { respond(data); }); - function respond(data) { - headers['Content-Length'] = 'string' == typeof data ? Buffer.byteLength(data) : data.length; + function respond (data) { + headers['Content-Length'] = 'string' === typeof data ? Buffer.byteLength(data) : data.length; self.res.writeHead(200, self.headers(self.req, headers)); self.res.end(data); callback(); @@ -337,11 +338,11 @@ Polling.prototype.compress = function (data, encoding, callback) { compressionMethods[encoding](this.httpCompression) .on('error', callback) - .on('data', function(chunk) { + .on('data', function (chunk) { buffers.push(chunk); nread += chunk.length; }) - .on('end', function() { + .on('end', function () { callback(null, Buffer.concat(buffers, nread)); }) .end(data); @@ -377,7 +378,7 @@ Polling.prototype.doClose = function (fn) { closeTimeoutTimer = setTimeout(onClose, this.closeTimeout); } - function onClose() { + function onClose () { clearTimeout(closeTimeoutTimer); fn(); self.onClose(); diff --git a/lib/transports/websocket.js b/lib/transports/websocket.js index 5a16f210c0..330fd4e384 100644 --- a/lib/transports/websocket.js +++ b/lib/transports/websocket.js @@ -3,9 +3,10 @@ * Module dependencies. */ -var Transport = require('../transport') - , parser = require('engine.io-parser') - , debug = require('debug')('engine:ws') +var Transport = require('../transport'); +var parser = require('engine.io-parser'); +var util = require('util'); +var debug = require('debug')('engine:ws'); /** * Export the constructor. @@ -14,7 +15,7 @@ var Transport = require('../transport') module.exports = WebSocket; /** - * WebSocket transport + * WebSocket transport * * @param {http.ServerRequest} * @api public @@ -32,13 +33,13 @@ function WebSocket (req) { }); this.writable = true; this.perMessageDeflate = null; -}; +} /** * Inherits from Transport. */ -WebSocket.prototype.__proto__ = Transport.prototype; +util.inherits(WebSocket, Transport); /** * Transport name @@ -85,8 +86,8 @@ WebSocket.prototype.onData = function (data) { WebSocket.prototype.send = function (packets) { var self = this; - packets.forEach(function(packet) { - parser.encodePacket(packet, self.supportsBinary, function(data) { + packets.forEach(function (packet) { + parser.encodePacket(packet, self.supportsBinary, function (data) { debug('writing "%s"', data); // always creates a new object since ws modifies it @@ -96,14 +97,14 @@ WebSocket.prototype.send = function (packets) { } if (self.perMessageDeflate) { - var len = 'string' == typeof data ? Buffer.byteLength(data) : data.length; + var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length; if (len < self.perMessageDeflate.threshold) { opts.compress = false; } } self.writable = false; - self.socket.send(data, opts, function (err){ + self.socket.send(data, opts, function (err) { if (err) return self.onError('write error', err.stack); self.writable = true; self.emit('drain'); diff --git a/package.json b/package.json index 307bc4adfc..a3ed3ca662 100644 --- a/package.json +++ b/package.json @@ -32,11 +32,15 @@ "ws": "1.1.1" }, "devDependencies": { + "babel-eslint": "5.0.0", "babel-preset-es2015": "6.3.13", "engine.io-client": "1.7.2", + "eslint-config-standard": "4.4.0", + "eslint-plugin-standard": "1.3.2", "expect.js": "0.2.0", "gulp": "3.9.0", "gulp-babel": "6.1.1", + "gulp-eslint": "1.1.1", "gulp-mocha": "2.2.0", "gulp-nsp": "^2.4.1", "mocha": "2.3.4", diff --git a/test/.eslintrc.json b/test/.eslintrc.json new file mode 100644 index 0000000000..7eeefc33b6 --- /dev/null +++ b/test/.eslintrc.json @@ -0,0 +1,5 @@ +{ + "env": { + "mocha": true + } +} diff --git a/test/common.js b/test/common.js index 1359f67d51..f5bdc0321f 100644 --- a/test/common.js +++ b/test/common.js @@ -10,7 +10,7 @@ var eio = require('..'); */ exports.listen = function (opts, fn) { - if ('function' == typeof opts) { + if ('function' === typeof opts) { fn = opts; opts = {}; } diff --git a/test/engine.io.js b/test/engine.io.js index c171adf34f..4850c5204e 100644 --- a/test/engine.io.js +++ b/test/engine.io.js @@ -15,12 +15,11 @@ var http = require('http'); */ describe('engine', function () { - it('should expose protocol number', function () { expect(eio.protocol).to.be.a('number'); }); - it('should be the same version as client', function(){ + it('should be the same version as client', function () { expect(eio.protocol).to.be.a('number'); var version = require('../package').version; expect(version).to.be(require('engine.io-client/package').version); @@ -35,7 +34,7 @@ describe('engine', function () { describe('listen', function () { it('should open a http server that returns 501', function (done) { - var server = listen(function (port) { + listen(function (port) { request.get('http://localhost:%d/'.s(port), function (res) { expect(res.status).to.be(501); done(); @@ -53,15 +52,15 @@ describe('engine', function () { }); it('should return an engine.Server', function () { - var server = http.createServer() - , engine = eio.attach(server); + var server = http.createServer(); + var engine = eio.attach(server); expect(engine).to.be.an(eio.Server); }); it('should attach engine to an http server', function (done) { - var server = http.createServer() - , engine = eio.attach(server); + var server = http.createServer(); + eio.attach(server); server.listen(function () { var uri = 'http://localhost:%d/engine.io/default/'.s(server.address().port); @@ -76,22 +75,22 @@ describe('engine', function () { }); it('should destroy upgrades not handled by engine', function (done) { - var server = http.createServer() - , engine = eio.attach(server); + var server = http.createServer(); + eio.attach(server, { destroyUpgradeTimeout: 50 }); server.listen(function () { var client = net.createConnection(server.address().port); client.setEncoding('ascii'); client.write([ - 'GET / HTTP/1.1' - , 'Connection: Upgrade' - , 'Upgrade: IRC/6.9' - , '', '' + 'GET / HTTP/1.1', + 'Connection: Upgrade', + 'Upgrade: IRC/6.9', + '', '' ].join('\r\n')); var check = setTimeout(function () { done(new Error('Client should have ended')); - }, 20); + }, 100); client.on('end', function () { clearTimeout(check); @@ -101,21 +100,21 @@ describe('engine', function () { }); it('should not destroy unhandled upgrades with destroyUpgrade:false', function (done) { - var server = http.createServer() - , engine = eio.attach(server, { destroyUpgrade: false, destroyUpgradeTimeout: 50 }); + var server = http.createServer(); + eio.attach(server, { destroyUpgrade: false, destroyUpgradeTimeout: 50 }); server.listen(function () { var client = net.createConnection(server.address().port); client.on('connect', function () { client.setEncoding('ascii'); client.write([ - 'GET / HTTP/1.1' - , 'Connection: Upgrade' - , 'Upgrade: IRC/6.9' - , '', '' + 'GET / HTTP/1.1', + 'Connection: Upgrade', + 'Upgrade: IRC/6.9', + '', '' ].join('\r\n')); - var check = setTimeout(function () { + setTimeout(function () { client.removeListener('end', onEnd); done(); }, 100); @@ -130,24 +129,24 @@ describe('engine', function () { }); it('should destroy unhandled upgrades with after a timeout', function (done) { - var server = http.createServer() - , engine = eio.attach(server, { destroyUpgradeTimeout: 200 }); + var server = http.createServer(); + eio.attach(server, { destroyUpgradeTimeout: 200 }); server.listen(function () { var client = net.createConnection(server.address().port); client.on('connect', function () { client.setEncoding('ascii'); client.write([ - 'GET / HTTP/1.1' - , 'Connection: Upgrade' - , 'Upgrade: IRC/6.9' - , '', '' + 'GET / HTTP/1.1', + 'Connection: Upgrade', + 'Upgrade: IRC/6.9', + '', '' ].join('\r\n')); // send from client to server // tests that socket is still alive // this will not keep the socket open as the server does not handle it - setTimeout(function() { + setTimeout(function () { client.write('foo'); }, 100); @@ -161,13 +160,13 @@ describe('engine', function () { }); it('should not destroy handled upgrades with after a timeout', function (done) { - var server = http.createServer() - , engine = eio.attach(server, { destroyUpgradeTimeout: 100 }); + var server = http.createServer(); + eio.attach(server, { destroyUpgradeTimeout: 100 }); // write to the socket to keep engine.io from closing it by writing before the timeout - server.on('upgrade', function(req, socket) { + server.on('upgrade', function (req, socket) { socket.write('foo'); - socket.on('data', function(chunk) { + socket.on('data', function (chunk) { expect(chunk.toString()).to.be('foo'); socket.end(); }); @@ -179,14 +178,14 @@ describe('engine', function () { client.on('connect', function () { client.setEncoding('ascii'); client.write([ - 'GET / HTTP/1.1' - , 'Connection: Upgrade' - , 'Upgrade: IRC/6.9' - , '', '' + 'GET / HTTP/1.1', + 'Connection: Upgrade', + 'Upgrade: IRC/6.9', + '', '' ].join('\r\n')); // test that socket is still open by writing after the timeout period - setTimeout(function() { + setTimeout(function () { client.write('foo'); }, 200); @@ -199,11 +198,11 @@ describe('engine', function () { }); it('should preserve original request listeners', function (done) { - var listeners = 0 - , server = http.createServer(function (req, res) { - expect(req && res).to.be.ok(); - listeners++; - }); + var listeners = 0; + var server = http.createServer(function (req, res) { + expect(req && res).to.be.ok(); + listeners++; + }); server.on('request', function (req, res) { expect(req && res).to.be.ok(); @@ -230,5 +229,4 @@ describe('engine', function () { }); }); }); - }); diff --git a/test/fixtures/server-close-upgraded.js b/test/fixtures/server-close-upgraded.js index 69ff0ee2a7..dc608d30bf 100644 --- a/test/fixtures/server-close-upgraded.js +++ b/test/fixtures/server-close-upgraded.js @@ -3,7 +3,7 @@ var listen = require('../common').listen; var engine = listen(function (port) { var socket = new eioc.Socket('ws://localhost:' + port); - socket.on('upgrade', function() { + socket.on('upgrade', function () { engine.httpServer.close(); engine.close(); }); diff --git a/test/fixtures/server-close-upgrading.js b/test/fixtures/server-close-upgrading.js index 581a1ea6e2..4ebfcc52be 100644 --- a/test/fixtures/server-close-upgrading.js +++ b/test/fixtures/server-close-upgrading.js @@ -3,7 +3,7 @@ var listen = require('../common').listen; var engine = listen(function (port) { var socket = new eioc.Socket('ws://localhost:' + port); - socket.on('upgrading', function() { + socket.on('upgrading', function () { engine.httpServer.close(); engine.close(); }); diff --git a/test/fixtures/server-close.js b/test/fixtures/server-close.js index 259a3f45db..07c3120943 100644 --- a/test/fixtures/server-close.js +++ b/test/fixtures/server-close.js @@ -3,7 +3,7 @@ var listen = require('../common').listen; var engine = listen(function (port) { var socket = new eioc.Socket('ws://localhost:' + port); - socket.on('open', function() { + socket.on('open', function () { engine.httpServer.close(); engine.close(); }); diff --git a/test/jsonp.js b/test/jsonp.js index 934d1ff427..b0ca0d973d 100644 --- a/test/jsonp.js +++ b/test/jsonp.js @@ -3,27 +3,25 @@ * Module dependencies. */ -var http = require('http'); var eioc = require('engine.io-client'); var listen = require('./common').listen; var expect = require('expect.js'); var request = require('superagent'); -var WebSocket = require('ws'); describe('JSONP', function () { before(function () { // we have to override the browser's functionality for JSONP - document = { + document = { // eslint-disable-line no-native-reassign, no-undef body: { - appendChild: function(){}, - removeChild: function(){} + appendChild: function () {}, + removeChild: function () {} } }; document.createElement = function (name) { var self = this; - if('script' == name) { + if ('script' === name) { var script = {}; script.__defineGetter__('parentNode', function () { @@ -31,39 +29,39 @@ describe('JSONP', function () { }); script.__defineSetter__('src', function (uri) { - request.get(uri).end(function(res) { - eval(res.text); + request.get(uri).end(function (res) { + eval(res.text); // eslint-disable-line no-eval }); }); return script; - } else if ('form' == name) { + } else if ('form' === name) { var form = { style: {}, action: '', - parentNode: { removeChild: function(){} }, - removeChild: function(){}, - setAttribute: function(){}, - appendChild: function(){}, - submit: function(){ + parentNode: { removeChild: function () {} }, + removeChild: function () {}, + setAttribute: function () {}, + appendChild: function () {}, + submit: function () { request .post(this.action) .type('form') .send({ d: self.areaValue }) - .end(function(){}); + .end(function () {}); } }; return form; - } else if ('textarea' == name) { + } else if ('textarea' === name) { var textarea = {}; - //a hack to be able to access the area data when form is sent + // a hack to be able to access the area data when form is sent textarea.__defineSetter__('value', function (data) { self.areaValue = data; }); return textarea; } else if (~name.indexOf('iframe')) { var iframe = {}; - setTimeout(function() { + setTimeout(function () { if (iframe.onload) iframe.onload(); }, 0); @@ -71,28 +69,28 @@ describe('JSONP', function () { } else { return {}; } - } + }; document.getElementsByTagName = function (name) { return [{ parentNode: { insertBefore: function () {} } - }] - } + }]; + }; }); after(function () { - delete document.getElementsByTagName - , document.createElement; + delete document.getElementsByTagName; + delete document.createElement; delete global.document; }); describe('handshake', function () { it('should open with polling JSONP when requested', function (done) { - var engine = listen( { allowUpgrades: false, transports: ['polling'] }, function (port) { - var socket = new eioc.Socket('ws://localhost:' + port - , { transports: ['polling'], forceJSONP: true, upgrade: false }); + var engine = listen({ allowUpgrades: false, transports: ['polling'] }, function (port) { + eioc('ws://localhost:' + port, + { transports: ['polling'], forceJSONP: true, upgrade: false }); engine.on('connection', function (socket) { expect(socket.transport.name).to.be('polling'); expect(socket.transport.head).to.be('___eio[0]('); @@ -105,8 +103,8 @@ describe('JSONP', function () { describe('messages', function () { var engine, port, socket; - beforeEach(function(done) { - engine = listen( { allowUpgrades: false, transports: ['polling'] }, function (p) { + beforeEach(function (done) { + engine = listen({ allowUpgrades: false, transports: ['polling'] }, function (p) { port = p; socket = new eioc.Socket('ws://localhost:' + port @@ -134,20 +132,20 @@ describe('JSONP', function () { }); it('should not fail JSON.parse for stringified messages', function (done) { - engine.on('connection', function(conn) { - conn.on('message', function(message) { - expect(JSON.parse(message)).to.be.eql({test : 'a\r\nb\n\n\n\nc'}); + engine.on('connection', function (conn) { + conn.on('message', function (message) { + expect(JSON.parse(message)).to.be.eql({test: 'a\r\nb\n\n\n\nc'}); done(); }); }); socket.on('open', function () { - socket.send(JSON.stringify({test : 'a\r\nb\n\n\n\nc'})); + socket.send(JSON.stringify({test: 'a\r\nb\n\n\n\nc'})); }); }); it('should parse newlines in message correctly', function (done) { - engine.on('connection', function(conn) { - conn.on('message', function(message) { + engine.on('connection', function (conn) { + conn.on('message', function (message) { expect(message).to.be.equal('a\r\nb\n\n\n\nc'); done(); }); @@ -157,7 +155,7 @@ describe('JSONP', function () { }); }); - it('should arrive from server to client and back with binary data (pollingJSONP)', function(done) { + it('should arrive from server to client and back with binary data (pollingJSONP)', function (done) { var binaryData = new Buffer(5); for (var i = 0; i < 5; i++) binaryData[i] = i; engine.on('connection', function (conn) { @@ -166,7 +164,7 @@ describe('JSONP', function () { }); }); - socket.on('open', function() { + socket.on('open', function () { socket.send(binaryData); socket.on('message', function (msg) { for (var i = 0; i < msg.length; i++) expect(msg[i]).to.be(i); @@ -178,10 +176,10 @@ describe('JSONP', function () { describe('close', function () { it('should trigger when server closes a client', function (done) { - var engine = listen( { allowUpgrades: false, transports: ['polling'] }, function (port) { - var socket = new eioc.Socket('ws://localhost:' + port - , { transports: ['polling'], forceJSONP: true, upgrade: false }) - , total = 2; + var engine = listen({ allowUpgrades: false, transports: ['polling'] }, function (port) { + var socket = new eioc.Socket('ws://localhost:' + port, + { transports: ['polling'], forceJSONP: true, upgrade: false }); + var total = 2; engine.on('connection', function (conn) { conn.on('close', function (reason) { @@ -203,10 +201,10 @@ describe('JSONP', function () { }); it('should trigger when client closes', function (done) { - var engine = listen( { allowUpgrades: false, transports: ['polling'] }, function (port) { + var engine = listen({ allowUpgrades: false, transports: ['polling'] }, function (port) { var socket = new eioc.Socket('ws://localhost:' + port - , { transports: ['polling'], forceJSONP: true, upgrade: false }) - , total = 2; + , { transports: ['polling'], forceJSONP: true, upgrade: false }); + var total = 2; engine.on('connection', function (conn) { conn.on('close', function (reason) { diff --git a/test/server.js b/test/server.js index ebd5afdd0d..136025b07a 100644 --- a/test/server.js +++ b/test/server.js @@ -14,27 +14,25 @@ var eioc = require('engine.io-client'); var listen = require('./common').listen; var expect = require('expect.js'); var request = require('superagent'); -var WebSocket = require('ws'); // are we running on node 0.8? var NODE_0_8 = /^v0\.8\./.test(process.version); // are we running on node < 4.4.3 ? -var NODE_LT_443 = (function(){ +var NODE_LT_443 = (function () { var parts = process.versions.node.split('.'); return (parts[0] < 4 || parts[1] < 4 || parts[2] < 3); })(); // are we running uws wsEngine ? -var UWS_ENGINE = process.env.EIO_WS_ENGINE == "uws"; +var UWS_ENGINE = process.env.EIO_WS_ENGINE === 'uws'; /** * Tests. */ describe('server', function () { - describe('verification', function () { it('should disallow non-existent transports', function (done) { - var engine = listen(function (port) { + listen(function (port) { request.get('http://localhost:%d/engine.io/default/'.s(port)) .query({ transport: 'tobi' }) // no tobi transport - outrageous .end(function (res) { @@ -49,7 +47,7 @@ describe('server', function () { it('should disallow `constructor` as transports', function (done) { // make sure we check for actual properties - not those present on every {} - var engine = listen(function (port) { + listen(function (port) { request.get('http://localhost:%d/engine.io/default/'.s(port)) .set('Origin', 'http://engine.io') .query({ transport: 'constructor' }) @@ -65,7 +63,7 @@ describe('server', function () { }); it('should disallow non-existent sids', function (done) { - var engine = listen(function (port) { + listen(function (port) { request.get('http://localhost:%d/engine.io/default/'.s(port)) .set('Origin', 'http://engine.io') .query({ transport: 'polling', sid: 'test' }) @@ -83,7 +81,7 @@ describe('server', function () { describe('handshake', function () { it('should send the io cookie', function (done) { - var engine = listen(function (port) { + listen(function (port) { request.get('http://localhost:%d/engine.io/default/'.s(port)) .query({ transport: 'polling', b64: 1 }) .end(function (res) { @@ -96,7 +94,7 @@ describe('server', function () { }); it('should send the io cookie custom name', function (done) { - var engine = listen({ cookie: 'woot' }, function (port) { + listen({ cookie: 'woot' }, function (port) { request.get('http://localhost:%d/engine.io/default/'.s(port)) .query({ transport: 'polling', b64: 1 }) .end(function (res) { @@ -108,7 +106,7 @@ describe('server', function () { }); it('should send the cookie with custom path', function (done) { - var engine = listen({ cookiePath: '/' }, function (port) { + listen({ cookiePath: '/' }, function (port) { request.get('http://localhost:%d/engine.io/default/'.s(port)) .query({ transport: 'polling', b64: 1 }) .end(function (res) { @@ -120,7 +118,7 @@ describe('server', function () { }); it('should not send the io cookie', function (done) { - var engine = listen({ cookie: false }, function (port) { + listen({ cookie: false }, function (port) { request.get('http://localhost:%d/engine.io/default/'.s(port)) .query({ transport: 'polling' }) .end(function (res) { @@ -151,7 +149,7 @@ describe('server', function () { var customId = 'CustomId' + Date.now(); - engine.generateId = function(req) { + engine.generateId = function (req) { return customId; }; @@ -167,7 +165,7 @@ describe('server', function () { }); it('should exchange handshake data', function (done) { - var engine = listen({ allowUpgrades: false }, function (port) { + listen({ allowUpgrades: false }, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); socket.on('handshake', function (obj) { expect(obj.sid).to.be.a('string'); @@ -179,7 +177,7 @@ describe('server', function () { }); it('should allow custom ping timeouts', function (done) { - var engine = listen({ allowUpgrades: false, pingTimeout: 123 }, function (port) { + listen({ allowUpgrades: false, pingTimeout: 123 }, function (port) { var socket = new eioc.Socket('http://localhost:%d'.s(port)); socket.on('handshake', function (obj) { expect(obj.pingTimeout).to.be(123); @@ -190,7 +188,7 @@ describe('server', function () { it('should trigger a connection event with a Socket', function (done) { var engine = listen({ allowUpgrades: false }, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port)); + eioc('ws://localhost:%d'.s(port)); engine.on('connection', function (socket) { expect(socket).to.be.an(eio.Socket); done(); @@ -200,7 +198,7 @@ describe('server', function () { it('should open with polling by default', function (done) { var engine = listen({ allowUpgrades: false }, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port)); + eioc('ws://localhost:%d'.s(port)); engine.on('connection', function (socket) { expect(socket.transport.name).to.be('polling'); done(); @@ -210,7 +208,7 @@ describe('server', function () { it('should be able to open with ws directly', function (done) { var engine = listen({ transports: ['websocket'] }, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); + eioc('ws://localhost:%d'.s(port), { transports: ['websocket'] }); engine.on('connection', function (socket) { expect(socket.transport.name).to.be('websocket'); done(); @@ -219,7 +217,7 @@ describe('server', function () { }); it('should not suggest any upgrades for websocket', function (done) { - var engine = listen({ transports: ['websocket'] }, function (port) { + listen({ transports: ['websocket'] }, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); socket.on('handshake', function (obj) { expect(obj.upgrades).to.have.length(0); @@ -229,7 +227,7 @@ describe('server', function () { }); it('should not suggest upgrades when none are availble', function (done) { - var engine = listen({ transports: ['polling'] }, function (port) { + listen({ transports: ['polling'] }, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { }); socket.on('handshake', function (obj) { expect(obj.upgrades).to.have.length(0); @@ -239,7 +237,7 @@ describe('server', function () { }); it('should only suggest available upgrades', function (done) { - var engine = listen({ transports: ['polling'] }, function (port) { + listen({ transports: ['polling'] }, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { }); socket.on('handshake', function (obj) { expect(obj.upgrades).to.have.length(0); @@ -249,7 +247,7 @@ describe('server', function () { }); it('should suggest all upgrades when no transports are disabled', function (done) { - var engine = listen({}, function (port) { + listen({}, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { }); socket.on('handshake', function (obj) { expect(obj.upgrades).to.have.length(1); @@ -261,10 +259,9 @@ describe('server', function () { it('default to polling when proxy doesn\'t support websocket', function (done) { var engine = listen({ allowUpgrades: false }, function (port) { - engine.on('connection', function (socket) { socket.on('message', function (msg) { - if ('echo' == msg) socket.send(msg); + if ('echo' === msg) socket.send(msg); }); }); @@ -289,7 +286,7 @@ describe('server', function () { it('should allow arbitrary data through query string', function (done) { var engine = listen({ allowUpgrades: false }, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port), { query: { a: 'b' } }); + eioc('ws://localhost:%d'.s(port), { query: { a: 'b' } }); engine.on('connection', function (conn) { expect(conn.request._query).to.have.keys('transport', 'a'); expect(conn.request._query.a).to.be('b'); @@ -300,7 +297,7 @@ describe('server', function () { it('should allow data through query string in uri', function (done) { var engine = listen({ allowUpgrades: false }, function (port) { - var socket = new eioc.Socket('ws://localhost:%d?a=b&c=d'.s(port)); + eioc('ws://localhost:%d?a=b&c=d'.s(port)); engine.on('connection', function (conn) { expect(conn.request._query.EIO).to.be.a('string'); expect(conn.request._query.a).to.be('b'); @@ -310,10 +307,8 @@ describe('server', function () { }); }); - - it('should disallow bad requests', function (done) { - var engine = listen(function (port) { + listen(function (port) { request.get('http://localhost:%d/engine.io/default/'.s(port)) .set('Origin', 'http://engine.io') .query({ transport: 'websocket' }) @@ -330,10 +325,10 @@ describe('server', function () { }); describe('close', function () { - it('should be able to access non-empty writeBuffer at closing (server)', function(done) { + it('should be able to access non-empty writeBuffer at closing (server)', function (done) { var opts = {allowUpgrades: false}; var engine = listen(opts, function (port) { - var socket = new eioc.Socket('http://localhost:%d'.s(port)); + eioc('http://localhost:%d'.s(port)); engine.on('connection', function (conn) { conn.on('close', function (reason) { expect(conn.writeBuffer.length).to.be(1); @@ -342,25 +337,25 @@ describe('server', function () { }, 10); done(); }); - conn.writeBuffer.push({ type: 'message', data: 'foo'}); + conn.writeBuffer.push({ type: 'message', data: 'foo' }); conn.onError(''); }); }); }); - it('should be able to access non-empty writeBuffer at closing (client)', function(done) { + it('should be able to access non-empty writeBuffer at closing (client)', function (done) { var opts = {allowUpgrades: false}; - var engine = listen(opts, function (port) { + listen(opts, function (port) { var socket = new eioc.Socket('http://localhost:%d'.s(port)); - socket.on('open', function() { + socket.on('open', function () { socket.on('close', function (reason) { expect(socket.writeBuffer.length).to.be(1); - setTimeout(function() { + setTimeout(function () { expect(socket.writeBuffer.length).to.be(0); }, 10); done(); }); - socket.writeBuffer.push({ type: 'message', data: 'foo'}); + socket.writeBuffer.push({ type: 'message', data: 'foo' }); socket.onError(''); }); }); @@ -370,7 +365,7 @@ describe('server', function () { var opts = { allowUpgrades: false, pingInterval: 5, pingTimeout: 5 }; var engine = listen(opts, function (port) { var socket = new eioc.Socket('http://localhost:%d'.s(port)); - socket.sendPacket = function (){}; + socket.sendPacket = function () {}; engine.on('connection', function (conn) { conn.on('close', function (reason) { expect(reason).to.be('ping timeout'); @@ -390,7 +385,7 @@ describe('server', function () { done(); }); // client abruptly disconnects, no polling request on this tick since we've just connected - socket.sendPacket = socket.onPacket = function (){}; + socket.sendPacket = socket.onPacket = function () {}; socket.close(); // then server app tries to close the socket, since client disappeared conn.close(); @@ -400,12 +395,12 @@ describe('server', function () { it('should trigger on client if server does not meet ping timeout', function (done) { var opts = { allowUpgrades: false, pingInterval: 50, pingTimeout: 30 }; - var engine = listen(opts, function (port) { + listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); socket.on('open', function () { // override onPacket and Transport#onClose to simulate an inactive server after handshake - socket.onPacket = function(){}; - socket.transport.onClose = function(){}; + socket.onPacket = function () {}; + socket.transport.onClose = function () {}; socket.on('close', function (reason, err) { expect(reason).to.be('ping timeout'); done(); @@ -417,8 +412,8 @@ describe('server', function () { it('should trigger on both ends upon ping timeout', function (done) { var opts = { allowUpgrades: false, pingTimeout: 10, pingInterval: 10 }; var engine = listen(opts, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port)) - , total = 2; + var socket = new eioc.Socket('ws://localhost:%d'.s(port)); + var total = 2; function onClose (reason, err) { expect(reason).to.be('ping timeout'); @@ -431,8 +426,8 @@ describe('server', function () { socket.on('open', function () { // override onPacket and Transport#onClose to simulate an inactive server after handshake - socket.onPacket = socket.sendPacket = function(){}; - socket.transport.onClose = function(){}; + socket.onPacket = socket.sendPacket = function () {}; + socket.transport.onClose = function () {}; socket.on('close', onClose); }); }); @@ -440,8 +435,8 @@ describe('server', function () { it('should trigger when server closes a client', function (done) { var engine = listen({ allowUpgrades: false }, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port)) - , total = 2; + var socket = new eioc.Socket('ws://localhost:%d'.s(port)); + var total = 2; engine.on('connection', function (conn) { conn.on('close', function (reason) { @@ -465,8 +460,8 @@ describe('server', function () { it('should trigger when server closes a client (ws)', function (done) { var opts = { allowUpgrades: false, transports: ['websocket'] }; var engine = listen(opts, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }) - , total = 2; + var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); + var total = 2; engine.on('connection', function (conn) { conn.on('close', function (reason) { @@ -489,8 +484,8 @@ describe('server', function () { it('should trigger when client closes', function (done) { var engine = listen({ allowUpgrades: false }, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port)) - , total = 2; + var socket = new eioc.Socket('ws://localhost:%d'.s(port)); + var total = 2; engine.on('connection', function (conn) { conn.on('close', function (reason) { @@ -515,8 +510,8 @@ describe('server', function () { it('should trigger when client closes (ws)', function (done) { var opts = { allowUpgrades: false, transports: ['websocket'] }; var engine = listen(opts, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }) - , total = 2; + var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); + var total = 2; engine.on('connection', function (conn) { conn.on('close', function (reason) { @@ -543,7 +538,7 @@ describe('server', function () { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); engine.on('connection', function (conn) { - conn.send(null, function () {socket.close();}); + conn.send(null, function () { socket.close(); }); conn.send('this should not be handled'); conn.on('close', function (reason) { @@ -565,12 +560,12 @@ describe('server', function () { }); it('should abort upgrade if socket is closed (GH-35)', function (done) { - var engine = listen({ allowUpgrades: true }, function (port) { + listen({ allowUpgrades: true }, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); socket.on('open', function () { socket.close(); // we wait until complete to see if we get an uncaught EPIPE - setTimeout(function(){ + setTimeout(function () { done(); }, 100); }); @@ -584,29 +579,29 @@ describe('server', function () { // see: https://github.com/driverdan/node-XMLHttpRequest/issues/44 var request = require('http').request; var sockets = []; - http.request = function(opts){ + http.request = function (opts) { var req = request.apply(null, arguments); - req.on('socket', function(socket){ + req.on('socket', function (socket) { sockets.push(socket); }); return req; }; - function done(){ + function done () { http.request = request; $done(); } - var socket = new eioc.Socket('ws://localhost:%d'.s(port)) - , serverSocket; + var socket = new eioc.Socket('ws://localhost:%d'.s(port)); + var serverSocket; - engine.on('connection', function(s){ + engine.on('connection', function (s) { serverSocket = s; }); - socket.transport.on('poll', function(){ + socket.transport.on('poll', function () { // we set a timer to wait for the request to actually reach - setTimeout(function(){ + setTimeout(function () { // at this time server's `connection` should have been fired expect(serverSocket).to.be.an('object'); @@ -622,7 +617,7 @@ describe('server', function () { // kill the underlying connection sockets[1].end(); - serverSocket.on('close', function(reason, err){ + serverSocket.on('close', function (reason, err) { expect(reason).to.be('transport error'); expect(err.message).to.be('poll connection closed prematurely'); done(); @@ -632,34 +627,34 @@ describe('server', function () { }); }); - it('should not trigger with connection: close header', function($done){ - var engine = listen({ allowUpgrades: false }, function(port){ + it('should not trigger with connection: close header', function ($done) { + var engine = listen({ allowUpgrades: false }, function (port) { // intercept requests to add connection: close var request = http.request; - http.request = function(){ + http.request = function () { var opts = arguments[0]; opts.headers = opts.headers || {}; opts.headers.Connection = 'close'; return request.apply(this, arguments); }; - function done(){ + function done () { http.request = request; $done(); } - engine.on('connection', function(socket){ - socket.on('message', function(msg){ + engine.on('connection', function (socket) { + socket.on('message', function (msg) { expect(msg).to.equal('test'); socket.send('woot'); }); }); var socket = new eioc.Socket('ws://localhost:%d'.s(port)); - socket.on('open', function(){ + socket.on('open', function () { socket.send('test'); }); - socket.on('message', function(msg){ + socket.on('message', function (msg) { expect(msg).to.be('woot'); done(); }); @@ -671,12 +666,12 @@ describe('server', function () { // first timeout should trigger after `pingInterval + pingTimeout`, // not just `pingTimeout`. var opts = { allowUpgrades: false, pingInterval: 300, pingTimeout: 100 }; - var engine = listen(opts, function (port) { + listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); var clientCloseReason = null; - socket.on('handshake', function() { - socket.onPacket = function(){}; + socket.on('handshake', function () { + socket.onPacket = function () {}; }); socket.on('open', function () { socket.on('close', function (reason) { @@ -684,7 +679,7 @@ describe('server', function () { }); }); - setTimeout(function() { + setTimeout(function () { expect(clientCloseReason).to.be(null); done(); }, 200); @@ -700,9 +695,9 @@ describe('server', function () { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); var clientCloseReason = null; - engine.on('connection', function(conn){ - conn.on('heartbeat', function() { - conn.onPacket = function(){}; + engine.on('connection', function (conn) { + conn.on('heartbeat', function () { + conn.onPacket = function () {}; }); }); @@ -712,7 +707,7 @@ describe('server', function () { }); }); - setTimeout(function() { + setTimeout(function () { expect(clientCloseReason).to.be(null); done(); }, 100); @@ -734,12 +729,12 @@ describe('server', function () { }); }); - engine.on('connection', function(conn){ - conn.on('heartbeat', function() { - setTimeout(function() { + engine.on('connection', function (conn) { + conn.on('heartbeat', function () { + setTimeout(function () { conn.close(); }, 20); - setTimeout(function() { + setTimeout(function () { expect(clientCloseReason).to.be('transport close'); done(); }, 100); @@ -761,16 +756,16 @@ describe('server', function () { }); }); - engine.on('connection', function(conn){ - conn.once('heartbeat', function() { - setTimeout(function() { - socket.onPacket = function(){}; + engine.on('connection', function (conn) { + conn.once('heartbeat', function () { + setTimeout(function () { + socket.onPacket = function () {}; expect(clientCloseReason).to.be(null); }, 150); - setTimeout(function() { + setTimeout(function () { expect(clientCloseReason).to.be(null); }, 350); - setTimeout(function() { + setTimeout(function () { expect(clientCloseReason).to.be('ping timeout'); done(); }, 500); @@ -802,15 +797,15 @@ describe('server', function () { // tests https://github.com/LearnBoost/engine.io-client/issues/207 // websocket test, transport error - it('should trigger transport close before open for ws', function(done){ + it('should trigger transport close before open for ws', function (done) { var opts = { transports: ['websocket'] }; - var engine = listen(opts, function (port) { + listen(opts, function (port) { var url = 'ws://%s:%d'.s('0.0.0.50', port); var socket = new eioc.Socket(url); - socket.on('open', function(){ + socket.on('open', function () { done(new Error('Test invalidation')); }); - socket.on('close', function(reason){ + socket.on('close', function (reason) { expect(reason).to.be('transport error'); done(); }); @@ -819,14 +814,14 @@ describe('server', function () { // tests https://github.com/LearnBoost/engine.io-client/issues/207 // polling test, transport error - it('should trigger transport close before open for xhr', function(done){ + it('should trigger transport close before open for xhr', function (done) { var opts = { transports: ['polling'] }; - var engine = listen(opts, function (port) { + listen(opts, function (port) { var socket = new eioc.Socket('http://invalidserver:%d'.s(port)); - socket.on('open', function(){ + socket.on('open', function () { done(new Error('Test invalidation')); }); - socket.on('close', function(reason){ + socket.on('close', function (reason) { expect(reason).to.be('transport error'); done(); }); @@ -835,14 +830,14 @@ describe('server', function () { // tests https://github.com/LearnBoost/engine.io-client/issues/207 // websocket test, force close - it('should trigger force close before open for ws', function(done){ + it('should trigger force close before open for ws', function (done) { var opts = { transports: ['websocket'] }; - var engine = listen(opts, function (port) { + listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); - socket.on('open', function(){ + socket.on('open', function () { done(new Error('Test invalidation')); }); - socket.on('close', function(reason){ + socket.on('close', function (reason) { expect(reason).to.be('forced close'); done(); }); @@ -852,14 +847,14 @@ describe('server', function () { // tests https://github.com/LearnBoost/engine.io-client/issues/207 // polling test, force close - it('should trigger force close before open for xhr', function(done){ + it('should trigger force close before open for xhr', function (done) { var opts = { transports: ['polling'] }; - var engine = listen(opts, function (port) { + listen(opts, function (port) { var socket = new eioc.Socket('http://localhost:%d'.s(port)); - socket.on('open', function(){ + socket.on('open', function () { done(new Error('Test invalidation')); }); - socket.on('close', function(reason){ + socket.on('close', function (reason) { expect(reason).to.be('forced close'); done(); }); @@ -875,7 +870,7 @@ describe('server', function () { }); var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); // override to simulate an inactive client - socket.sendPacket = socket.onHeartbeat = function (){}; + socket.sendPacket = socket.onHeartbeat = function () {}; }); }); @@ -887,7 +882,7 @@ describe('server', function () { }); var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['polling'] }); // override to simulate an inactive client - socket.sendPacket = socket.onHeartbeat = function (){}; + socket.sendPacket = socket.onHeartbeat = function () {}; }); }); @@ -913,7 +908,7 @@ describe('server', function () { }); var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['polling'] }); socket.on('open', function () { - socket.transport.doWrite('invalid', function (){}); + socket.transport.doWrite('invalid', function () {}); }); }); }); @@ -926,7 +921,7 @@ describe('server', function () { conn.close(); }); }); - new eioc.Socket('ws://localhost:%d'.s(port)); + eioc('ws://localhost:%d'.s(port)); }); }); @@ -941,18 +936,18 @@ describe('server', function () { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); socket.on('upgrading', function (transport) { // override not to complete upgrading - transport.send = function (){}; + transport.send = function () {}; }); }); }); - it('should not crash when messing with Object prototype', function(done){ - Object.prototype.foo = 'bar'; + it('should not crash when messing with Object prototype', function (done) { + Object.prototype.foo = 'bar'; // eslint-disable-line no-extend-native var engine = listen({ allowUpgrades: true }, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); socket.on('open', function () { engine.close(); - setTimeout(function(){ + setTimeout(function () { done(); }, 100); }); @@ -960,20 +955,20 @@ describe('server', function () { }); describe('graceful close', function () { - function fixture(filename) { + function fixture (filename) { return process.execPath + ' ' + path.join(__dirname, 'fixtures', filename); } - it('should stop socket and timers', function(done){ + it('should stop socket and timers', function (done) { exec(fixture('server-close.js'), done); }); - it('should stop upgraded socket and timers', function(done){ + it('should stop upgraded socket and timers', function (done) { exec(fixture('server-close-upgraded.js'), done); }); - it('should stop upgrading socket and timers', function(done){ + it('should stop upgrading socket and timers', function (done) { exec(fixture('server-close-upgrading.js'), done); }); }); @@ -999,9 +994,9 @@ describe('server', function () { it('should arrive from server to client (multiple)', function (done) { var engine = listen({ allowUpgrades: false }, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port)) - , expected = ['a', 'b', 'c'] - , i = 0; + var socket = new eioc.Socket('ws://localhost:%d'.s(port)); + var expected = ['a', 'b', 'c']; + var i = 0; engine.on('connection', function (conn) { conn.send('a'); @@ -1034,12 +1029,12 @@ describe('server', function () { }); }); - it('should not be receiving data when getting a message longer than maxHttpBufferSize when polling', function(done) { + it('should not be receiving data when getting a message longer than maxHttpBufferSize when polling', function (done) { var opts = { allowUpgrades: false, transports: ['polling'], maxHttpBufferSize: 5 }; var engine = listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); engine.on('connection', function (conn) { - conn.on('message', function(msg) { + conn.on('message', function (msg) { console.log(msg); }); }); @@ -1050,12 +1045,12 @@ describe('server', function () { setTimeout(done, 1000); }); - it('should receive data when getting a message shorter than maxHttpBufferSize when polling', function(done) { + it('should receive data when getting a message shorter than maxHttpBufferSize when polling', function (done) { var opts = { allowUpgrades: false, transports: ['polling'], maxHttpBufferSize: 5 }; var engine = listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port)); engine.on('connection', function (conn) { - conn.on('message', function(msg) { + conn.on('message', function (msg) { expect(msg).to.be('a'); done(); }); @@ -1066,7 +1061,6 @@ describe('server', function () { }); }); - it('should arrive from server to client (ws)', function (done) { var opts = { allowUpgrades: false, transports: ['websocket'] }; var engine = listen(opts, function (port) { @@ -1086,9 +1080,9 @@ describe('server', function () { it('should arrive from server to client (multiple, ws)', function (done) { var opts = { allowUpgrades: false, transports: ['websocket'] }; var engine = listen(opts, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }) - , expected = ['a', 'b', 'c'] - , i = 0; + var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); + var expected = ['a', 'b', 'c']; + var i = 0; engine.on('connection', function (conn) { conn.send('a'); @@ -1118,9 +1112,9 @@ describe('server', function () { it('should arrive from server to client (multiple, no delay, ws)', function (done) { var opts = { allowUpgrades: false, transports: ['websocket'] }; var engine = listen(opts, function (port) { - var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }) - , expected = ['a', 'b', 'c'] - , i = 0; + var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); + var expected = ['a', 'b', 'c']; + var i = 0; engine.on('connection', function (conn) { conn.on('close', function () { @@ -1150,7 +1144,7 @@ describe('server', function () { } var opts = { allowUpgrades: false, transports: ['websocket'] }; - var engine = listen(opts, function(port) { + var engine = listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); engine.on('connection', function (conn) { @@ -1158,7 +1152,7 @@ describe('server', function () { }); socket.on('open', function () { - socket.on('message', function(msg) { + socket.on('message', function (msg) { for (var i = 0; i < binaryData.length; i++) { var num = msg.readInt8(i); expect(num).to.be(i); @@ -1176,7 +1170,7 @@ describe('server', function () { } var opts = { allowUpgrades: false, transports: ['websocket'] }; - var engine = listen(opts, function(port) { + var engine = listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); engine.on('connection', function (conn) { @@ -1184,7 +1178,7 @@ describe('server', function () { }); socket.on('open', function () { - socket.on('message', function(msg) { + socket.on('message', function (msg) { for (var i = 0, ii = 0; ii < binaryData.length; i += 4, ii++) { var num = msg.readInt32LE(i); expect(num).to.be((ii + 100) * 9823); @@ -1202,7 +1196,7 @@ describe('server', function () { } var opts = { allowUpgrades: false, transports: ['websocket'] }; - var engine = listen(opts, function(port) { + var engine = listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); engine.on('connection', function (conn) { @@ -1210,7 +1204,7 @@ describe('server', function () { }); socket.on('open', function () { - socket.on('message', function(msg) { + socket.on('message', function (msg) { for (var i = 0, ii = 0; ii < binaryData.length; i += 4, ii++) { var num = msg.readInt32LE(i); expect(num).to.be((ii + 100) * 9823); @@ -1228,7 +1222,7 @@ describe('server', function () { } var opts = { allowUpgrades: false, transports: ['websocket'] }; - var engine = listen(opts, function(port) { + var engine = listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); engine.on('connection', function (conn) { @@ -1236,7 +1230,7 @@ describe('server', function () { }); socket.on('open', function () { - socket.on('message', function(msg) { + socket.on('message', function (msg) { for (var i = 0; i < binaryData.length; i++) { var num = msg.readInt8(i); expect(num).to.be(i); @@ -1254,15 +1248,15 @@ describe('server', function () { } var opts = { allowUpgrades: false, transports: ['polling'] }; - var engine = listen(opts, function(port) { + var engine = listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['polling'] }); engine.on('connection', function (conn) { conn.send(binaryData); }); - socket.on('open', function() { - socket.on('message', function(msg) { + socket.on('open', function () { + socket.on('message', function (msg) { for (var i = 0; i < binaryData.length; i++) { var num = msg.readInt8(i); expect(num).to.be(i); @@ -1281,7 +1275,7 @@ describe('server', function () { } var opts = { allowUpgrades: false, transports: ['websocket'] }; - var engine = listen(opts, function(port) { + var engine = listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); socket.binaryType = 'arraybuffer'; @@ -1289,8 +1283,8 @@ describe('server', function () { conn.send(binaryData); }); - socket.on('open', function() { - socket.on('message', function(msg) { + socket.on('open', function () { + socket.on('message', function (msg) { expect(msg instanceof ArrayBuffer).to.be(true); var intArray = new Int8Array(msg); for (var i = 0; i < binaryData.length; i++) { @@ -1310,7 +1304,7 @@ describe('server', function () { } var opts = { allowUpgrades: false, transports: ['polling'] }; - var engine = listen(opts, function(port) { + var engine = listen(opts, function (port) { var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['polling'] }); socket.binaryType = 'arraybuffer'; @@ -1318,8 +1312,8 @@ describe('server', function () { conn.send(binaryData); }); - socket.on('open', function() { - socket.on('message', function(msg) { + socket.on('open', function () { + socket.on('message', function (msg) { expect(msg instanceof ArrayBuffer).to.be(true); var intArray = new Int8Array(msg); for (var i = 0; i < binaryData.length; i++) { @@ -1332,28 +1326,27 @@ describe('server', function () { }); }); - - it('should trigger a flush/drain event', function(done){ - var engine = listen({ allowUpgrades: false }, function(port){ - engine.on('connection', function(socket){ + it('should trigger a flush/drain event', function (done) { + var engine = listen({ allowUpgrades: false }, function (port) { + engine.on('connection', function (socket) { var totalEvents = 4; - engine.on('flush', function(sock, buf){ + engine.on('flush', function (sock, buf) { expect(sock).to.be(socket); expect(buf).to.be.an('array'); --totalEvents || done(); }); - socket.on('flush', function(buf){ + socket.on('flush', function (buf) { expect(buf).to.be.an('array'); --totalEvents || done(); }); - engine.on('drain', function(sock){ + engine.on('drain', function (sock) { expect(sock).to.be(socket); expect(socket.writeBuffer.length).to.be(0); --totalEvents || done(); }); - socket.on('drain', function(){ + socket.on('drain', function () { expect(socket.writeBuffer.length).to.be(0); --totalEvents || done(); }); @@ -1361,7 +1354,7 @@ describe('server', function () { socket.send('aaaa'); }); - new eioc.Socket('ws://localhost:%d'.s(port)); + eioc('ws://localhost:%d'.s(port)); }); }); @@ -1385,7 +1378,7 @@ describe('server', function () { }); var socket = new eioc.Socket('ws://localhost:%d'.s(port), { transports: ['websocket'] }); socket.on('open', function () { - for (var i=0;i= 4) describe('wsEngine option', function() { - it('should allow loading of other websocket server implementation like uws', function(done) { - var engine = listen({ allowUpgrades: false, wsEngine: 'uws' }, function (port) { - expect(engine.ws instanceof require('uws').Server).to.be.ok(); - var socket = new eioc.Socket('ws://localhost:%d'.s(port)); - engine.on('connection', function (conn) { - conn.send('a'); - }); - socket.on('open', function () { - socket.on('message', function (msg) { - expect(msg).to.be('a'); - done(); + if (!UWS_ENGINE && parseInt(process.versions.node, 10) >= 4) { + describe('wsEngine option', function () { + it('should allow loading of other websocket server implementation like uws', function (done) { + var engine = listen({ allowUpgrades: false, wsEngine: 'uws' }, function (port) { + expect(engine.ws instanceof require('uws').Server).to.be.ok(); + var socket = new eioc.Socket('ws://localhost:%d'.s(port)); + engine.on('connection', function (conn) { + conn.send('a'); + }); + socket.on('open', function () { + socket.on('message', function (msg) { + expect(msg).to.be('a'); + done(); + }); }); }); }); }); - }); + } });