diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..7172aa4 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,21 @@ +{ + "extends": "standard", + "env": { + "node": true, + "mocha": true, + }, + "parserOptions": { + }, + "globals": { + }, + "rules": { + "no-var": 2, + "object-curly-spacing": [2, "always"], + "object-shorthand": 2, + "prefer-const": 2, + "prefer-template": 2, + "semi": [2, "always", {"omitLastInOneLineBlock": true}], + "space-before-function-paren": [2, "never"], + "standard/object-curly-even-spacing": 0 + } +} diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 31b4d64..0000000 --- a/.eslintrc.js +++ /dev/null @@ -1,37 +0,0 @@ -module.exports = { - env: { - node: true, - mocha: true, - }, - parserOptions: { - sourceType: "script" - }, - globals: { - "Promise": false - }, - rules: { - "brace-style": [2, "1tbs", {"allowSingleLine": true} ], - "complexity": [2, 13], - "curly": 2, - "eqeqeq": 2, - "indent": [2, 2, { - SwitchCase: 1 - }], - "max-depth": 2, - "max-statements": [2, 36], - "new-cap": 2, - "no-caller": 2, - "no-cond-assign": 2, - "no-else-return": 2, - "no-undef": 2, - "no-unused-vars": [2, { "args": "after-used" }], - "no-use-before-define": 2, - "padded-blocks": [2, "never"], - "quotes": [2, "single", "avoid-escape"], - "semi": [2, "always", {"omitLastInOneLineBlock": true }], - "space-before-blocks": [2, "always"], - "space-before-function-paren": [2, "never"], - "strict": 2, - "wrap-iife": [2, "inside"] - } -}; diff --git a/bin/find-arduino.js b/bin/find-arduino.js index 59a54f8..08869e2 100755 --- a/bin/find-arduino.js +++ b/bin/find-arduino.js @@ -3,7 +3,7 @@ // outputs the path to an arduino or nothing -var serialport = require('../'); +const serialport = require('../'); serialport.list(function(err, ports) { if (err) { console.error(err); diff --git a/bin/serialport-list.js b/bin/serialport-list.js index 070f68a..1f35a91 100755 --- a/bin/serialport-list.js +++ b/bin/serialport-list.js @@ -1,9 +1,9 @@ #!/usr/bin/env node 'use strict'; -var serialport = require('../'); -var version = require('../package.json').version; -var args = require('commander'); +const serialport = require('../'); +const version = require('../package.json').version; +const args = require('commander'); args .version(version) @@ -11,29 +11,29 @@ args .option('-f, --format ', 'Format the output as text, json, or jsonline. default: text', /^(text|json|jsonline)$/i, 'text') .parse(process.argv); -var formatters = { - text: function(err, ports) { +const formatters = { + text(err, ports) { if (err) { console.error(err); process.exit(1); } - ports.forEach(function(port) { - console.log(port.comName + '\t' + (port.pnpId || '') + '\t' + (port.manufacturer || '')); + ports.forEach(port => { + console.log(`${port.comName}\t${port.pnpId || ''}\t${port.manufacturer || ''}`); }); }, - json: function(err, ports) { + json(err, ports) { if (err) { console.error(JSON.stringify(err)); process.exit(1); } console.log(JSON.stringify(ports)); }, - jsonline: function(err, ports) { + jsonline(err, ports) { if (err) { console.error(JSON.stringify(err)); process.exit(1); } - ports.forEach(function(port) { + ports.forEach(port => { console.log(JSON.stringify(port)); }); } diff --git a/bin/serialport-terminal.js b/bin/serialport-terminal.js index a8bc105..3463f65 100755 --- a/bin/serialport-terminal.js +++ b/bin/serialport-terminal.js @@ -1,9 +1,9 @@ #!/usr/bin/env node 'use strict'; -var SerialPort = require('../'); -var version = require('../package.json').version; -var args = require('commander'); +const SerialPort = require('../'); +const version = require('../package.json').version; +const args = require('commander'); function makeNumber(input) { return Number(input); @@ -15,7 +15,7 @@ args .description('A basic terminal interface for communicating over a serial port. Pressing ctrl+c exits.') .option('-l --list', 'List available ports then exit') // TODO make the port not a flag as it's always required - .option('-p, --port, --portname ', 'Path or Name of serial port') + .option('-p, --port ', 'Path or Name of serial port') .option('-b, --baud ', 'Baud rate default: 9600', makeNumber, 9600) .option('--databits ', 'Data bits default: 8', makeNumber, 8) .option('--parity ', 'Parity default: none', 'none') @@ -30,53 +30,57 @@ function listPorts() { console.error('Error listing ports', err); } else { ports.forEach(function(port) { - console.log(port.comName + '\t' + (port.pnpId || '') + '\t' + (port.manufacturer || '')); + console.log(`${port.comName}\t${port.pnpId || ''}\t${port.manufacturer || ''}`); }); } }); }; -if (args.list) { - return listPorts(); -} - -if (!args.port) { - args.outputHelp(); - args.missingArgument('port'); - process.exit(-1); -} - -var openOptions = { - baudRate: args.baud, - dataBits: args.databits, - parity: args.parity, - stopBits: args.stopbits -}; - -var port = new SerialPort(args.port, openOptions); - -process.stdin.resume(); -process.stdin.setRawMode(true); -process.stdin.on('data', function(s) { - if (s[0] === 0x03) { - port.close(); - process.exit(0); +function createPort() { + if (!args.port) { + args.outputHelp(); + args.missingArgument('port'); + process.exit(-1); } - if (args.localecho) { - if (s[0] === 0x0d) { - process.stdout.write('\n'); - } else { - process.stdout.write(s); + + const openOptions = { + baudRate: args.baud, + dataBits: args.databits, + parity: args.parity, + stopBits: args.stopbits + }; + + const port = new SerialPort(args.port, openOptions); + + process.stdin.resume(); + process.stdin.setRawMode(true); + process.stdin.on('data', function(s) { + if (s[0] === 0x03) { + port.close(); + process.exit(0); } - } - port.write(s); -}); + if (args.localecho) { + if (s[0] === 0x0d) { + process.stdout.write('\n'); + } else { + process.stdout.write(s); + } + } + port.write(s); + }); -port.on('data', function(data) { - process.stdout.write(data.toString()); -}); + port.on('data', function(data) { + process.stdout.write(data.toString()); + }); -port.on('error', function(err) { - console.log('Error', err); - process.exit(1); -}); + port.on('error', function(err) { + console.log('Error', err); + process.exit(1); + }); +} + +if (args.list) { + listPorts(); +} else { + createPort(); +} diff --git a/examples/drain.js b/examples/drain.js index c342774..fa0dfad 100644 --- a/examples/drain.js +++ b/examples/drain.js @@ -1,10 +1,10 @@ 'use strict'; -var SerialPort = require('serialport'); -var port = new SerialPort('/dev/cu.Cubelet-RGB'); +const SerialPort = require('serialport'); +const port = new SerialPort('/dev/cu.Cubelet-RGB'); port.on('open', function() { - var largeMessage = new Buffer(1024 * 10).fill('!'); + const largeMessage = new Buffer(1024 * 10).fill('!'); console.log('Calling write'); port.write(largeMessage, function() { console.log('Write callback returned'); diff --git a/examples/readdata.js b/examples/readdata.js index 3002513..ff573b2 100644 --- a/examples/readdata.js +++ b/examples/readdata.js @@ -1,9 +1,9 @@ 'use strict'; -var serialport = require('serialport'); -var SerialPort = serialport.SerialPort; -var parsers = serialport.parsers; +const serialport = require('serialport'); +const SerialPort = serialport.SerialPort; +const parsers = serialport.parsers; -var port = new SerialPort('/dev/cu.usbmodemfd121', { +const port = new SerialPort('/dev/cu.usbmodemfd121', { baudrate: 9600, parser: parsers.readline('\r\n') }); diff --git a/lib/bindings-auto-detect.js b/lib/bindings-auto-detect.js index 5de472c..acfc529 100644 --- a/lib/bindings-auto-detect.js +++ b/lib/bindings-auto-detect.js @@ -1,6 +1,6 @@ 'use strict'; -var debug = require('debug')('serialport:binding'); +const debug = require('debug')('serialport:binding'); /** * @module serialport diff --git a/lib/bindings-darwin.js b/lib/bindings-darwin.js index ab7e65c..352cc28 100644 --- a/lib/bindings-darwin.js +++ b/lib/bindings-darwin.js @@ -1,8 +1,8 @@ 'use strict'; -var binding = require('bindings')('serialport.node'); +const binding = require('bindings')('serialport.node'); -var defaultBindingOptions = { +const defaultBindingOptions = { vmin: 1, vtime: 0 }; @@ -111,7 +111,7 @@ DarwinBinding.prototype.write = function(buffer, cb) { binding.write(this.fd, buffer, cb); }; -var commonMethods = [ +const commonMethods = [ 'drain', 'flush', 'update', @@ -120,8 +120,8 @@ var commonMethods = [ commonMethods.map(function(methodName) { DarwinBinding.prototype[methodName] = function() { - var args = Array.prototype.slice.apply(arguments); - var cb = args[args.length - 1]; + const args = Array.prototype.slice.apply(arguments); + const cb = args[args.length - 1]; if (typeof cb !== 'function') { throw new TypeError('"cb" is not a function'); @@ -137,7 +137,7 @@ commonMethods.map(function(methodName) { Object.defineProperty(DarwinBinding.prototype, 'isOpen', { enumerable: true, - get: function() { + get() { return this.fd !== null; } }); diff --git a/lib/bindings-linux.js b/lib/bindings-linux.js index c8bd9c0..46cbcde 100644 --- a/lib/bindings-linux.js +++ b/lib/bindings-linux.js @@ -1,8 +1,8 @@ 'use strict'; -var binding = require('bindings')('serialport.node'); +const binding = require('bindings')('serialport.node'); -var defaultBindingOptions = { +const defaultBindingOptions = { vmin: 1, vtime: 0 }; @@ -110,7 +110,7 @@ LinuxBinding.prototype.write = function(buffer, cb) { binding.write(this.fd, buffer, cb); }; -var commonMethods = [ +const commonMethods = [ 'drain', 'flush', 'update', @@ -119,8 +119,8 @@ var commonMethods = [ commonMethods.map(function(methodName) { LinuxBinding.prototype[methodName] = function() { - var args = Array.prototype.slice.apply(arguments); - var cb = args[args.length - 1]; + const args = Array.prototype.slice.apply(arguments); + const cb = args[args.length - 1]; if (typeof cb !== 'function') { throw new TypeError('"cb" is not a function'); @@ -136,7 +136,7 @@ commonMethods.map(function(methodName) { Object.defineProperty(LinuxBinding.prototype, 'isOpen', { enumerable: true, - get: function() { + get() { return this.fd !== null; } }); diff --git a/lib/bindings-mock.js b/lib/bindings-mock.js index 4c1f26a..c66ce3f 100644 --- a/lib/bindings-mock.js +++ b/lib/bindings-mock.js @@ -1,15 +1,15 @@ 'use strict'; -var inherits = require('util').inherits; +const inherits = require('util').inherits; -var processNextTick = function() { - var args = Array.prototype.slice.apply(arguments); - var cb = args.shift(); +const processNextTick = function() { + const args = Array.prototype.slice.apply(arguments); + const cb = args.shift(); process.nextTick(function() { cb.apply(null, args) }); }; function MissingPortError(name) { name = name || 'unknown method:'; - this.message = 'Port does not exist - please call MockBindings.createPort(path) first: ' + name; + this.message = `Port does not exist - please call MockBindings.createPort(path) first: ${name}`; this.name = 'MissingPortError'; Error.captureStackTrace(this, MissingPortError); } @@ -17,13 +17,13 @@ inherits(MissingPortError, Error); function ClosedPortError(name) { name = name || 'unknown method:'; - this.message = 'Port is closed: ' + name; + this.message = `Port is closed: ${name}`; this.name = 'ClosedPortError'; Error.captureStackTrace(this, MissingPortError); } inherits(ClosedPortError, Error); -var ports = {}; +let ports = {}; function MockBindings(opt) { if (typeof opt.disconnect !== 'function') { @@ -63,7 +63,7 @@ MockBindings.createPort = function(path, opt) { }; MockBindings.list = function(cb) { - var info = Object.keys(ports).map(function(path) { + const info = Object.keys(ports).map(function(path) { return ports[path].info; }); processNextTick(cb, null, info); @@ -77,10 +77,10 @@ MockBindings.prototype.emitData = function(data) { this.port.data = Buffer.concat([this.port.data, data]); if (this.port.pendingReadCB) { - var buffer = this.port.pendingReadCB[0]; - var offset = this.port.pendingReadCB[1]; - var length = this.port.pendingReadCB[2]; - var cb = this.port.pendingReadCB[3]; + const buffer = this.port.pendingReadCB[0]; + const offset = this.port.pendingReadCB[1]; + const length = this.port.pendingReadCB[2]; + const cb = this.port.pendingReadCB[3]; this.port.pendingReadCB = null; processNextTick(this.read.bind(this), buffer, offset, length, cb); } @@ -104,7 +104,7 @@ MockBindings.prototype.open = function(path, opt, cb) { throw new TypeError('"cb" is not a function'); } - var port = this.port = ports[path]; + const port = this.port = ports[path]; if (!port) { return processNextTick(cb, new MissingPortError(path)); } @@ -128,7 +128,7 @@ MockBindings.prototype.open = function(path, opt, cb) { }; MockBindings.prototype.close = function(cb) { - var port = this.port; + const port = this.port; if (!port) { return processNextTick(cb, new ClosedPortError('close')); } @@ -184,7 +184,7 @@ MockBindings.prototype.write = function(buffer, cb) { return processNextTick(cb, new ClosedPortError('write')); } - var data = this.port.lastWrite = new Buffer(buffer); // copy + const data = this.port.lastWrite = new Buffer(buffer); // copy processNextTick(cb, null); if (this.port.echo) { @@ -205,8 +205,8 @@ MockBindings.prototype.read = function(buffer, offset, length, cb) { this.port.pendingReadCB = [buffer, offset, length, cb]; return; } - var data = this.port.data.slice(0, length); - var readLength = data.copy(buffer, offset); + const data = this.port.data.slice(0, length); + const readLength = data.copy(buffer, offset); this.port.data = this.port.data.slice(length); processNextTick(cb, null, readLength, buffer); diff --git a/lib/bindings-win32.js b/lib/bindings-win32.js index 8d2a291..5c4664e 100644 --- a/lib/bindings-win32.js +++ b/lib/bindings-win32.js @@ -1,6 +1,6 @@ 'use strict'; -var binding = require('bindings')('serialport.node'); +const binding = require('bindings')('serialport.node'); function asyncError(cb, err) { process.nextTick(function() { @@ -27,7 +27,7 @@ WindowsBinding.prototype.read = function(buffer, offset, length, cb) { if (typeof offset !== 'number') { throw new TypeError('"offset" is not an integer'); } - + if (typeof length !== 'number') { throw new TypeError('"length" is not an integer'); } @@ -128,7 +128,7 @@ WindowsBinding.prototype.write = function(buffer, cb) { binding.write(this.fd, buffer, cb); }; -var commonMethods = [ +const commonMethods = [ 'drain', 'flush', 'update', @@ -137,8 +137,8 @@ var commonMethods = [ commonMethods.map(function(methodName) { WindowsBinding.prototype[methodName] = function() { - var args = Array.prototype.slice.apply(arguments); - var cb = args[args.length - 1]; + const args = Array.prototype.slice.apply(arguments); + const cb = args[args.length - 1]; if (typeof cb !== 'function') { throw new TypeError('"cb" is not a function'); @@ -154,7 +154,7 @@ commonMethods.map(function(methodName) { Object.defineProperty(WindowsBinding.prototype, 'isOpen', { enumerable: true, - get: function() { + get() { return this.fd !== null; } }); diff --git a/lib/index.js b/lib/index.js index 52b4e16..8311a27 100644 --- a/lib/index.js +++ b/lib/index.js @@ -5,9 +5,9 @@ * @copyright Chris Williams */ -var SerialPort = require('./serialport'); -var Binding = require('./bindings-auto-detect'); -var parsers = require('./parsers'); +const SerialPort = require('./serialport'); +const Binding = require('./bindings-auto-detect'); +const parsers = require('./parsers'); SerialPort.Binding = Binding; SerialPort.parsers = parsers; diff --git a/lib/list-linux.js b/lib/list-linux.js index 1dc62a9..4e8399f 100644 --- a/lib/list-linux.js +++ b/lib/list-linux.js @@ -1,8 +1,8 @@ 'use strict'; -var childProcess = require('child_process'); -var fs = require('fs'); -var path = require('path'); +const childProcess = require('child_process'); +const fs = require('fs'); +const path = require('path'); function promisify(func) { return function(arg) { @@ -19,7 +19,7 @@ function promisify(func) { function promisedFilter(func) { return function(data) { - var shouldKeep = data.map(func); + const shouldKeep = data.map(func); return Promise.all(shouldKeep).then(function(keep) { return data.filter(function(path, index) { return keep[index]; @@ -28,16 +28,16 @@ function promisedFilter(func) { }; } -var statAsync = promisify(fs.stat); -var readdirAsync = promisify(fs.readdir); -var execAsync = promisify(childProcess.exec); +const statAsync = promisify(fs.stat); +const readdirAsync = promisify(fs.readdir); +const execAsync = promisify(childProcess.exec); function udevParser(output) { - var udevInfo = output.split('\n').reduce(function(info, line) { + const udevInfo = output.split('\n').reduce(function(info, line) { if (!line || line.trim() === '') { return info; } - var parts = line.split('=').map(function(part) { + const parts = line.split('=').map(function(part) { return part.trim(); }); @@ -46,7 +46,7 @@ function udevParser(output) { return info; }, {}); - var pnpId; + let pnpId; if (udevInfo.devlinks) { udevInfo.devlinks.split(' ').forEach(function(path) { if (path.indexOf('/by-id/') === -1) { return } @@ -54,23 +54,23 @@ function udevParser(output) { }); } - var vendorId = udevInfo.id_vendor_id; + let vendorId = udevInfo.id_vendor_id; if (vendorId && vendorId.substring(0, 2) !== '0x') { - vendorId = '0x' + vendorId; + vendorId = `0x${vendorId}`; } - var productId = udevInfo.id_model_id; + let productId = udevInfo.id_model_id; if (productId && productId.substring(0, 2) !== '0x') { - productId = '0x' + productId; + productId = `0x${productId}`; } return { comName: udevInfo.devname, manufacturer: udevInfo.id_vendor, serialNumber: udevInfo.id_serial, - pnpId: pnpId, - vendorId: vendorId, - productId: productId + pnpId, + vendorId, + productId }; } @@ -85,12 +85,12 @@ function checkPathAndDevice(path) { } function lookupPort(file) { - var udevadm = 'udevadm info --query=property -p $(udevadm info -q path -n ' + file + ')'; + const udevadm = `udevadm info --query=property -p $(udevadm info -q path -n ${file})`; return execAsync(udevadm).then(udevParser); } function listLinux(callback) { - var dirName = '/dev'; + const dirName = '/dev'; readdirAsync(dirName) .catch(function(err) { // if this directory is not found we just pretend everything is OK diff --git a/lib/parser-byte-length.js b/lib/parser-byte-length.js index eb59f29..2af7646 100644 --- a/lib/parser-byte-length.js +++ b/lib/parser-byte-length.js @@ -1,6 +1,6 @@ 'use strict'; -var Transform = require('stream').Transform; -var inherits = require('util').inherits; +const Transform = require('stream').Transform; +const inherits = require('util').inherits; function ByteLengthParser(options) { if (!(this instanceof ByteLengthParser)) { @@ -25,9 +25,9 @@ function ByteLengthParser(options) { inherits(ByteLengthParser, Transform); ByteLengthParser.prototype._transform = function(chunk, encoding, cb) { - var data = Buffer.concat([this.buffer, chunk]); + let data = Buffer.concat([this.buffer, chunk]); while (data.length >= this.length) { - var out = data.slice(0, this.length); + const out = data.slice(0, this.length); this.push(out); data = data.slice(this.length); } @@ -41,5 +41,4 @@ ByteLengthParser.prototype._flush = function(cb) { cb(); }; - module.exports = ByteLengthParser; diff --git a/lib/parser-delimiter.js b/lib/parser-delimiter.js index 2b15f66..93012d9 100644 --- a/lib/parser-delimiter.js +++ b/lib/parser-delimiter.js @@ -1,6 +1,6 @@ 'use strict'; -var Transform = require('stream').Transform; -var inherits = require('util').inherits; +const Transform = require('stream').Transform; +const inherits = require('util').inherits; function DelimiterParser(options) { if (!(this instanceof DelimiterParser)) { @@ -25,8 +25,8 @@ function DelimiterParser(options) { inherits(DelimiterParser, Transform); DelimiterParser.prototype._transform = function(chunk, encoding, cb) { - var data = Buffer.concat([this.buffer, chunk]); - var position; + let data = Buffer.concat([this.buffer, chunk]); + let position; while ((position = data.indexOf(this.delimiter)) !== -1) { this.push(data.slice(0, position)); data = data.slice(position + this.delimiter.length); diff --git a/lib/parser-readline.js b/lib/parser-readline.js index dcd8326..f4108ea 100644 --- a/lib/parser-readline.js +++ b/lib/parser-readline.js @@ -1,6 +1,6 @@ 'use strict'; -var DelimiterParser = require('./parser-delimiter'); -var inherits = require('util').inherits; +const DelimiterParser = require('./parser-delimiter'); +const inherits = require('util').inherits; function ReadlineParser(options) { if (!(this instanceof ReadlineParser)) { @@ -15,7 +15,7 @@ function ReadlineParser(options) { DelimiterParser.call(this, options); - var encoding = options.encoding || 'utf8'; + const encoding = options.encoding || 'utf8'; this.delimiter = new Buffer(options.delimiter, encoding); this.setEncoding(encoding); } diff --git a/lib/push-methods.js b/lib/push-methods.js index 8b68dc4..a34544e 100644 --- a/lib/push-methods.js +++ b/lib/push-methods.js @@ -1,7 +1,7 @@ 'use strict'; function allocNewPool(poolSize) { - var pool; + let pool; // performs better on node 6+ if (Buffer.allocUnsafe) { pool = Buffer.allocUnsafe(poolSize); @@ -21,13 +21,13 @@ function _read(bytesToRead) { // Grab another reference to the pool in the case that while we're // in the thread pool another read() finishes up the pool, and // allocates a new one. - var pool = this._pool; + const pool = this._pool; // Read the smaller of rest of the pool or however many bytes we want - var toRead = Math.min(pool.length - pool.used, bytesToRead); - var start = pool.used; + const toRead = Math.min(pool.length - pool.used, bytesToRead); + const start = pool.used; // the actual read. - var self = this; + const self = this; this.read(pool, start, toRead, function onRead(err, bytesRead) { if (err) { return this.disconnect(err); @@ -45,7 +45,7 @@ function pushBindingWrap(opt) { throw new TypeError('"push" is not a function'); } - var binding = opt.binding; + const binding = opt.binding; if (typeof binding._read !== 'function') { binding._read = _read; binding._readBufferSize = opt.readBufferSize || 1024; @@ -58,5 +58,4 @@ function pushBindingWrap(opt) { return binding; }; - module.exports = pushBindingWrap; diff --git a/lib/read-unix.js b/lib/read-unix.js index 11db74f..d50caf6 100644 --- a/lib/read-unix.js +++ b/lib/read-unix.js @@ -1,6 +1,6 @@ 'use strict'; -var fs = require('fs'); -var ReadPoller = require('bindings')('serialport.node').ReadPoller; +const fs = require('fs'); +const ReadPoller = require('bindings')('serialport.node').ReadPoller; module.exports = function readUnix(buffer, offset, length, cb) { if (typeof cb !== 'function') { @@ -28,9 +28,9 @@ module.exports = function readUnix(buffer, offset, length, cb) { return; } - var disconnectError = err && ( - err.code === 'EBADF' || // Bad file number means we got closed - err.code === 'ENXIO' || // No such device or address probably usb disconnect + const disconnectError = err && ( + err.code === 'EBADF' || // Bad file number means we got closed + err.code === 'ENXIO' || // No such device or address probably usb disconnect err.code === 'UNKNOWN' || // ¯\_(ツ)_/¯ does this ever happen? err.errno === -1 // generic error ); diff --git a/lib/serialport.js b/lib/serialport.js index 00ac515..9e75e0f 100644 --- a/lib/serialport.js +++ b/lib/serialport.js @@ -6,22 +6,22 @@ */ // 3rd Party Dependencies -var stream = require('stream'); -var debug = require('debug')('serialport:main'); +const stream = require('stream'); +const debug = require('debug')('serialport:main'); // Internal Dependencies -var mixInPushMethods = require('./push-methods'); +const mixInPushMethods = require('./push-methods'); // shims -var inherits = require('util').inherits; +const inherits = require('util').inherits; // VALIDATION ARRAYS -var DATABITS = [5, 6, 7, 8]; -var STOPBITS = [1, 1.5, 2]; -var PARITY = ['none', 'even', 'mark', 'odd', 'space']; -var FLOWCONTROLS = ['xon', 'xoff', 'xany', 'rtscts']; +const DATABITS = [5, 6, 7, 8]; +const STOPBITS = [1, 1.5, 2]; +const PARITY = ['none', 'even', 'mark', 'odd', 'space']; +const FLOWCONTROLS = ['xon', 'xoff', 'xany', 'rtscts']; -var defaultSettings = { +const defaultSettings = { autoOpen: true, baudRate: 9600, dataBits: 8, @@ -33,10 +33,10 @@ var defaultSettings = { xany: false, xoff: false, xon: false, - highWaterMark: 16 * 1024, + highWaterMark: 16 * 1024 }; -var defaultSetFlags = { +const defaultSetFlags = { brk: false, cts: false, dtr: true, @@ -107,13 +107,13 @@ function SerialPort(path, options, callback) { options = {}; } - var settings = Object.assign({}, defaultSettings, options); + const settings = Object.assign({}, defaultSettings, options); stream.Duplex.call(this, { highWaterMark: settings.highWaterMark }); - var Binding = settings.binding || SerialPort.Binding; + const Binding = settings.binding || SerialPort.Binding; if (!Binding) { throw new TypeError('No binding set, pass it as `options.binding` or set it on `SerialPort.Binding`'); @@ -124,38 +124,38 @@ function SerialPort(path, options, callback) { } if (typeof settings.baudRate !== 'number') { - throw new TypeError('Invalid "baudRate" must be a number got: ' + settings.baudRate); + throw new TypeError(`Invalid "baudRate" must be a number got: ${settings.baudRate}`); } if (DATABITS.indexOf(settings.dataBits) === -1) { - throw new TypeError('Invalid "databits": ' + settings.dataBits); + throw new TypeError(`Invalid "databits": ${settings.dataBits}`); } if (STOPBITS.indexOf(settings.stopBits) === -1) { - throw new TypeError('Invalid "stopbits": ' + settings.stopbits); + throw new TypeError(`Invalid "stopbits": ${settings.stopbits}`); } if (PARITY.indexOf(settings.parity) === -1) { - throw new TypeError('Invalid "parity": ' + settings.parity); + throw new TypeError(`Invalid "parity": ${settings.parity}`); } FLOWCONTROLS.forEach(function(control) { if (typeof settings[control] !== 'boolean') { - throw new TypeError('Invalid "' + control + '" is not boolean'); + throw new TypeError(`Invalid "${control}" is not boolean`); } }); - var push = this.push.bind(this); - var binding = new Binding({ + const push = this.push.bind(this); + let binding = new Binding({ disconnect: this._disconnected.bind(this), - push: push, + push, readBufferSize: settings.highWaterMark, bindingOptions: settings.bindingOptions }); binding = mixInPushMethods({ - binding: binding, - push: push, + binding, + push, readBufferSize: settings.highWaterMark }); @@ -186,13 +186,13 @@ inherits(SerialPort, stream.Duplex); Object.defineProperties(SerialPort.prototype, { 'isOpen': { enumerable: true, - get: function() { + get() { return this.binding.isOpen && !this.closing; } }, 'baudRate': { enumerable: true, - get: function() { + get() { return this.settings.baudRate; } } @@ -212,7 +212,7 @@ SerialPort.prototype._error = function(error, callback) { }; SerialPort.prototype._asyncError = function(error, callback) { - process.nextTick(this._error.bind(this, error,callback)); + process.nextTick(this._error.bind(this, error, callback)); }; /** @@ -235,7 +235,7 @@ SerialPort.prototype.open = function(callback) { } this.opening = true; - debug('open', 'path: ' + this.path); + debug('open', `path: ${this.path}`); this.binding.open(this.path, this.settings, function afterOpen(err) { this.opening = false; if (err) { @@ -259,10 +259,10 @@ SerialPort.prototype.update = function(options, callback) { return this._asyncError(new Error('Port is not open'), callback); } - var settings = Object.assign({}, defaultSettings, options); + const settings = Object.assign({}, defaultSettings, options); this.settings.baudRate = settings.baudRate; - debug('update', 'baudRate: ' + settings.baudRate); + debug('update', `baudRate: ${settings.baudRate}`); this.binding.update(this.settings, function afterUpdate(err) { if (err) { return this._error(err, callback); @@ -285,7 +285,7 @@ Even though serialport is a stream, when writing it can accept arrays of bytes i * @param {function=} callback Called once the write operation finishes. Data may not yet be flushed to the underlying port, no arguments. * @returns {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. */ -var superWrite = SerialPort.prototype.write; +const superWrite = SerialPort.prototype.write; SerialPort.prototype.write = function(data, encoding, callback) { if (Array.isArray(data)) { data = new Buffer(data); @@ -304,7 +304,7 @@ SerialPort.prototype._write = function(data, encoding, callback) { data = new Buffer(data, encoding); } - debug('_write', data.length + ' bytes of data'); + debug('_write', `${data.length} bytes of data`); this.binding.write(data, callback); }; @@ -332,7 +332,7 @@ SerialPort.prototype._writev = function(data, callback) { */ SerialPort.prototype._read = function(bytes) { - if(!this.isOpen) { + if (!this.isOpen) { this.once('open', function afterOpenRead() { this.binding._read(bytes); }); @@ -406,7 +406,7 @@ SerialPort.prototype.set = function(options, callback) { options = {}; } - var settings = Object.assign({}, defaultSetFlags, options); + const settings = Object.assign({}, defaultSetFlags, options); debug('set', settings); this.binding.set(settings, function afterSet(err) { if (err) { diff --git a/package.json b/package.json index f11cb65..cb568f6 100644 --- a/package.json +++ b/package.json @@ -62,9 +62,9 @@ "devDependencies": { "chai": "^3.5.0", "chai-subset": "^1.2.2", - "eslint": "^3.12.1", - "eslint-config-standard": "^6.2.0", - "eslint-plugin-promise": "^3.0.0", + "eslint": "^3.12.2", + "eslint-config-standard": "^6.2.1", + "eslint-plugin-promise": "^3.4.0", "eslint-plugin-standard": "^2.0.1", "istanbul": "^0.4.4", "jsdoc-to-markdown": "^2.0.1", @@ -77,7 +77,7 @@ "node-pre-gyp" ], "engines": { - "node": ">= 0.10.0" + "node": ">= 4.0.0" }, "bin": { "serialport-list": "./bin/serialport-list.js", @@ -89,7 +89,7 @@ "docs": "jsdoc2md --no-cache -t .docs/README.hbs --partial .docs/sig-name.hbs --partial .docs/sig-link.hbs --partial .docs/edit-warning.hbs -r table --separators --name-format lib/* > README.md", "docs:diff": "jsdoc2md --no-cache -t .docs/README.hbs --partial .docs/sig-name.hbs --partial .docs/sig-link.hbs --partial .docs/edit-warning.hbs -r table --separators --name-format lib/* | diff -q README.md - || (echo 'Docs out of date, run `npm run docs` and commit the new README.md' && false)", "install": "node-pre-gyp install --fallback-to-build", - "lint": "eslint *.js lib/**/*.js test/**/*.js bin/**/*.js examples/**/*.js", + "lint": "eslint lib test bin examples", "rebuild-all": "npm rebuild && node-gyp rebuild", "stress": "mocha --no-timeouts test/arduinoTest/stress.js", "test": "istanbul cover ./node_modules/mocha/bin/_mocha", diff --git a/test/arduinoTest/serialDuplexTest.js b/test/arduinoTest/serialDuplexTest.js index 8ea9d09..5310b3b 100755 --- a/test/arduinoTest/serialDuplexTest.js +++ b/test/arduinoTest/serialDuplexTest.js @@ -7,8 +7,8 @@ Tests the functionality of the serial port library. To be used in conjunction with the Arduino sketch ArduinoEcho.ino */ 'use strict'; -var SerialPort = require('../../'); -var args = require('commander'); +const SerialPort = require('../../'); +const args = require('commander'); args .usage('-p ') @@ -22,15 +22,15 @@ if (!args.port) { process.exit(-1); } -var port = new SerialPort(args.port); // open the serial port: -var output = 32; // ASCII space; lowest printable character -var byteCount = 0; // number of bytes read +const port = new SerialPort(args.port); // open the serial port: +let output = 32; // ASCII space; lowest printable character +let byteCount = 0; // number of bytes read function onOpen() { console.log('Port Open'); - console.log('Baud Rate: ' + port.options.baudRate); - var outString = String.fromCharCode(output); - console.log('Sent:\t\t' + outString); + console.log(`Baud Rate: ${port.options.baudRate}`); + const outString = String.fromCharCode(output); + console.log(`Sent:\t\t${outString}`); port.write(outString); } @@ -40,12 +40,12 @@ function onData(data) { } else { output = 32; // lowest printable character: space } - console.log('Received:\t' + data); - console.log('Read Events:\t' + byteCount); + console.log(`Received:\t${data}`); + console.log(`Read Events:\t${byteCount}`); byteCount++; - var outString = String.fromCharCode(output); + const outString = String.fromCharCode(output); port.write(outString); - console.log('Sent:\t\t' + outString); + console.log(`Sent:\t\t${outString}`); } function onClose() { @@ -54,7 +54,7 @@ function onClose() { } function onError(error) { - console.log('there was an error with the serial port: ' + error); + console.log(`there was an error with the serial port: ${error}`); process.exit(1); } diff --git a/test/arduinoTest/stress.js b/test/arduinoTest/stress.js index f13b252..e2cbee5 100644 --- a/test/arduinoTest/stress.js +++ b/test/arduinoTest/stress.js @@ -2,23 +2,24 @@ // `npm run stress` to run these tests -var assert = require('chai').assert; -var util = require('util'); -var SerialPort = require('../../'); +const assert = require('chai').assert; +const util = require('util'); +const SerialPort = require('../../'); require('colors'); // this modifies String.prototype // var fs = require('fs'); // Installing memwatch-next via package.json fails on node 10 on linux on our CI; // Pending https://github.com/marcominetti/node-memwatch/issues/15 +let memwatch; try { - var memwatch = require('memwatch-next'); + memwatch = require('memwatch-next'); } catch (e) { console.error('Please install memwatch-next to use the stress tests'); process.exit(-1); } describe('the stress', function() { - var testPort = process.env.TEST_PORT; + const testPort = process.env.TEST_PORT; if (!testPort) { it('cannot be tested as we have no test ports'); @@ -32,15 +33,15 @@ describe('the stress', function() { } it("doesn't leak memory", function(done) { - var data = new Buffer(1024); - var hd = new memwatch.HeapDiff(); - var port = new SerialPort(testPort, {}, false); + const data = new Buffer(1024); + const hd = new memwatch.HeapDiff(); + const port = new SerialPort(testPort, {}, false); port.on('close', done); - var leaks = 0; + let leaks = 0; memwatch.on('leak', function(info) { // fs.appendFile('leak.log', util.inspect(info)); - console.log(util.inspect(info, {depth: 5}).red); + console.log(util.inspect(info, { depth: 5 }).red); leaks++; }); @@ -55,8 +56,8 @@ describe('the stress', function() { port.on('data', function() {}); - var writing = true; - var write = function() { + let writing = true; + const write = function() { if (!writing) { return } port.write(data, write); }; @@ -73,9 +74,9 @@ describe('the stress', function() { writing = false; if (leaks > 0) { - var diff = hd.end(); + const diff = hd.end(); // fs.appendFile('heapdiff.log', util.inspect(diff, {depth: 5})); - console.log(util.inspect(diff, {depth: 5}).red); + console.log(util.inspect(diff, { depth: 5 }).red); assert.fail('leak detected'); } port.close(); diff --git a/test/bindings.js b/test/bindings.js index 3b2d132..bcae711 100644 --- a/test/bindings.js +++ b/test/bindings.js @@ -1,8 +1,9 @@ 'use strict'; +/* eslint-disable no-new */ -var assert = require('chai').assert; +const assert = require('chai').assert; -var platform; +let platform; switch (process.platform) { case 'win32': platform = 'win32'; @@ -14,7 +15,7 @@ switch (process.platform) { platform = 'linux'; } -var defaultOpenOptions = { +const defaultOpenOptions = { baudRate: 9600, dataBits: 8, hupcl: true, @@ -27,7 +28,7 @@ var defaultOpenOptions = { xon: false }; -var defaultSetFlags = { +const defaultSetFlags = { brk: false, cts: false, dtr: true, @@ -35,7 +36,7 @@ var defaultSetFlags = { rts: true }; -var bindingsToTest = [ +const bindingsToTest = [ 'mock', platform ]; @@ -48,15 +49,15 @@ function disconnect(err) { // The echo firmware should respond with this data when it's // ready to echo. This allows for remote device bootup. // the default firmware is called arduinoEcho.ino -var readyData = new Buffer('READY'); +const readyData = new Buffer('READY'); // Test our mock binding and the binding for the platform we're running on bindingsToTest.forEach(function(bindingName) { - var binding = require('../lib/bindings-' + bindingName); - var testPort = process.env.TEST_PORT; + const binding = require(`../lib/bindings-${bindingName}`); + let testPort = process.env.TEST_PORT; if (bindingName === 'mock') { testPort = '/dev/exists'; - binding.createPort(testPort, { echo: true, readyData: readyData }); + binding.createPort(testPort, { echo: true, readyData }); } // eslint-disable-next-line no-use-before-define @@ -64,7 +65,7 @@ bindingsToTest.forEach(function(bindingName) { }); function testBinding(bindingName, Binding, testPort) { - describe('bindings-'+ bindingName, function() { + describe(`bindings-${bindingName}`, function() { describe('static method', function() { describe('.list', function() { it('returns an array', function(done) { @@ -83,7 +84,7 @@ function testBinding(bindingName, Binding, testPort) { console.log('no ports to test'); return done(); } - var obj = data[0]; + const obj = data[0]; Object.keys(obj).forEach(function(key) { assert.notEqual(obj[key], '', 'empty values should be undefined'); assert.isNotNull(obj[key], 'empty values should be undefined'); @@ -96,16 +97,16 @@ function testBinding(bindingName, Binding, testPort) { describe('constructor', function() { it('creates a binding object', function() { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); assert.instanceOf(binding, Binding); }); it('throws when missing disconnect callback', function(done) { try { - new Binding({}); - } catch(e) { + new Binding({ }); + } catch (e) { assert.instanceOf(e, TypeError); done(); } @@ -114,7 +115,7 @@ function testBinding(bindingName, Binding, testPort) { it('throws when not given an options object', function(done) { try { new Binding(); - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); done(); } @@ -128,10 +129,10 @@ function testBinding(bindingName, Binding, testPort) { return; } - var binding; + let binding; beforeEach(function() { binding = new Binding({ - disconnect: disconnect + disconnect }); }); @@ -152,10 +153,10 @@ function testBinding(bindingName, Binding, testPort) { describe('instance method', function() { describe('#open', function() { - var binding; + let binding; beforeEach(function() { binding = new Binding({ - disconnect: disconnect + disconnect }); }); @@ -171,7 +172,7 @@ function testBinding(bindingName, Binding, testPort) { it('throws when not given a path', function(done) { try { binding.open(''); - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); done(); } @@ -180,7 +181,7 @@ function testBinding(bindingName, Binding, testPort) { it('throws when not given options', function(done) { try { binding.open('COMBAD'); - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); done(); } @@ -189,7 +190,7 @@ function testBinding(bindingName, Binding, testPort) { it('throws when not given a callback', function(done) { try { binding.open('COMBAD', {}); - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); done(); } @@ -201,7 +202,7 @@ function testBinding(bindingName, Binding, testPort) { } it('cannot open if already open', function(done) { - var options = Object.assign({}, defaultOpenOptions, {lock: false}); + const options = Object.assign({}, defaultOpenOptions, { lock: false }); binding.open(testPort, options, function(err) { assert.isNull(err); binding.open(testPort, options, function(err) { @@ -223,7 +224,7 @@ function testBinding(bindingName, Binding, testPort) { it('doesn\'t supports a custom baudRates of 25000'); } else { it('supports a custom baudRate of 25000', function(done) { - var customRates = Object.assign({}, defaultOpenOptions, {baudRate: 25000}); + const customRates = Object.assign({}, defaultOpenOptions, { baudRate: 25000 }); binding.open(testPort, customRates, function(err) { assert.isNull(err); assert.equal(binding.isOpen, true); @@ -241,8 +242,8 @@ function testBinding(bindingName, Binding, testPort) { }); it('locks the port by default', function(done) { - var binding2 = new Binding({ - disconnect: disconnect + const binding2 = new Binding({ + disconnect }); binding.open(testPort, defaultOpenOptions, function(err) { @@ -261,9 +262,9 @@ function testBinding(bindingName, Binding, testPort) { it('Ports currently cannot be unlocked on windows'); } else { it('can unlock the port', function(done) { - var noLock = Object.assign({}, defaultOpenOptions, {lock: false}); - var binding2 = new Binding({ - disconnect: disconnect + const noLock = Object.assign({}, defaultOpenOptions, { lock: false }); + const binding2 = new Binding({ + disconnect }); binding.open(testPort, noLock, function(err) { @@ -286,10 +287,10 @@ function testBinding(bindingName, Binding, testPort) { }); describe('#close', function() { - var binding; + let binding; beforeEach(function() { binding = new Binding({ - disconnect: disconnect + disconnect }); }); @@ -319,11 +320,11 @@ function testBinding(bindingName, Binding, testPort) { describe('#update', function() { it('errors asynchronously when not open', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); - var zalgo = false; - binding.update({baudRate: 9600}, function(err) { + let zalgo = false; + binding.update({ baudRate: 9600 }, function(err) { assert.instanceOf(err, Error); done(); zalgo = true; @@ -336,10 +337,10 @@ function testBinding(bindingName, Binding, testPort) { return; } - var binding; + let binding; beforeEach(function(done) { binding = new Binding({ - disconnect: disconnect + disconnect }); binding.open(testPort, defaultOpenOptions, done); }); @@ -360,14 +361,14 @@ function testBinding(bindingName, Binding, testPort) { it('errors when not called with options', function(done) { try { binding.set(function() {}); - } catch(e) { + } catch (e) { assert.instanceOf(e, Error); done(); } }); it('updates baudRate', function(done) { - binding.update({baudRate: 57600}, done); + binding.update({ baudRate: 57600 }, done); }); // if (platform === 'win32') { @@ -386,10 +387,10 @@ function testBinding(bindingName, Binding, testPort) { describe('#write', function() { it('errors asynchronously when not open', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); - var zalgo = false; + let zalgo = false; binding.write(new Buffer([]), function(err) { assert.instanceOf(err, Error); done(); @@ -399,38 +400,38 @@ function testBinding(bindingName, Binding, testPort) { }); it('throws when not given a buffer', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); try { binding.write(null, function() {}); - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); done(); } }); it('throws when not given a callback', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); try { binding.write(new Buffer(1)); - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); done(); } }); if (!testPort) { - it('Cannot be tested as we have no test ports on ' + platform); + it(`Cannot be tested as we have no test ports on ${platform}`); return; } - var binding; + let binding; beforeEach(function(done) { binding = new Binding({ - disconnect: disconnect + disconnect }); binding.open(testPort, defaultOpenOptions, done); }); @@ -440,7 +441,7 @@ function testBinding(bindingName, Binding, testPort) { }); it('calls the write callback once after a small write', function(done) { - var data = new Buffer('simple write of 24 bytes'); + const data = new Buffer('simple write of 24 bytes'); binding.write(data, function(err) { assert.isNull(err); done(); @@ -449,7 +450,7 @@ function testBinding(bindingName, Binding, testPort) { it('calls the write callback once after a 5k write', function(done) { this.timeout(20000); - var data = new Buffer(1024 * 5); + const data = new Buffer(1024 * 5); binding.write(data, function(err) { assert.isNull(err); done(); @@ -459,10 +460,10 @@ function testBinding(bindingName, Binding, testPort) { describe('#drain', function() { it('errors asynchronously when not open', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); - var zalgo = false; + let zalgo = false; binding.drain(function(err) { assert.instanceOf(err, Error); done(); @@ -476,10 +477,10 @@ function testBinding(bindingName, Binding, testPort) { return; } - var binding; + let binding; beforeEach(function(done) { binding = new Binding({ - disconnect: disconnect + disconnect }); binding.open(testPort, defaultOpenOptions, done); }); @@ -498,10 +499,10 @@ function testBinding(bindingName, Binding, testPort) { describe('#flush', function() { it('errors asynchronously when not open', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); - var zalgo = false; + let zalgo = false; binding.flush(function(err) { assert.instanceOf(err, Error); done(); @@ -515,10 +516,10 @@ function testBinding(bindingName, Binding, testPort) { return; } - var binding; + let binding; beforeEach(function(done) { binding = new Binding({ - disconnect: disconnect + disconnect }); binding.open(testPort, defaultOpenOptions, done); }); @@ -534,10 +535,10 @@ function testBinding(bindingName, Binding, testPort) { describe('#set', function() { it('errors asynchronously when not open', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); - var zalgo = false; + let zalgo = false; binding.set(defaultSetFlags, function(err) { assert.instanceOf(err, Error); done(); @@ -548,12 +549,12 @@ function testBinding(bindingName, Binding, testPort) { }); it('throws when not called with options', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); try { binding.set(function() {}); - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); done(); } @@ -564,10 +565,10 @@ function testBinding(bindingName, Binding, testPort) { return; } - var binding; + let binding; beforeEach(function(done) { binding = new Binding({ - disconnect: disconnect + disconnect }); binding.open(testPort, defaultOpenOptions, done); }); @@ -585,11 +586,11 @@ function testBinding(bindingName, Binding, testPort) { // is left over on the pipe and isn't cleared when flushed on unix describe('#read', function() { it('errors asynchronously when not open', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); - var buffer = new Buffer(5); - var zalgo = false; + const buffer = new Buffer(5); + let zalgo = false; binding.read(buffer, 0, buffer.length, function(err, bytesRead, data) { assert.instanceOf(err, Error); assert.isUndefined(bytesRead); @@ -605,11 +606,11 @@ function testBinding(bindingName, Binding, testPort) { return; } - var binding; - var buffer; + let binding; + let buffer; beforeEach(function(done) { buffer = new Buffer(readyData.length); - binding = new Binding({disconnect: disconnect}); + binding = new Binding({ disconnect }); binding.open(testPort, defaultOpenOptions, done); }); @@ -642,10 +643,10 @@ function testBinding(bindingName, Binding, testPort) { describe('#get', function() { it('errors asynchronously when not open', function(done) { - var binding = new Binding({ - disconnect: disconnect + const binding = new Binding({ + disconnect }); - var zalgo = false; + let zalgo = false; binding.get(function(err, data) { assert.instanceOf(err, Error); assert.isUndefined(data); @@ -660,9 +661,9 @@ function testBinding(bindingName, Binding, testPort) { return; } - var binding; + let binding; beforeEach(function(done) { - binding = new Binding({disconnect: disconnect}); + binding = new Binding({ disconnect }); binding.open(testPort, defaultOpenOptions, done); }); @@ -684,8 +685,8 @@ function testBinding(bindingName, Binding, testPort) { describe('#disconnect', function() { it('calls the disconnect callback', function(done) { - var binding = new Binding({ - disconnect: function(err) { + const binding = new Binding({ + disconnect(err) { assert.instanceOf(err, Error); done(); } diff --git a/test/electron/main.js b/test/electron/main.js index 2bcf635..e728b05 100644 --- a/test/electron/main.js +++ b/test/electron/main.js @@ -1,9 +1,9 @@ 'use strict'; -var app = require('electron').app; +const app = require('electron').app; try { - var serialport = require('../..'); // eslint-disable-line no-unused-vars + const serialport = require('../..'); // eslint-disable-line no-unused-vars } catch (e) { console.error('Error loading serialport'); console.error(e); diff --git a/test/integration.js b/test/integration.js index 751ddde..188ee3f 100644 --- a/test/integration.js +++ b/test/integration.js @@ -1,9 +1,9 @@ 'use strict'; -var crypto = require('crypto'); -var assert = require('chai').assert; -var SerialPort = require('../'); +const crypto = require('crypto'); +const assert = require('chai').assert; +const SerialPort = require('../'); -var platform; +let platform; switch (process.platform) { case 'win32': platform = 'win32'; @@ -15,14 +15,14 @@ switch (process.platform) { platform = 'unix'; } -var readyData = new Buffer('READY'); +const readyData = new Buffer('READY'); // test everything on our mock biding and natively -var defaultBinding = SerialPort.Binding; -var mockBinding = require('../lib/bindings-mock'); +const defaultBinding = SerialPort.Binding; +const mockBinding = require('../lib/bindings-mock'); -var mockTestPort = '/dev/exists'; -mockBinding.createPort(mockTestPort, { echo: true, readyData: readyData }); +const mockTestPort = '/dev/exists'; +mockBinding.createPort(mockTestPort, { echo: true, readyData }); // eslint-disable-next-line no-use-before-define integrationTest('mock', mockTestPort, mockBinding); @@ -33,9 +33,9 @@ integrationTest(platform, process.env.TEST_PORT, defaultBinding); // Be careful to close the ports when you're done with them // Ports are by default exclusively locked so a failure fails all tests function integrationTest(platform, testPort, binding) { - describe(platform + ' SerialPort Integration Tests', function() { + describe(`${platform} SerialPort Integration Tests`, function() { if (!testPort) { - it(platform + ' tests requires an Arduino loaded with the arduinoEcho program on a serialport set to the TEST_PORT env var'); + it(`${platform} tests requires an Arduino loaded with the arduinoEcho program on a serialport set to the TEST_PORT env var`); return; } @@ -47,12 +47,13 @@ function integrationTest(platform, testPort, binding) { describe('.list', function() { it('contains the test port', function(done) { function lastPath(name) { - var parts = name.split('.'); + const parts = name.split('.'); return parts[parts.length - 1]; } SerialPort.list(function(err, ports) { - var foundPort = false; + assert.isNull(err); + let foundPort = false; ports.forEach(function(port) { if (lastPath(port.comName) === lastPath(testPort)) { foundPort = true; @@ -74,7 +75,7 @@ function integrationTest(platform, testPort, binding) { }); it('emits an error event when trying to open an invalid port', function(done) { - var port = new SerialPort('COM99'); + const port = new SerialPort('COM99'); port.on('error', function(err) { assert.instanceOf(err, Error); done(); @@ -84,7 +85,7 @@ function integrationTest(platform, testPort, binding) { describe('opening and closing', function() { it('can open and close', function(done) { - var port = new SerialPort(testPort); + const port = new SerialPort(testPort); port.on('open', function() { assert.isTrue(port.isOpen); port.close(); @@ -96,7 +97,7 @@ function integrationTest(platform, testPort, binding) { }); it('cannot be opened again after open', function(done) { - var port = new SerialPort(testPort, function(err) { + const port = new SerialPort(testPort, function(err) { assert.isNull(err); port.open(function(err) { assert.instanceOf(err, Error); @@ -106,7 +107,7 @@ function integrationTest(platform, testPort, binding) { }); it('cannot be opened while opening', function(done) { - var port = new SerialPort(testPort, { autoOpen: false }); + const port = new SerialPort(testPort, { autoOpen: false }); port.open(function(err) { assert.isNull(err); }); @@ -120,7 +121,7 @@ function integrationTest(platform, testPort, binding) { }); it('can open and close ports repetitively', function(done) { - var port = new SerialPort(testPort, { autoOpen: false }); + const port = new SerialPort(testPort, { autoOpen: false }); port.open(function(err) { assert.isNull(err); port.close(function(err) { @@ -140,8 +141,8 @@ function integrationTest(platform, testPort, binding) { } it('allows changing the baud rate of an open port', function(done) { - var port = new SerialPort(testPort, function() { - port.update({baudRate: 57600}, function(err) { + const port = new SerialPort(testPort, function() { + port.update({ baudRate: 57600 }, function(err) { assert.isNull(err); port.close(done); }); @@ -153,16 +154,16 @@ function integrationTest(platform, testPort, binding) { it('5k test', function(done) { this.timeout(20000); // 5k of random ascii - var output = new Buffer(crypto.randomBytes(5120).toString('ascii')); - var expectedInput = Buffer.concat([readyData, output]); - var port = new SerialPort(testPort); + const output = new Buffer(crypto.randomBytes(5120).toString('ascii')); + const expectedInput = Buffer.concat([readyData, output]); + const port = new SerialPort(testPort); // this will trigger from the "READY" the arduino sends when it's... ready port.once('data', function() { port.write(output); }); - var input = new Buffer(0); + let input = new Buffer(0); port.on('data', function(data) { input = Buffer.concat([input, data]); if (input.length >= expectedInput.length) { diff --git a/test/list-linux.js b/test/list-linux.js index 85e8ed9..2d45c33 100644 --- a/test/list-linux.js +++ b/test/list-linux.js @@ -1,9 +1,9 @@ 'use strict'; -var assert = require('chai').assert; -var listLinux = require('./mocks/list-linux'); +const assert = require('chai').assert; +const listLinux = require('./mocks/list-linux'); -var ports = { +const ports = { 'ttyS0': 'DEVNAME=/dev/ttyS0\n' + 'DEVPATH=/devices/platform/serial8250/tty/ttyS0\n' + @@ -35,7 +35,7 @@ var ports = { 'ttyNOTASERIALPORT': '' }; -var portOutput = [ +const portOutput = [ { comName: '/dev/ttyS0', manufacturer: undefined, diff --git a/test/manual-testing/memory-binding.js b/test/manual-testing/memory-binding.js index 40c2e36..6544b12 100644 --- a/test/manual-testing/memory-binding.js +++ b/test/manual-testing/memory-binding.js @@ -1,5 +1,5 @@ 'use strict'; -var port = process.env.TEST_PORT; +const port = process.env.TEST_PORT; if (!port) { console.error('Please pass TEST_PORT environment variable'); @@ -8,9 +8,9 @@ if (!port) { // var Binding = require('../../lib/bindings-mock'); // Binding.createPort(port); -var Binding = require('../../').Binding; +const Binding = require('../../').Binding; -var defaultOpenOptions = { +const defaultOpenOptions = { baudRate: 9600, dataBits: 8, hupcl: true, @@ -23,19 +23,19 @@ var defaultOpenOptions = { xon: false }; -var counter = 0; +let counter = 0; function makePort(err) { if (err) { throw err } counter++; if (counter % 1000 === 0) { - console.log('Attempt ' + counter); - debugger; + console.log(`Attempt ${counter}`); + // debugger; } if (counter > 10000) { process.exit(0); } - var binding = new Binding({disconnect: function() { throw 'disconnect' }}); + const binding = new Binding({ disconnect() { throw new Error('disconnect') } }); binding.open(port, defaultOpenOptions, function afterBindingOpen(err) { if (err) { throw err } binding.close(makePort); diff --git a/test/manual-testing/memory.js b/test/manual-testing/memory.js index 6fe6d16..ae69da1 100644 --- a/test/manual-testing/memory.js +++ b/test/manual-testing/memory.js @@ -1,26 +1,26 @@ 'use strict'; -var SerialPort = require('../../'); -var port = process.env.TEST_PORT; +const SerialPort = require('../../'); +const port = process.env.TEST_PORT; if (!port) { console.error('Please pass TEST_PORT environment variable'); process.exit(1); } -var counter = 0; +let counter = 0; function makePort(err) { if (err) { throw err } counter++; if (counter % 1000 === 0) { - console.log('Attempt ' + counter); - debugger; + console.log(`Attempt ${counter}`); + // debugger; } if (counter > 10000) { process.exit(0); } - var serialPort = new SerialPort(port, function(err) { + const serialPort = new SerialPort(port, function(err) { if (err) { throw err } serialPort.close(makePort); }); diff --git a/test/manual-testing/performance.js b/test/manual-testing/performance.js index e368eb4..3bcbb8c 100644 --- a/test/manual-testing/performance.js +++ b/test/manual-testing/performance.js @@ -1,7 +1,7 @@ 'use strict'; -var SerialPort = require('../../'); -var port = process.env.TEST_PORT; +const SerialPort = require('../../'); +const port = process.env.TEST_PORT; if (!port) { console.error('Please pass TEST_PORT environment variable'); @@ -11,11 +11,11 @@ if (!port) { // var Binding = require('../../lib/bindings-mock'); // Binding.createPort(port); // SerialPort.Binding = Binding; -debugger; +// debugger; -var writeData = new Buffer(50000).fill(1); +const writeData = new Buffer(50000).fill(1); -var serialPort = new SerialPort(port, { +const serialPort = new SerialPort(port, { // baudRate: 115200 }); @@ -24,7 +24,7 @@ serialPort.once('data', function onceData() { serialPort.write(writeData); }); -var recieved = 0; +let recieved = 0; serialPort.on('data', function onData(data) { recieved += data.length; if (recieved >= writeData.length) { diff --git a/test/mocks/list-linux.js b/test/mocks/list-linux.js index 7e148f7..d8196ea 100644 --- a/test/mocks/list-linux.js +++ b/test/mocks/list-linux.js @@ -2,15 +2,15 @@ 'use strict'; -var proxyquire = require('proxyquire'); +const proxyquire = require('proxyquire'); -var mockPorts = {}; -var characterDevice = true; -var error = false; +let mockPorts = {}; +let characterDevice = true; +let error = false; -var listLinux = proxyquire('../../lib/list-linux', { +const listLinux = proxyquire('../../lib/list-linux', { fs: { - readdir: function(path, cb) { + readdir(path, cb) { if (error) { return process.nextTick(function() { cb(new Error('Bad')); @@ -20,21 +20,21 @@ var listLinux = proxyquire('../../lib/list-linux', { cb(null, Object.keys(mockPorts)); }); }, - stat: function(path, cb) { + stat(path, cb) { process.nextTick(function() { - cb(null, { isCharacterDevice: function() { return characterDevice } }); + cb(null, { isCharacterDevice() { return characterDevice } }); }); } }, path: { // needed for testing on windows - join: function() { + join() { return Array.prototype.join.call(arguments, '/'); } }, child_process: { - exec: function(cmd, cb) { - var port = cmd.split(/\/dev\/(.*)\)/)[1]; + exec(cmd, cb) { + const port = cmd.split(/\/dev\/(.*)\)/)[1]; process.nextTick(function() { cb(null, mockPorts[port]); }); diff --git a/test/parser-byte-length.js b/test/parser-byte-length.js index 96392a7..b023fed 100644 --- a/test/parser-byte-length.js +++ b/test/parser-byte-length.js @@ -1,21 +1,22 @@ 'use strict'; +/* eslint-disable no-new */ -var assert = require('chai').assert; -var sinon = require('sinon'); +const assert = require('chai').assert; +const sinon = require('sinon'); -var ByteLengthParser = require('../lib/parser-byte-length'); +const ByteLengthParser = require('../lib/parser-byte-length'); describe('ByteLengthParser', function() { it('works without new', function() { // eslint-disable-next-line new-cap - var parser = ByteLengthParser({length: 4}); + const parser = ByteLengthParser({ length: 4 }); assert.instanceOf(parser, ByteLengthParser); }); it('emits data events every 8 bytes', function() { - var data = new Buffer('Robots are so freaking cool!'); - var spy = sinon.spy(); - var parser = new ByteLengthParser({length: 8}); + const data = new Buffer('Robots are so freaking cool!'); + const spy = sinon.spy(); + const parser = new ByteLengthParser({ length: 8 }); parser.on('data', spy); parser.write(data); assert.equal(spy.callCount, 3); @@ -47,8 +48,8 @@ describe('ByteLengthParser', function() { }); it('continues looking for bytes in additional writes', function() { - var parser = new ByteLengthParser({length: 4}); - var spy = sinon.spy(); + const parser = new ByteLengthParser({ length: 4 }); + const spy = sinon.spy(); parser.on('data', spy); parser.write(new Buffer('ab')); parser.write(new Buffer('cd')); diff --git a/test/parser-delimiter.js b/test/parser-delimiter.js index e776ec8..3918205 100644 --- a/test/parser-delimiter.js +++ b/test/parser-delimiter.js @@ -1,20 +1,21 @@ 'use strict'; +/* eslint-disable no-new */ -var assert = require('chai').assert; -var sinon = require('sinon'); +const assert = require('chai').assert; +const sinon = require('sinon'); -var DelimiterParser = require('../lib/parser-delimiter'); +const DelimiterParser = require('../lib/parser-delimiter'); describe('DelimiterParser', function() { it('works without new', function() { // eslint-disable-next-line new-cap - var parser = DelimiterParser({delimiter: new Buffer('4')}); + const parser = DelimiterParser({ delimiter: new Buffer('4') }); assert.instanceOf(parser, DelimiterParser); }); it('transforms data to strings split on a delimiter', function() { - var spy = sinon.spy(); - var parser = new DelimiterParser({ + const spy = sinon.spy(); + const parser = new DelimiterParser({ delimiter: new Buffer('\n') }); parser.on('data', spy); @@ -57,21 +58,21 @@ describe('DelimiterParser', function() { }); it('allows setting of the delimiter with a string', function() { - new DelimiterParser({delimiter: 'string'}); + new DelimiterParser({ delimiter: 'string' }); }); it('allows setting of the delimiter with a buffer', function() { - new DelimiterParser({delimiter: new Buffer([1])}); + new DelimiterParser({ delimiter: new Buffer([1]) }); }); it('allows setting of the delimiter with an array of bytes', function() { - new DelimiterParser({delimiter: [1]}); + new DelimiterParser({ delimiter: [1] }); }); it('emits data events every time it meets 00x 00x', function() { - var data = new Buffer('This could be\0\0binary data\0\0sent from a Moteino\0\0'); - var parser = new DelimiterParser({delimiter: [0, 0]}); - var spy = sinon.spy(); + const data = new Buffer('This could be\0\0binary data\0\0sent from a Moteino\0\0'); + const parser = new DelimiterParser({ delimiter: [0, 0] }); + const spy = sinon.spy(); parser.on('data', spy); parser.write(data); assert.equal(spy.callCount, 3); @@ -81,35 +82,35 @@ describe('DelimiterParser', function() { }); it('accepts single byte delimiter', function() { - var data = new Buffer('This could be\0binary data\0sent from a Moteino\0'); - var parser = new DelimiterParser({delimiter: [0]}); - var spy = sinon.spy(); + const data = new Buffer('This could be\0binary data\0sent from a Moteino\0'); + const parser = new DelimiterParser({ delimiter: [0] }); + const spy = sinon.spy(); parser.on('data', spy); parser.write(data); assert.equal(spy.callCount, 3); }); it('Works when buffer starts with delimiter', function() { - var data = new Buffer('\0Hello\0World\0'); - var parser = new DelimiterParser({delimiter: new Buffer([0])}); - var spy = sinon.spy(); + const data = new Buffer('\0Hello\0World\0'); + const parser = new DelimiterParser({ delimiter: new Buffer([0]) }); + const spy = sinon.spy(); parser.on('data', spy); parser.write(data); assert.equal(spy.callCount, 2); }); it('should only emit if delimiters are strictly in row', function() { - var data = new Buffer('\0Hello\u0001World\0\0\u0001'); - var parser = new DelimiterParser({delimiter: [0, 1]}); - var spy = sinon.spy(); + const data = new Buffer('\0Hello\u0001World\0\0\u0001'); + const parser = new DelimiterParser({ delimiter: [0, 1] }); + const spy = sinon.spy(); parser.on('data', spy); parser.write(data); assert.equal(spy.callCount, 1); }); it('continues looking for delimiters in the next buffers', function() { - var parser = new DelimiterParser({delimiter: [0, 0]}); - var spy = sinon.spy(); + const parser = new DelimiterParser({ delimiter: [0, 0] }); + const spy = sinon.spy(); parser.on('data', spy); parser.write(new Buffer('This could be\0\0binary ')); parser.write(new Buffer('data\0\0sent from a Moteino\0\0')); diff --git a/test/parser-readline.js b/test/parser-readline.js index 267fc0a..e6051e5 100644 --- a/test/parser-readline.js +++ b/test/parser-readline.js @@ -1,20 +1,21 @@ 'use strict'; +/* eslint-disable no-new */ -var assert = require('chai').assert; -var sinon = require('sinon'); +const assert = require('chai').assert; +const sinon = require('sinon'); -var ReadlineParser = require('../lib/parser-readline'); +const ReadlineParser = require('../lib/parser-readline'); describe('ReadlineParser', function() { it('works without new', function() { // eslint-disable-next-line new-cap - var parser = ReadlineParser(); + const parser = ReadlineParser(); assert.instanceOf(parser, ReadlineParser); }); it('transforms data to strings split on a delimiter', function() { - var spy = sinon.spy(); - var parser = new ReadlineParser(); + const spy = sinon.spy(); + const parser = new ReadlineParser(); parser.on('data', spy); parser.write(new Buffer('I love robots\nEach ')); parser.write(new Buffer('and Every One\n')); @@ -28,8 +29,8 @@ describe('ReadlineParser', function() { }); it('allows setting of the delimiter with a string', function() { - var spy = sinon.spy(); - var parser = new ReadlineParser({delimiter: 'a'}); + const spy = sinon.spy(); + const parser = new ReadlineParser({ delimiter: 'a' }); parser.on('data', spy); parser.write(new Buffer('how are youa')); assert(spy.calledWith('how ')); @@ -37,8 +38,8 @@ describe('ReadlineParser', function() { }); it('allows setting of the delimiter with a buffer', function() { - var spy = sinon.spy(); - var parser = new ReadlineParser({delimiter: new Buffer('a')}); + const spy = sinon.spy(); + const parser = new ReadlineParser({ delimiter: new Buffer('a') }); parser.on('data', spy); parser.write(new Buffer('how are youa')); assert(spy.calledWith('how ')); @@ -46,8 +47,8 @@ describe('ReadlineParser', function() { }); it('allows setting of the delimiter with an array of bytes', function() { - var spy = sinon.spy(); - var parser = new ReadlineParser({delimiter: [97]}); + const spy = sinon.spy(); + const parser = new ReadlineParser({ delimiter: [97] }); parser.on('data', spy); parser.write(new Buffer('how are youa')); assert(spy.calledWith('how ')); @@ -55,8 +56,8 @@ describe('ReadlineParser', function() { }); it('allows setting of encoding', function() { - var spy = sinon.spy(); - var parser = new ReadlineParser({ + const spy = sinon.spy(); + const parser = new ReadlineParser({ encoding: 'hex' }); parser.on('data', spy); @@ -66,8 +67,8 @@ describe('ReadlineParser', function() { }); it('encoding should be reflected in a string delimiter', function() { - var spy = sinon.spy(); - var parser = new ReadlineParser({ + const spy = sinon.spy(); + const parser = new ReadlineParser({ delimiter: 'FF', encoding: 'hex' }); @@ -98,20 +99,20 @@ describe('ReadlineParser', function() { }); it('allows setting of the delimiter with a string', function() { - new ReadlineParser({delimiter: 'string'}); + new ReadlineParser({ delimiter: 'string' }); }); it('allows setting of the delimiter with a buffer', function() { - new ReadlineParser({delimiter: new Buffer([1])}); + new ReadlineParser({ delimiter: new Buffer([1]) }); }); it('allows setting of the delimiter with an array of bytes', function() { - new ReadlineParser({delimiter: [1]}); + new ReadlineParser({ delimiter: [1] }); }); it('doesn\'t emits empty data events', function() { - var spy = sinon.spy(); - var parser = new ReadlineParser({delimiter: 'a'}); + const spy = sinon.spy(); + const parser = new ReadlineParser({ delimiter: 'a' }); parser.on('data', spy); parser.write(new Buffer('aFa')); assert(spy.calledOnce); diff --git a/test/push-methods.js b/test/push-methods.js index 0cc3cb7..04ba575 100644 --- a/test/push-methods.js +++ b/test/push-methods.js @@ -1,13 +1,14 @@ 'use strict'; +/* eslint-disable no-new */ -var assert = require('chai').assert; -var pushBindingWrap = require('../lib/push-methods'); -var MockBinding = require('../lib/bindings-mock'); +const assert = require('chai').assert; +const pushBindingWrap = require('../lib/push-methods'); +const MockBinding = require('../lib/bindings-mock'); describe('pushBindingWrap()', function() { it('throws when not passed a binding', function(done) { try { - pushBindingWrap({push: function() {}}); + pushBindingWrap({ push() {} }); } catch (e) { assert.instanceOf(e, TypeError); done(); @@ -16,7 +17,7 @@ describe('pushBindingWrap()', function() { it('throws when not passed a push function', function(done) { try { - pushBindingWrap({binding: {}}); + pushBindingWrap({ binding: {} }); } catch (e) { assert.instanceOf(e, TypeError); done(); @@ -24,27 +25,27 @@ describe('pushBindingWrap()', function() { }); it('assigns `_read()` only if not already a method', function(done) { - var mockBinding = new MockBinding({disconnect: function() {}}); + const mockBinding = new MockBinding({ disconnect() {} }); assert.isUndefined(mockBinding._read); - pushBindingWrap({ binding: mockBinding, push: function() {}}); + pushBindingWrap({ binding: mockBinding, push() {} }); assert.equal(typeof mockBinding._read, 'function'); - var _read = function() {}; - var fakeBinding = { _read: _read}; - pushBindingWrap({ binding: fakeBinding, push: function() {}}); + const _read = function() {}; + const fakeBinding = { _read }; + pushBindingWrap({ binding: fakeBinding, push() {} }); assert.equal(fakeBinding._read, _read); done(); }); it('assigns `push()` only if not already a method', function(done) { - var mockBinding = new MockBinding({disconnect: function() {}}); + const mockBinding = new MockBinding({ disconnect() {} }); assert.isUndefined(mockBinding.push); - pushBindingWrap({ binding: mockBinding, push: function() {}}); + pushBindingWrap({ binding: mockBinding, push() {} }); assert.equal(typeof mockBinding.push, 'function'); - var push = function() {}; - var fakeBinding = { push: push}; - pushBindingWrap({ binding: fakeBinding, push: function() {}}); + const push = function() {}; + const fakeBinding = { push }; + pushBindingWrap({ binding: fakeBinding, push() {} }); assert.equal(fakeBinding.push, push); done(); }); @@ -52,9 +53,9 @@ describe('pushBindingWrap()', function() { describe('_read()', function() { it('calls `read()` with the right arguments', function(done) { - var bytesToRead = 5; - var fakeBinding = { - read: function(buffer, offset, bytes) { + const bytesToRead = 5; + const fakeBinding = { + read(buffer, offset, bytes) { assert.instanceOf(buffer, Buffer); assert.isNumber(offset); assert.isNumber(bytes); @@ -62,24 +63,24 @@ describe('_read()', function() { done(); } }; - pushBindingWrap({binding: fakeBinding, push: function() {}}); + pushBindingWrap({ binding: fakeBinding, push() {} }); fakeBinding._read(bytesToRead); }); it('calls push with available data', function(done) { - var readData = new Buffer('12345!'); - var fakeBinding = { - read: function(buffer, offset, bytes, cb) { + const readData = new Buffer('12345!'); + const fakeBinding = { + read(buffer, offset, bytes, cb) { readData.copy(buffer, offset); process.nextTick(cb.bind(null, null, readData.length, buffer)); }, - push: function(data) { + push(data) { assert.deepEqual(data, readData); done(); return false; } }; - pushBindingWrap({binding: fakeBinding, push: function() {}}); + pushBindingWrap({ binding: fakeBinding, push() {} }); fakeBinding._read(6); }); }); diff --git a/test/serialport.js b/test/serialport.js index ccb1066..4d4bda0 100644 --- a/test/serialport.js +++ b/test/serialport.js @@ -1,15 +1,15 @@ 'use strict'; -var sinon = require('sinon'); -var chai = require('chai'); +const sinon = require('sinon'); +const chai = require('chai'); chai.use(require('chai-subset')); -var assert = chai.assert; +const assert = chai.assert; -var SerialPort = require('../lib/serialport'); -var mockBinding = require('../lib/bindings-mock'); +const SerialPort = require('../lib/serialport'); +const mockBinding = require('../lib/bindings-mock'); describe('SerialPort', function() { - var sandbox; + let sandbox; beforeEach(function() { SerialPort.Binding = mockBinding; @@ -26,7 +26,7 @@ describe('SerialPort', function() { describe('constructor', function() { it('provides auto construction', function(done) { - var serialPort = SerialPort; + const serialPort = SerialPort; this.port = serialPort('/dev/exists', done); }); @@ -39,12 +39,12 @@ describe('SerialPort', function() { }); it('emits the open event', function(done) { - var port = new SerialPort('/dev/exists'); + const port = new SerialPort('/dev/exists'); port.on('open', done); }); it("doesn't open if told not to", function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); + const port = new SerialPort('/dev/exists', { autoOpen: false }); port.on('open', function() { throw new Error("this shouldn't be opening"); }); @@ -62,7 +62,7 @@ describe('SerialPort', function() { // is this a test for open? it('emits an error when an bad port is provided', function(done) { - var port = new SerialPort('/bad/port'); + const port = new SerialPort('/bad/port'); port.once('error', function(err) { assert.instanceOf(err, Error); done(); @@ -73,7 +73,7 @@ describe('SerialPort', function() { SerialPort.Binding = undefined; try { this.port = new SerialPort('/dev/exists'); - } catch(err) { + } catch (err) { assert.instanceOf(err, Error); done(); } @@ -82,7 +82,7 @@ describe('SerialPort', function() { it('throws an error when no port is provided', function(done) { try { this.port = new SerialPort(''); - } catch(err) { + } catch (err) { assert.instanceOf(err, Error); done(); } @@ -90,8 +90,8 @@ describe('SerialPort', function() { it('throws an error when given bad options even with a callback', function(done) { try { - this.port = new SerialPort('/dev/exists', { baudRate: 'whatever'}, function() {}); - } catch(err) { + this.port = new SerialPort('/dev/exists', { baudRate: 'whatever' }, function() {}); + } catch (err) { assert.instanceOf(err, Error); done(); } @@ -99,8 +99,8 @@ describe('SerialPort', function() { it('errors with a non number baudRate', function(done) { try { - this.port = new SerialPort('/bad/port', { baudRate: 'whatever'}); - } catch(err) { + this.port = new SerialPort('/bad/port', { baudRate: 'whatever' }); + } catch (err) { assert.instanceOf(err, Error); done(); } @@ -109,7 +109,7 @@ describe('SerialPort', function() { it('errors with invalid databits', function(done) { try { this.port = new SerialPort('/dev/exists', { dataBits: 19 }); - } catch(err) { + } catch (err) { assert.instanceOf(err, Error); done(); } @@ -118,7 +118,7 @@ describe('SerialPort', function() { it('errors with invalid stopbits', function(done) { try { this.port = new SerialPort('/dev/exists', { stopBits: 19 }); - } catch(err) { + } catch (err) { assert.instanceOf(err, Error); done(); } @@ -127,7 +127,7 @@ describe('SerialPort', function() { it('errors with invalid parity', function(done) { try { this.port = new SerialPort('/dev/exists', { parity: 'pumpkins' }); - } catch(err) { + } catch (err) { assert.instanceOf(err, Error); done(); } @@ -136,21 +136,21 @@ describe('SerialPort', function() { it('errors with invalid flow control', function(done) { try { this.port = new SerialPort('/dev/exists', { xon: 'pumpkins' }); - } catch(err) { + } catch (err) { assert.instanceOf(err, Error); done(); } }); it('sets valid flow control individually', function(done) { - var options = { + const options = { xon: true, xoff: true, xany: true, rtscts: true, autoOpen: false }; - var port = new SerialPort('/dev/exists', options); + const port = new SerialPort('/dev/exists', options); assert.isTrue(port.settings.xon); assert.isTrue(port.settings.xoff); assert.isTrue(port.settings.xany); @@ -166,11 +166,11 @@ describe('SerialPort', function() { describe('property', function() { describe('.baudRate', function() { it('is a read only property set during construction', function() { - var port = new SerialPort('/dev/exists', {autoOpen: false, baudRate: 14400 }); + const port = new SerialPort('/dev/exists', { autoOpen: false, baudRate: 14400 }); assert.equal(port.baudRate, 14400); try { port.baudRate = 9600; - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); } assert.equal(port.baudRate, 14400); @@ -179,11 +179,11 @@ describe('SerialPort', function() { describe('.path', function() { it('is a read only property set during construction', function() { - var port = new SerialPort('/dev/exists', {autoOpen: false}); + const port = new SerialPort('/dev/exists', { autoOpen: false }); assert.equal(port.path, '/dev/exists'); try { port.path = 'foo'; - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); } assert.equal(port.path, '/dev/exists'); @@ -192,24 +192,24 @@ describe('SerialPort', function() { describe('.isOpen', function() { it('is a read only property', function() { - var port = new SerialPort('/dev/exists', {autoOpen: false}); + const port = new SerialPort('/dev/exists', { autoOpen: false }); assert.equal(port.isOpen, false); try { port.isOpen = 'foo'; - } catch(e) { + } catch (e) { assert.instanceOf(e, TypeError); } assert.equal(port.isOpen, false); }); it('returns false when the port is created', function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); + const port = new SerialPort('/dev/exists', { autoOpen: false }); assert.isFalse(port.isOpen); done(); }); it('returns false when the port is opening', function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); + const port = new SerialPort('/dev/exists', { autoOpen: false }); sandbox.stub(port.binding, 'open', function() { assert.isTrue(port.opening); assert.isFalse(port.isOpen); @@ -219,15 +219,14 @@ describe('SerialPort', function() { }); it('returns true when the port is open', function(done) { - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { assert.isTrue(port.isOpen); done(); }); }); it('returns false when the port is closing', function(done) { - var port; - port = new SerialPort('/dev/exists', {}, function() { + const port = new SerialPort('/dev/exists', {}, function() { sandbox.stub(this.binding, 'close', function() { assert.isFalse(port.isOpen); done(); @@ -237,7 +236,7 @@ describe('SerialPort', function() { }); it('returns false when the port is closed', function(done) { - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { port.close(); }); port.on('close', function() { @@ -251,8 +250,8 @@ describe('SerialPort', function() { describe('instance method', function() { describe('#open', function() { it('passes the port to the bindings', function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); - var openSpy = sandbox.spy(port.binding, 'open'); + const port = new SerialPort('/dev/exists', { autoOpen: false }); + const openSpy = sandbox.spy(port.binding, 'open'); assert.isFalse(port.isOpen); port.open(function(err) { assert.isNull(err); @@ -263,7 +262,7 @@ describe('SerialPort', function() { }); it('passes default options to the bindings', function(done) { - var defaultOptions = { + const defaultOptions = { baudRate: 9600, parity: 'none', xon: false, @@ -274,7 +273,7 @@ describe('SerialPort', function() { dataBits: 8, stopBits: 1 }; - var port = new SerialPort('/dev/exists', { autoOpen: false }); + const port = new SerialPort('/dev/exists', { autoOpen: false }); sandbox.stub(port.binding, 'open', function(path, opt, cb) { assert.equal(path, '/dev/exists'); assert.containSubset(opt, defaultOptions); @@ -285,7 +284,7 @@ describe('SerialPort', function() { }); it('calls back an error when opening an invalid port', function(done) { - var port = new SerialPort('/dev/unhappy', { autoOpen: false }); + const port = new SerialPort('/dev/unhappy', { autoOpen: false }); port.open(function(err) { assert.instanceOf(err, Error); done(); @@ -293,8 +292,8 @@ describe('SerialPort', function() { }); it('emits data after being reopened', function(done) { - var data = new Buffer('Howdy!'); - var port = new SerialPort('/dev/exists', function() { + const data = new Buffer('Howdy!'); + const port = new SerialPort('/dev/exists', function() { port.close(function() { port.open(function() { port.binding.write(data, function() { @@ -309,7 +308,7 @@ describe('SerialPort', function() { }); it('cannot be opened again after open', function(done) { - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { port.open(function(err) { assert.instanceOf(err, Error); done(); @@ -318,7 +317,7 @@ describe('SerialPort', function() { }); it('cannot be opened while opening', function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); + const port = new SerialPort('/dev/exists', { autoOpen: false }); port.open(function(err) { assert.isNull(err); }); @@ -330,8 +329,8 @@ describe('SerialPort', function() { }); it('allows opening after an open error', function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); - var stub = sandbox.stub(port.binding, 'open', function(path, opt, cb) { + const port = new SerialPort('/dev/exists', { autoOpen: false }); + const stub = sandbox.stub(port.binding, 'open', function(path, opt, cb) { cb(new Error('Haha no')); }); port.open(function(err) { @@ -344,8 +343,8 @@ describe('SerialPort', function() { describe('#write', function() { it('writes to the bindings layer', function(done) { - var data = new Buffer('Crazy!'); - var port = new SerialPort('/dev/exists'); + const data = new Buffer('Crazy!'); + const port = new SerialPort('/dev/exists'); port.on('open', function() { port.write(data, function() { assert.deepEqual(data, port.binding.port.lastWrite); @@ -355,11 +354,11 @@ describe('SerialPort', function() { }); it('converts strings to buffers', function(done) { - var port = new SerialPort('/dev/exists'); + const port = new SerialPort('/dev/exists'); port.on('open', function() { - var data = 'Crazy!'; + const data = 'Crazy!'; port.write(data, function() { - var lastWrite = port.binding.port.lastWrite; + const lastWrite = port.binding.port.lastWrite; assert.deepEqual(new Buffer(data), lastWrite); done(); }); @@ -367,11 +366,11 @@ describe('SerialPort', function() { }); it('converts strings with encodings to buffers', function(done) { - var port = new SerialPort('/dev/exists'); + const port = new SerialPort('/dev/exists'); port.on('open', function() { - var data = 'COFFEE'; + const data = 'COFFEE'; port.write(data, 'hex', function() { - var lastWrite = port.binding.port.lastWrite; + const lastWrite = port.binding.port.lastWrite; assert.deepEqual(new Buffer(data, 'hex'), lastWrite); done(); }); @@ -379,11 +378,11 @@ describe('SerialPort', function() { }); it('converts arrays to buffers', function(done) { - var port = new SerialPort('/dev/exists'); + const port = new SerialPort('/dev/exists'); port.on('open', function() { - var data = [0,32,44,88]; + const data = [0, 32, 44, 88]; port.write(data, function() { - var lastWrite = port.binding.port.lastWrite; + const lastWrite = port.binding.port.lastWrite; assert.deepEqual(new Buffer(data), lastWrite); done(); }); @@ -393,7 +392,7 @@ describe('SerialPort', function() { describe('#close', function() { it('emits a close event', function(done) { - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { port.on('close', function() { assert.isFalse(port.isOpen); done(); @@ -403,7 +402,7 @@ describe('SerialPort', function() { }); it('has a close callback', function(done) { - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { port.close(function() { assert.isFalse(port.isOpen); done(); @@ -412,21 +411,21 @@ describe('SerialPort', function() { }); it('emits the close event and runs the callback', function(done) { - var called = 0; - var doneIfTwice = function() { + let called = 0; + const doneIfTwice = function() { called++; if (called === 2) { return done() } }; - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { port.close(doneIfTwice); }); port.on('close', doneIfTwice); }); it('emits an error event or error callback but not both', function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); - var called = 0; - var doneIfTwice = function(err) { + const port = new SerialPort('/dev/exists', { autoOpen: false }); + let called = 0; + const doneIfTwice = function(err) { assert.instanceOf(err, Error); called++; if (called === 2) { return done() } @@ -437,8 +436,8 @@ describe('SerialPort', function() { }); it('fires a close event after being reopened', function(done) { - var port = new SerialPort('/dev/exists', function() { - var closeSpy = sandbox.spy(); + const port = new SerialPort('/dev/exists', function() { + const closeSpy = sandbox.spy(); port.on('close', closeSpy); port.close(function() { port.open(function() { @@ -452,8 +451,8 @@ describe('SerialPort', function() { }); it('errors when the port is not open', function(done) { - var cb = function() {}; - var port = new SerialPort('/dev/exists', { autoOpen: false }, cb); + const cb = function() {}; + const port = new SerialPort('/dev/exists', { autoOpen: false }, cb); port.close(function(err) { assert.instanceOf(err, Error); done(); @@ -463,7 +462,7 @@ describe('SerialPort', function() { describe('#update', function() { it('errors when the port is not open', function(done) { - var port = new SerialPort('/dev/exists', {autoOpen: false}); + const port = new SerialPort('/dev/exists', { autoOpen: false }); port.update({}, function(err) { assert.instanceOf(err, Error); done(); @@ -471,6 +470,7 @@ describe('SerialPort', function() { }); it('sets the baudRate on the port', function(done) { + // eslint-disable-next-line no-new new SerialPort('/dev/exists', function() { assert.equal(this.baudRate, 9600); this.update({ baudRate: 14400 }, function(err) { @@ -484,8 +484,8 @@ describe('SerialPort', function() { describe('#set', function() { it('errors when serialport not open', function(done) { - var cb = function() {}; - var port = new SerialPort('/dev/exists', { autoOpen: false }, cb); + const cb = function() {}; + const port = new SerialPort('/dev/exists', { autoOpen: false }, cb); port.set({}, function(err) { assert.instanceOf(err, Error); done(); @@ -493,7 +493,7 @@ describe('SerialPort', function() { }); it('sets the flags on the ports bindings', function(done) { - var settings = { + const settings = { brk: true, cts: true, dtr: true, @@ -501,7 +501,7 @@ describe('SerialPort', function() { rts: true }; - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { sandbox.stub(port.binding, 'set', function(options) { assert.deepEqual(options, settings); done(); @@ -511,13 +511,13 @@ describe('SerialPort', function() { }); it('sets missing options to default values', function(done) { - var settings = { + const settings = { cts: true, dts: true, rts: false }; - var filledWithMissing = { + const filledWithMissing = { brk: false, cts: true, dtr: true, @@ -525,7 +525,7 @@ describe('SerialPort', function() { rts: false }; - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { sandbox.stub(port.binding, 'set', function(options) { assert.deepEqual(options, filledWithMissing); done(); @@ -535,7 +535,7 @@ describe('SerialPort', function() { }); it('resets all flags if none are provided', function(done) { - var defaults = { + const defaults = { brk: false, cts: false, dtr: true, @@ -543,7 +543,7 @@ describe('SerialPort', function() { rts: true }; - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { sandbox.stub(port.binding, 'set', function(options) { assert.deepEqual(options, defaults); done(); @@ -555,7 +555,7 @@ describe('SerialPort', function() { describe('#flush', function() { it('errors when serialport not open', function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); + const port = new SerialPort('/dev/exists', { autoOpen: false }); port.flush(function(err) { assert.instanceOf(err, Error); done(); @@ -565,7 +565,7 @@ describe('SerialPort', function() { describe('#drain', function() { it('drain errors when serialport not open', function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); + const port = new SerialPort('/dev/exists', { autoOpen: false }); port.drain(function(err) { assert.instanceOf(err, Error); done(); @@ -575,7 +575,7 @@ describe('SerialPort', function() { describe('#get', function() { it('errors when serialport not open', function(done) { - var port = new SerialPort('/dev/exists', { autoOpen: false }); + const port = new SerialPort('/dev/exists', { autoOpen: false }); port.get(function(err) { assert.instanceOf(err, Error); done(); @@ -583,14 +583,15 @@ describe('SerialPort', function() { }); it('gets the status from the ports bindings', function(done) { - var status = { + const status = { cts: true, dsr: true, dcd: true }; - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { port.get(function(err, modemStatus) { + assert.isNull(err); assert.deepEqual(modemStatus, status); done(); }); @@ -607,8 +608,8 @@ describe('SerialPort', function() { describe('reading data', function() { it('emits data events by default', function(done) { - var testData = new Buffer('I am a really short string'); - var port = new SerialPort('/dev/exists', function() { + const testData = new Buffer('I am a really short string'); + const port = new SerialPort('/dev/exists', function() { port.once('data', function(recvData) { assert.deepEqual(recvData, testData); done(); @@ -620,11 +621,11 @@ describe('SerialPort', function() { describe('disconnections', function() { it('emits a disconnect event and closes the port', function(done) { - var port = new SerialPort('/dev/exists', function() { + const port = new SerialPort('/dev/exists', function() { assert.isTrue(port.isOpen); port.binding.disconnect('/dev/exists'); }); - var spy = sandbox.spy(); + const spy = sandbox.spy(); port.on('disconnect', spy); port.on('close', function() { assert.isFalse(port.isOpen);