diff --git a/benchmark/fs/readfile-partitioned.js b/benchmark/fs/readfile-partitioned.js index 2775793e0b0928..90af3754ce3de2 100644 --- a/benchmark/fs/readfile-partitioned.js +++ b/benchmark/fs/readfile-partitioned.js @@ -29,7 +29,7 @@ function main(conf) { fs.writeFileSync(filename, data); data = null; - var zipData = Buffer.alloc(1024, 'a'); + const zipData = Buffer.alloc(1024, 'a'); var reads = 0; var zips = 0; diff --git a/benchmark/fs/write-stream-throughput.js b/benchmark/fs/write-stream-throughput.js index bc88330929c2fc..3936adc7ff1b42 100644 --- a/benchmark/fs/write-stream-throughput.js +++ b/benchmark/fs/write-stream-throughput.js @@ -38,7 +38,7 @@ function main({ dur, encodingType, size }) { var started = false; var ended = false; - var f = fs.createWriteStream(filename); + const f = fs.createWriteStream(filename); f.on('drain', write); f.on('open', write); f.on('close', done); diff --git a/benchmark/http/_chunky_http_client.js b/benchmark/http/_chunky_http_client.js index 21418a7c26b584..5164f8c6199e35 100644 --- a/benchmark/http/_chunky_http_client.js +++ b/benchmark/http/_chunky_http_client.js @@ -54,7 +54,7 @@ function main({ len, n }) { const add = 11; var count = 0; const PIPE = process.env.PIPE_NAME; - var socket = net.connect(PIPE, () => { + const socket = net.connect(PIPE, () => { bench.start(); WriteHTTPHeaders(socket, 1, len); socket.setEncoding('utf8'); diff --git a/benchmark/http/http_server_for_chunky_client.js b/benchmark/http/http_server_for_chunky_client.js index edcacf5d124e8f..ef0a23a02928ef 100644 --- a/benchmark/http/http_server_for_chunky_client.js +++ b/benchmark/http/http_server_for_chunky_client.js @@ -10,9 +10,7 @@ process.env.PIPE_NAME = PIPE; tmpdir.refresh(); -var server; - -server = http.createServer((req, res) => { +const server = http.createServer((req, res) => { const headers = { 'content-type': 'text/plain', 'content-length': '2' diff --git a/benchmark/http/set-header.js b/benchmark/http/set-header.js index 01cd8492dff729..1909c0991dfc71 100644 --- a/benchmark/http/set-header.js +++ b/benchmark/http/set-header.js @@ -17,7 +17,7 @@ const c = 50; // setHeaderWH: setHeader(...), writeHead(status, ...) function main({ res }) { process.env.PORT = PORT; - var server = require('../fixtures/simple-http-server.js') + const server = require('../fixtures/simple-http-server.js') .listen(PORT) .on('listening', () => { const path = `/${type}/${len}/${chunks}/normal/${chunkedEnc}`; diff --git a/benchmark/http/simple.js b/benchmark/http/simple.js index c6faaaa9efdfd2..acb613ef036583 100644 --- a/benchmark/http/simple.js +++ b/benchmark/http/simple.js @@ -11,7 +11,7 @@ const bench = common.createBenchmark(main, { }); function main({ type, len, chunks, c, chunkedEnc, res }) { - var server = require('../fixtures/simple-http-server.js') + const server = require('../fixtures/simple-http-server.js') .listen(common.PORT) .on('listening', () => { const path = `/${type}/${len}/${chunks}/normal/${chunkedEnc}`; diff --git a/benchmark/http/upgrade.js b/benchmark/http/upgrade.js index c286cdb2644d0c..8d365fe46df24e 100644 --- a/benchmark/http/upgrade.js +++ b/benchmark/http/upgrade.js @@ -19,7 +19,7 @@ const resData = 'HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + '\r\n\r\n'; function main({ n }) { - var server = require('../fixtures/simple-http-server.js') + const server = require('../fixtures/simple-http-server.js') .listen(common.PORT) .on('listening', () => { bench.start(); diff --git a/benchmark/tls/throughput.js b/benchmark/tls/throughput.js index 3c0c2d4ea18099..cd957ff1edf495 100644 --- a/benchmark/tls/throughput.js +++ b/benchmark/tls/throughput.js @@ -14,7 +14,6 @@ const tls = require('tls'); function main({ dur, type, size }) { var encoding; - var server; var chunk; switch (type) { case 'buf': @@ -39,7 +38,7 @@ function main({ dur, type, size }) { ciphers: 'AES256-GCM-SHA384' }; - server = tls.createServer(options, onConnection); + const server = tls.createServer(options, onConnection); var conn; server.listen(common.PORT, () => { const opt = { port: common.PORT, rejectUnauthorized: false }; diff --git a/benchmark/tls/tls-connect.js b/benchmark/tls/tls-connect.js index 470d536f87e6b2..fa6e2cb80abf06 100644 --- a/benchmark/tls/tls-connect.js +++ b/benchmark/tls/tls-connect.js @@ -46,7 +46,7 @@ function makeConnection() { port: common.PORT, rejectUnauthorized: false }; - var conn = tls.connect(options, () => { + const conn = tls.connect(options, () => { clientConn++; conn.on('error', (er) => { console.error('client error', er); diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 65a538f3c8684a..b506767ab2c751 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -61,7 +61,7 @@ function Agent(options) { this.maxFreeSockets = this.options.maxFreeSockets || 256; this.on('free', (socket, options) => { - var name = this.getName(options); + const name = this.getName(options); debug('agent.on(free)', name); if (socket.writable && @@ -153,13 +153,13 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, if (!options.servername) options.servername = calculateServerName(options, req); - var name = this.getName(options); + const name = this.getName(options); if (!this.sockets[name]) { this.sockets[name] = []; } - var freeLen = this.freeSockets[name] ? this.freeSockets[name].length : 0; - var sockLen = freeLen + this.sockets[name].length; + const freeLen = this.freeSockets[name] ? this.freeSockets[name].length : 0; + const sockLen = freeLen + this.sockets[name].length; if (freeLen) { // We have a free socket, so use that. @@ -200,7 +200,7 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) { if (!options.servername) options.servername = calculateServerName(options, req); - var name = this.getName(options); + const name = this.getName(options); options._agentKey = name; debug('createConnection', name, options); @@ -280,9 +280,9 @@ function installListeners(agent, s, options) { } Agent.prototype.removeSocket = function removeSocket(s, options) { - var name = this.getName(options); + const name = this.getName(options); debug('removeSocket', name, 'writable:', s.writable); - var sets = [this.sockets]; + const sets = [this.sockets]; // If the socket was destroyed, remove it from the free buffers too. if (!s.writable) @@ -324,7 +324,7 @@ Agent.prototype.reuseSocket = function reuseSocket(socket, req) { }; Agent.prototype.destroy = function destroy() { - var sets = [this.freeSockets, this.sockets]; + const sets = [this.freeSockets, this.sockets]; for (var s = 0; s < sets.length; s++) { var set = sets[s]; var keys = Object.keys(set); diff --git a/lib/_http_client.js b/lib/_http_client.js index f29f5b3333811c..c281a4dbdacbb0 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -99,7 +99,7 @@ function ClientRequest(input, options, cb) { } var agent = options.agent; - var defaultAgent = options._defaultAgent || Agent.globalAgent; + const defaultAgent = options._defaultAgent || Agent.globalAgent; if (agent === false) { agent = new defaultAgent.constructor(); } else if (agent === null || agent === undefined) { @@ -115,7 +115,7 @@ function ClientRequest(input, options, cb) { } this.agent = agent; - var protocol = options.protocol || defaultAgent.protocol; + const protocol = options.protocol || defaultAgent.protocol; var expectedProtocol = defaultAgent.protocol; if (this.agent && this.agent.protocol) expectedProtocol = this.agent.protocol; @@ -131,20 +131,20 @@ function ClientRequest(input, options, cb) { throw new ERR_INVALID_PROTOCOL(protocol, expectedProtocol); } - var defaultPort = options.defaultPort || + const defaultPort = options.defaultPort || this.agent && this.agent.defaultPort; - var port = options.port = options.port || defaultPort || 80; - var host = options.host = validateHost(options.hostname, 'hostname') || + const port = options.port = options.port || defaultPort || 80; + const host = options.host = validateHost(options.hostname, 'hostname') || validateHost(options.host, 'host') || 'localhost'; - var setHost = (options.setHost === undefined || Boolean(options.setHost)); + const setHost = (options.setHost === undefined || Boolean(options.setHost)); this.socketPath = options.socketPath; this.timeout = options.timeout; var method = options.method; - var methodIsString = (typeof method === 'string'); + const methodIsString = (typeof method === 'string'); if (method !== null && method !== undefined && !methodIsString) { throw new ERR_INVALID_ARG_TYPE('method', 'string', method); } @@ -197,7 +197,7 @@ function ClientRequest(input, options, cb) { } } - var headersArray = Array.isArray(options.headers); + const headersArray = Array.isArray(options.headers); if (!headersArray) { if (options.headers) { var keys = Object.keys(options.headers); @@ -244,7 +244,7 @@ function ClientRequest(input, options, cb) { options.headers); } - var oncreate = (err, socket) => { + const oncreate = (err, socket) => { if (called) return; called = true; @@ -327,15 +327,15 @@ function emitAbortNT() { function createHangUpError() { // eslint-disable-next-line no-restricted-syntax - var error = new Error('socket hang up'); + const error = new Error('socket hang up'); error.code = 'ECONNRESET'; return error; } function socketCloseListener() { - var socket = this; - var req = socket._httpMessage; + const socket = this; + const req = socket._httpMessage; debug('HTTP socket close'); // Pull through final chunk, if anything is buffered. @@ -386,8 +386,8 @@ function socketCloseListener() { } function socketErrorListener(err) { - var socket = this; - var req = socket._httpMessage; + const socket = this; + const req = socket._httpMessage; debug('SOCKET ERROR:', err.message, err.stack); if (req) { @@ -400,7 +400,7 @@ function socketErrorListener(err) { // Handle any pending data socket.read(); - var parser = socket.parser; + const parser = socket.parser; if (parser) { parser.finish(); freeParser(parser, req, socket); @@ -413,16 +413,16 @@ function socketErrorListener(err) { } function freeSocketErrorListener(err) { - var socket = this; + const socket = this; debug('SOCKET ERROR on FREE socket:', err.message, err.stack); socket.destroy(); socket.emit('agentRemove'); } function socketOnEnd() { - var socket = this; - var req = this._httpMessage; - var parser = this.parser; + const socket = this; + const req = this._httpMessage; + const parser = this.parser; if (!req.res && !req.socket._hadError) { // If we don't have a response then we know that the socket @@ -438,13 +438,13 @@ function socketOnEnd() { } function socketOnData(d) { - var socket = this; - var req = this._httpMessage; - var parser = this.parser; + const socket = this; + const req = this._httpMessage; + const parser = this.parser; assert(parser && parser.socket === socket); - var ret = parser.execute(d); + const ret = parser.execute(d); if (ret instanceof Error) { debug('parse error', ret); freeParser(parser, req, socket); @@ -506,8 +506,8 @@ function statusIsInformational(status) { // client function parserOnIncomingClient(res, shouldKeepAlive) { - var socket = this.socket; - var req = socket._httpMessage; + const socket = this.socket; + const req = socket._httpMessage; debug('AGENT incoming response!'); @@ -557,7 +557,7 @@ function parserOnIncomingClient(res, shouldKeepAlive) { // Add our listener first, so that we guarantee socket cleanup res.on('end', responseOnEnd); req.on('prefinish', requestOnPrefinish); - var handled = req.emit('response', res); + const handled = req.emit('response', res); // If the user did not listen for the 'response' event, then they // can't possibly read the data, so we ._dump() it into the void @@ -573,7 +573,7 @@ function parserOnIncomingClient(res, shouldKeepAlive) { // client function responseKeepAlive(res, req) { - var socket = req.socket; + const socket = req.socket; if (!req.shouldKeepAlive) { if (socket.writable) { @@ -627,7 +627,7 @@ function emitFreeNT(socket) { } function tickOnSocket(req, socket) { - var parser = parsers.alloc(); + const parser = parsers.alloc(); req.socket = socket; req.connection = socket; parser.reinitialize(HTTPParser.RESPONSE, parser[is_reused_symbol]); diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index 9ad3b8eb0d725a..372b6c784b8809 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -244,7 +244,7 @@ function matchKnownFields(field, lowercased) { IncomingMessage.prototype._addHeaderLine = _addHeaderLine; function _addHeaderLine(field, value, dest) { field = matchKnownFields(field); - var flag = field.charCodeAt(0); + const flag = field.charCodeAt(0); if (flag === 0 || flag === 2) { field = field.slice(1); // Make a delimited list diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 3be6cd2e96daf1..3d5a4c32e15f7f 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -53,8 +53,8 @@ const kIsCorked = Symbol('isCorked'); const hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); -var RE_CONN_CLOSE = /(?:^|\W)close(?:$|\W)/i; -var RE_TE_CHUNKED = common.chunkExpression; +const RE_CONN_CLOSE = /(?:^|\W)close(?:$|\W)/i; +const RE_TE_CHUNKED = common.chunkExpression; // isCookieField performs a case-insensitive comparison of a provided string // against the word "cookie." As of V8 6.6 this is faster than handrolling or @@ -161,7 +161,7 @@ OutgoingMessage.prototype._renderHeaders = function _renderHeaders() { throw new ERR_HTTP_HEADERS_SENT('render'); } - var headersMap = this[outHeadersKey]; + const headersMap = this[outHeadersKey]; const headers = {}; if (headersMap !== null) { @@ -540,7 +540,7 @@ OutgoingMessage.prototype.removeHeader = function removeHeader(name) { throw new ERR_HTTP_HEADERS_SENT('remove'); } - var key = name.toLowerCase(); + const key = name.toLowerCase(); switch (key) { case 'connection': @@ -656,8 +656,8 @@ function connectionCorkNT(msg, conn) { OutgoingMessage.prototype.addTrailers = function addTrailers(headers) { this._trailer = ''; - var keys = Object.keys(headers); - var isArray = Array.isArray(headers); + const keys = Object.keys(headers); + const isArray = Array.isArray(headers); var field, value; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; @@ -720,7 +720,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) { if (typeof callback === 'function') this.once('finish', callback); - var finish = onFinish.bind(undefined, this); + const finish = onFinish.bind(undefined, this); if (this._hasBody && this.chunkedEncoding) { this._send('0\r\n' + this._trailer + '\r\n', 'latin1', finish); @@ -773,7 +773,7 @@ OutgoingMessage.prototype._finish = function _finish() { // This function, outgoingFlush(), is called by both the Server and Client // to attempt to flush any pending messages out to the socket. OutgoingMessage.prototype._flush = function _flush() { - var socket = this.socket; + const socket = this.socket; var ret; if (socket && socket.writable) { diff --git a/lib/_http_server.js b/lib/_http_server.js index 282b3a8227d43b..79f56bc19c9da2 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -201,7 +201,7 @@ ServerResponse.prototype._implicitHeader = function _implicitHeader() { ServerResponse.prototype.writeHead = writeHead; function writeHead(statusCode, reason, obj) { - var originalStatusCode = statusCode; + const originalStatusCode = statusCode; statusCode |= 0; if (statusCode < 100 || statusCode > 999) { @@ -244,7 +244,7 @@ function writeHead(statusCode, reason, obj) { if (checkInvalidHeaderChar(this.statusMessage)) throw new ERR_INVALID_CHAR('statusMessage'); - var statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}${CRLF}`; + const statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}${CRLF}`; if (statusCode === 204 || statusCode === 304 || (statusCode >= 100 && statusCode <= 199)) { @@ -340,7 +340,7 @@ function connectionListenerInternal(server, socket) { socket.setTimeout(server.timeout); socket.on('timeout', socketOnTimeout); - var parser = parsers.alloc(); + const parser = parsers.alloc(); parser.reinitialize(HTTPParser.REQUEST, parser[is_reused_symbol]); parser.socket = socket; @@ -353,7 +353,7 @@ function connectionListenerInternal(server, socket) { parser.maxHeaderPairs = server.maxHeadersCount << 1; } - var state = { + const state = { onData: null, onEnd: null, onClose: null, @@ -408,7 +408,7 @@ function updateOutgoingData(socket, state, delta) { } function socketOnDrain(socket, state) { - var needPause = state.outgoingData > socket.writableHighWaterMark; + const needPause = state.outgoingData > socket.writableHighWaterMark; // If we previously paused, then start reading again. if (socket._paused && !needPause) { @@ -420,11 +420,11 @@ function socketOnDrain(socket, state) { } function socketOnTimeout() { - var req = this.parser && this.parser.incoming; - var reqTimeout = req && !req.complete && req.emit('timeout', this); - var res = this._httpMessage; - var resTimeout = res && res.emit('timeout', this); - var serverTimeout = this.server.emit('timeout', this); + const req = this.parser && this.parser.incoming; + const reqTimeout = req && !req.complete && req.emit('timeout', this); + const res = this._httpMessage; + const resTimeout = res && res.emit('timeout', this); + const serverTimeout = this.server.emit('timeout', this); if (!reqTimeout && !resTimeout && !serverTimeout) this.destroy(); @@ -451,7 +451,7 @@ function abortIncoming(incoming) { } function socketOnEnd(server, socket, parser, state) { - var ret = parser.finish(); + const ret = parser.finish(); if (ret instanceof Error) { debug('parse error'); @@ -475,7 +475,7 @@ function socketOnData(server, socket, parser, state, d) { assert(!socket._paused); debug('SERVER socketOnData %d', d.length); - var ret = parser.execute(d); + const ret = parser.execute(d); onParserExecuteCommon(server, socket, parser, state, ret, d); } @@ -641,7 +641,7 @@ function parserOnIncoming(server, socket, state, req, keepAlive) { } } - var res = new server[kServerResponse](req); + const res = new server[kServerResponse](req); res._onPendingData = updateOutgoingData.bind(undefined, socket, state); res.shouldKeepAlive = keepAlive; @@ -726,7 +726,7 @@ function unconsume(parser, socket) { } function socketOnWrap(ev, fn) { - var res = net.Socket.prototype.on.call(this, ev, fn); + const res = net.Socket.prototype.on.call(this, ev, fn); if (!this.parser) { this.on = net.Socket.prototype.on; return res; diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index d0bc95496a2b12..d1929f0e2f4bc7 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -213,7 +213,7 @@ Readable.prototype._destroy = function(err, cb) { // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; + const state = this._readableState; var skipChunkCheck; if (!state.objectMode) { @@ -239,7 +239,7 @@ Readable.prototype.unshift = function(chunk) { function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { debug('readableAddChunk', chunk); - var state = stream._readableState; + const state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); @@ -383,8 +383,8 @@ function howMuchToRead(n, state) { Readable.prototype.read = function(n) { debug('read', n); n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + const state = this._readableState; + const nOrig = n; if (n !== 0) state.emittedReadable = false; @@ -534,7 +534,7 @@ function onEofChunk(stream, state) { // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { - var state = stream._readableState; + const state = stream._readableState; debug('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { @@ -545,7 +545,7 @@ function emitReadable(stream) { } function emitReadable_(stream) { - var state = stream._readableState; + const state = stream._readableState; debug('emitReadable_', state.destroyed, state.length, state.ended); if (!state.destroyed && (state.length || state.ended)) { stream.emit('readable'); @@ -625,8 +625,8 @@ Readable.prototype._read = function(n) { }; Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; + const src = this; + const state = this._readableState; switch (state.pipesCount) { case 0: @@ -642,11 +642,11 @@ Readable.prototype.pipe = function(dest, pipeOpts) { state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && + const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; + const endFn = doEnd ? onend : unpipe; if (state.endEmitted) process.nextTick(endFn); else @@ -672,7 +672,7 @@ Readable.prototype.pipe = function(dest, pipeOpts) { // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. - var ondrain = pipeOnDrain(src); + const ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; @@ -703,7 +703,7 @@ Readable.prototype.pipe = function(dest, pipeOpts) { src.on('data', ondata); function ondata(chunk) { debug('ondata'); - var ret = dest.write(chunk); + const ret = dest.write(chunk); debug('dest.write', ret); if (ret === false) { // If the user unpiped during `dest.write()`, it is possible @@ -765,7 +765,7 @@ Readable.prototype.pipe = function(dest, pipeOpts) { function pipeOnDrain(src) { return function pipeOnDrainFunctionResult() { - var state = src._readableState; + const state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; @@ -778,8 +778,8 @@ function pipeOnDrain(src) { Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; + const state = this._readableState; + const unpipeInfo = { hasUnpiped: false }; // If we're not piping anywhere, then do nothing. if (state.pipesCount === 0) @@ -818,8 +818,8 @@ Readable.prototype.unpipe = function(dest) { return this; } - // try to find the right one. - var index = state.pipes.indexOf(dest); + // Try to find the right one. + const index = state.pipes.indexOf(dest); if (index === -1) return this; @@ -920,7 +920,7 @@ function nReadingNextTick(self) { // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function() { - var state = this._readableState; + const state = this._readableState; if (!state.flowing) { debug('resume'); // We flow only if there is no one listening @@ -974,7 +974,7 @@ function flow(stream) { // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function(stream) { - var state = this._readableState; + const state = this._readableState; var paused = false; stream.on('end', () => { @@ -999,16 +999,15 @@ Readable.prototype.wrap = function(stream) { else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = this.push(chunk); + const ret = this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { + // Proxy all the other methods. Important when wrapping filters and duplexes. + for (const i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function methodWrap(method) { return function methodWrapReturnFunction() { @@ -1123,7 +1122,7 @@ function fromList(n, state) { } function endReadable(stream) { - var state = stream._readableState; + const state = stream._readableState; debug('endReadable', state.endEmitted); if (!state.endEmitted) { diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js index 7393dddbabc329..e123b05ee85270 100644 --- a/lib/_stream_transform.js +++ b/lib/_stream_transform.js @@ -76,10 +76,10 @@ util.inherits(Transform, Duplex); function afterTransform(er, data) { - var ts = this._transformState; + const ts = this._transformState; ts.transforming = false; - var cb = ts.writecb; + const cb = ts.writecb; if (cb === null) { return this.emit('error', new ERR_MULTIPLE_CALLBACK()); @@ -93,7 +93,7 @@ function afterTransform(er, data) { cb(er); - var rs = this._readableState; + const rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); @@ -163,7 +163,7 @@ Transform.prototype._transform = function(chunk, encoding, cb) { }; Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; + const ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; @@ -180,7 +180,7 @@ Transform.prototype._write = function(chunk, encoding, cb) { // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function(n) { - var ts = this._transformState; + const ts = this._transformState; if (ts.writechunk !== null && !ts.transforming) { ts.transforming = true; diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index e5b11d06a19b39..d6d86cc8596f0a 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -93,7 +93,7 @@ function WritableState(options, stream, isDuplex) { // Should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. - var noDecode = options.decodeStrings === false; + const noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string @@ -157,14 +157,14 @@ function WritableState(options, stream, isDuplex) { // Allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two - var corkReq = { next: null, entry: null, finish: undefined }; + const corkReq = { next: null, entry: null, finish: undefined }; corkReq.finish = onCorkedFinish.bind(undefined, corkReq, this); this.corkedRequestsFree = corkReq; } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; - var out = []; + const out = []; while (current) { out.push(current); current = current.next; @@ -245,7 +245,7 @@ Writable.prototype.pipe = function() { function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); + const er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb errorOrDestroy(stream, er); process.nextTick(cb, er); @@ -271,9 +271,9 @@ function validChunk(stream, state, chunk, cb) { } Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; + const state = this._writableState; var ret = false; - var isBuf = !state.objectMode && Stream._isUint8Array(chunk); + const isBuf = !state.objectMode && Stream._isUint8Array(chunk); if (isBuf && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = Stream._uint8ArrayToBuffer(chunk); @@ -307,7 +307,7 @@ Writable.prototype.cork = function() { }; Writable.prototype.uncork = function() { - var state = this._writableState; + const state = this._writableState; if (state.corked) { state.corked--; @@ -371,11 +371,11 @@ function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { chunk = newChunk; } } - var len = state.objectMode ? 1 : chunk.length; + const len = state.objectMode ? 1 : chunk.length; state.length += len; - var ret = state.length < state.highWaterMark; + const ret = state.length < state.highWaterMark; // We must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; @@ -448,9 +448,9 @@ function onwriteStateUpdate(state) { } function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + const state = stream._writableState; + const sync = state.sync; + const cb = state.writecb; if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); @@ -569,7 +569,7 @@ Writable.prototype._write = function(chunk, encoding, cb) { Writable.prototype._writev = null; Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; + const state = this._writableState; if (typeof chunk === 'function') { cb = chunk; @@ -638,7 +638,7 @@ function prefinish(stream, state) { } function finishMaybe(stream, state) { - var need = needFinish(state); + const need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { diff --git a/lib/_tls_common.js b/lib/_tls_common.js index 29b4cc78a8fc84..78e67af23d46f0 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -139,8 +139,8 @@ exports.createSecureContext = function createSecureContext(options, context) { // `ssl_set_pkey` returns `0` when the key does not match the cert, but // `ssl_set_cert` returns `1` and nullifies the key in the SSL structure // which leads to the crash later on. - var key = options.key; - var passphrase = options.passphrase; + const key = options.key; + const passphrase = options.passphrase; if (key) { if (Array.isArray(key)) { for (i = 0; i < key.length; ++i) { diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 37f9f84ed95a96..98f9fc98fbaa02 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -370,7 +370,7 @@ function TLSSocket(socket, opts) { util.inherits(TLSSocket, net.Socket); exports.TLSSocket = TLSSocket; -var proxiedMethods = [ +const proxiedMethods = [ 'ref', 'unref', 'open', 'bind', 'listen', 'connect', 'bind6', 'connect6', 'getsockname', 'getpeername', 'setNoDelay', 'setKeepAlive', 'setSimultaneousAccepts', 'setBlocking', @@ -429,7 +429,7 @@ TLSSocket.prototype._wrapHandle = function(wrap) { if (wrap) handle = wrap._handle; - var options = this._tlsOptions; + const options = this._tlsOptions; if (!handle) { handle = options.pipe ? new Pipe(PipeConstants.SOCKET) : @@ -491,9 +491,8 @@ TLSSocket.prototype._destroySSL = function _destroySSL() { }; TLSSocket.prototype._init = function(socket, wrap) { - var options = this._tlsOptions; - var ssl = this._handle; - + const options = this._tlsOptions; + const ssl = this._handle; this.server = options.server; // Clients (!isServer) always request a cert, servers request a client cert @@ -638,7 +637,7 @@ TLSSocket.prototype._handleTimeout = function() { }; TLSSocket.prototype._emitTLSError = function(err) { - var e = this._tlsError(err); + const e = this._tlsError(err); if (e) this.emit('error', e); }; @@ -1082,7 +1081,7 @@ Server.prototype.setOptions = function(options) { if (options.dhparam) this.dhparam = options.dhparam; if (options.sessionTimeout) this.sessionTimeout = options.sessionTimeout; if (options.ticketKeys) this.ticketKeys = options.ticketKeys; - var secureOptions = options.secureOptions || 0; + const secureOptions = options.secureOptions || 0; if (options.honorCipherOrder !== undefined) this.honorCipherOrder = !!options.honorCipherOrder; else @@ -1106,7 +1105,7 @@ Server.prototype.addContext = function(servername, context) { throw new ERR_TLS_REQUIRED_SERVER_NAME(); } - var re = new RegExp('^' + + const re = new RegExp('^' + servername.replace(/([.^$+?\-\\[\]{}])/g, '\\$1') .replace(/\*/g, '[^.]*') + '$'); @@ -1228,7 +1227,7 @@ let warnOnAllowUnauthorized = true; exports.connect = function connect(...args) { args = normalizeConnectArgs(args); var options = args[0]; - var cb = args[1]; + const cb = args[1]; const allowUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0'; if (allowUnauthorized && warnOnAllowUnauthorized) { @@ -1259,7 +1258,7 @@ exports.connect = function connect(...args) { const context = options.secureContext || tls.createSecureContext(options); - var tlssock = new TLSSocket(options.socket, { + const tlssock = new TLSSocket(options.socket, { pipe: !!options.path, secureContext: context, isServer: false, diff --git a/lib/child_process.js b/lib/child_process.js index f1b5006242dab5..3be928061e92a1 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -118,7 +118,7 @@ exports.fork = function fork(modulePath /* , args, options */) { exports._forkChild = function _forkChild(fd) { // set process.send() - var p = new Pipe(PipeConstants.IPC); + const p = new Pipe(PipeConstants.IPC); p.open(fd); p.unref(); const control = setupChannel(process, p); @@ -223,7 +223,7 @@ exports.execFile = function execFile(file /* , args, options, callback */) { options.killSignal = sanitizeKillSignal(options.killSignal); - var child = spawn(file, args, { + const child = spawn(file, args, { cwd: options.cwd, env: options.env, gid: options.gid, @@ -234,8 +234,8 @@ exports.execFile = function execFile(file /* , args, options, callback */) { }); var encoding; - var _stdout = []; - var _stderr = []; + const _stdout = []; + const _stderr = []; if (options.encoding !== 'buffer' && Buffer.isEncoding(options.encoding)) { encoding = options.encoding; } else { @@ -346,7 +346,7 @@ exports.execFile = function execFile(file /* , args, options, callback */) { child.stdout.setEncoding(encoding); child.stdout.on('data', function onChildStdout(chunk) { - var encoding = child.stdout._readableState.encoding; + const encoding = child.stdout._readableState.encoding; const length = encoding ? Buffer.byteLength(chunk, encoding) : chunk.length; @@ -369,7 +369,7 @@ exports.execFile = function execFile(file /* , args, options, callback */) { child.stderr.setEncoding(encoding); child.stderr.on('data', function onChildStderr(chunk) { - var encoding = child.stderr._readableState.encoding; + const encoding = child.stderr._readableState.encoding; const length = encoding ? Buffer.byteLength(chunk, encoding) : chunk.length; @@ -521,8 +521,8 @@ function normalizeSpawnArguments(file, args, options) { args.unshift(file); } - var env = options.env || process.env; - var envPairs = []; + const env = options.env || process.env; + const envPairs = []; // process.env.NODE_V8_COVERAGE always propagates, making it possible to // collect coverage for programs that spawn with white-listed environment. @@ -533,7 +533,7 @@ function normalizeSpawnArguments(file, args, options) { } // Prototype values are intentionally included. - for (var key in env) { + for (const key in env) { const value = env[key]; if (value !== undefined) { envPairs.push(`${key}=${value}`); @@ -646,15 +646,15 @@ function checkExecSyncError(ret, args, cmd) { function execFileSync(command, args, options) { - var opts = normalizeSpawnArguments(command, args, options); - var inheritStderr = !opts.options.stdio; + const opts = normalizeSpawnArguments(command, args, options); + const inheritStderr = !opts.options.stdio; - var ret = spawnSync(opts.file, opts.args.slice(1), opts.options); + const ret = spawnSync(opts.file, opts.args.slice(1), opts.options); if (inheritStderr && ret.stderr) process.stderr.write(ret.stderr); - var err = checkExecSyncError(ret, opts.args, undefined); + const err = checkExecSyncError(ret, opts.args, undefined); if (err) throw err; @@ -665,15 +665,15 @@ exports.execFileSync = execFileSync; function execSync(command, options) { - var opts = normalizeExecArgs(command, options, null); - var inheritStderr = !opts.options.stdio; + const opts = normalizeExecArgs(command, options, null); + const inheritStderr = !opts.options.stdio; - var ret = spawnSync(opts.file, opts.options); + const ret = spawnSync(opts.file, opts.options); if (inheritStderr && ret.stderr) process.stderr.write(ret.stderr); - var err = checkExecSyncError(ret, opts.args, command); + const err = checkExecSyncError(ret, opts.args, command); if (err) throw err; diff --git a/lib/dgram.js b/lib/dgram.js index da94e1a9cda01b..ba4524bab2a0fc 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -89,7 +89,7 @@ function Socket(type, listener) { sendBufferSize = options.sendBufferSize; } - var handle = newHandle(type, lookup); + const handle = newHandle(type, lookup); handle[owner_symbol] = this; this[async_id_symbol] = handle.getAsyncId(); @@ -498,7 +498,7 @@ function doSend(ex, self, ip, list, address, port, callback) { return; } - var req = new SendWrap(); + const req = new SendWrap(); req.list = list; // Keep reference alive. req.address = address; req.port = port; @@ -507,12 +507,12 @@ function doSend(ex, self, ip, list, address, port, callback) { req.oncomplete = afterSend; } - var err = state.handle.send(req, - list, - list.length, - port, - ip, - !!callback); + const err = state.handle.send(req, + list, + list.length, + port, + ip, + !!callback); if (err && callback) { // Don't emit as error, dgram_legacy.js compatibility @@ -564,8 +564,8 @@ function socketCloseNT(self) { Socket.prototype.address = function() { healthCheck(this); - var out = {}; - var err = this[kStateSymbol].handle.getsockname(out); + const out = {}; + const err = this[kStateSymbol].handle.getsockname(out); if (err) { throw errnoException(err, 'getsockname'); } @@ -575,7 +575,7 @@ Socket.prototype.address = function() { Socket.prototype.setBroadcast = function(arg) { - var err = this[kStateSymbol].handle.setBroadcast(arg ? 1 : 0); + const err = this[kStateSymbol].handle.setBroadcast(arg ? 1 : 0); if (err) { throw errnoException(err, 'setBroadcast'); } @@ -585,7 +585,7 @@ Socket.prototype.setBroadcast = function(arg) { Socket.prototype.setTTL = function(ttl) { validateNumber(ttl, 'ttl'); - var err = this[kStateSymbol].handle.setTTL(ttl); + const err = this[kStateSymbol].handle.setTTL(ttl); if (err) { throw errnoException(err, 'setTTL'); } @@ -597,7 +597,7 @@ Socket.prototype.setTTL = function(ttl) { Socket.prototype.setMulticastTTL = function(ttl) { validateNumber(ttl, 'ttl'); - var err = this[kStateSymbol].handle.setMulticastTTL(ttl); + const err = this[kStateSymbol].handle.setMulticastTTL(ttl); if (err) { throw errnoException(err, 'setMulticastTTL'); } @@ -607,7 +607,7 @@ Socket.prototype.setMulticastTTL = function(ttl) { Socket.prototype.setMulticastLoopback = function(arg) { - var err = this[kStateSymbol].handle.setMulticastLoopback(arg ? 1 : 0); + const err = this[kStateSymbol].handle.setMulticastLoopback(arg ? 1 : 0); if (err) { throw errnoException(err, 'setMulticastLoopback'); } @@ -635,7 +635,7 @@ Socket.prototype.addMembership = function(multicastAddress, } const { handle } = this[kStateSymbol]; - var err = handle.addMembership(multicastAddress, interfaceAddress); + const err = handle.addMembership(multicastAddress, interfaceAddress); if (err) { throw errnoException(err, 'addMembership'); } @@ -651,7 +651,7 @@ Socket.prototype.dropMembership = function(multicastAddress, } const { handle } = this[kStateSymbol]; - var err = handle.dropMembership(multicastAddress, interfaceAddress); + const err = handle.dropMembership(multicastAddress, interfaceAddress); if (err) { throw errnoException(err, 'dropMembership'); } @@ -678,7 +678,7 @@ function stopReceiving(socket) { function onMessage(nread, handle, buf, rinfo) { - var self = handle[owner_symbol]; + const self = handle[owner_symbol]; if (nread < 0) { return self.emit('error', errnoException(nread, 'recvmsg')); } diff --git a/lib/dns.js b/lib/dns.js index df19807d60206d..3d057d6b50081d 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -70,7 +70,7 @@ function onlookupall(err, addresses) { return this.callback(dnsException(err, 'getaddrinfo', this.hostname)); } - var family = this.family; + const family = this.family; for (var i = 0; i < addresses.length; i++) { const addr = addresses[i]; addresses[i] = { @@ -123,7 +123,7 @@ function lookup(hostname, options, callback) { return {}; } - var matchedFamily = isIP(hostname); + const matchedFamily = isIP(hostname); if (matchedFamily) { if (all) { process.nextTick( @@ -134,13 +134,15 @@ function lookup(hostname, options, callback) { return {}; } - var req = new GetAddrInfoReqWrap(); + const req = new GetAddrInfoReqWrap(); req.callback = callback; req.family = family; req.hostname = hostname; req.oncomplete = all ? onlookupall : onlookup; - var err = cares.getaddrinfo(req, toASCII(hostname), family, hints, verbatim); + const err = cares.getaddrinfo( + req, toASCII(hostname), family, hints, verbatim + ); if (err) { process.nextTick(callback, dnsException(err, 'getaddrinfo', hostname)); return {}; @@ -176,13 +178,13 @@ function lookupService(hostname, port, callback) { port = +port; - var req = new GetNameInfoReqWrap(); + const req = new GetNameInfoReqWrap(); req.callback = callback; req.hostname = hostname; req.port = port; req.oncomplete = onlookupservice; - var err = cares.getnameinfo(req, hostname, port); + const err = cares.getnameinfo(req, hostname, port); if (err) throw dnsException(err, 'getnameinfo', hostname); return req; } @@ -214,13 +216,13 @@ function resolver(bindingName) { throw new ERR_INVALID_CALLBACK(); } - var req = new QueryReqWrap(); + const req = new QueryReqWrap(); req.bindingName = bindingName; req.callback = callback; req.hostname = name; req.oncomplete = onresolve; req.ttl = !!(options && options.ttl); - var err = this._handle[bindingName](req, toASCII(name)); + const err = this._handle[bindingName](req, toASCII(name)); if (err) throw dnsException(err, bindingName, name); return req; } @@ -228,7 +230,7 @@ function resolver(bindingName) { return query; } -var resolveMap = Object.create(null); +const resolveMap = Object.create(null); Resolver.prototype.resolveAny = resolveMap.ANY = resolver('queryAny'); Resolver.prototype.resolve4 = resolveMap.A = resolver('queryA'); Resolver.prototype.resolve6 = resolveMap.AAAA = resolver('queryAaaa'); diff --git a/lib/domain.js b/lib/domain.js index 9c505a5025a9e0..8d7882c3694e25 100644 --- a/lib/domain.js +++ b/lib/domain.js @@ -41,7 +41,7 @@ const { WeakReference } = internalBinding('util'); // Overwrite process.domain with a getter/setter that will allow for more // effective optimizations -var _domain = [null]; +const _domain = [null]; Object.defineProperty(process, 'domain', { enumerable: true, get: function() { @@ -298,7 +298,7 @@ Domain.prototype.enter = function() { Domain.prototype.exit = function() { // Don't do anything if this domain is not on the stack. - var index = stack.lastIndexOf(this); + const index = stack.lastIndexOf(this); if (index === -1) return; // Exit all domains until this one. @@ -347,7 +347,7 @@ Domain.prototype.add = function(ee) { Domain.prototype.remove = function(ee) { ee.domain = null; - var index = this.members.indexOf(ee); + const index = this.members.indexOf(ee); if (index !== -1) this.members.splice(index, 1); }; @@ -389,7 +389,7 @@ function intercepted(_this, self, cb, fnargs) { return; } - var args = []; + const args = []; var i, ret; self.enter(); @@ -407,7 +407,7 @@ function intercepted(_this, self, cb, fnargs) { Domain.prototype.intercept = function(cb) { - var self = this; + const self = this; function runIntercepted() { return intercepted(this, self, cb, arguments); @@ -432,7 +432,7 @@ function bound(_this, self, cb, fnargs) { Domain.prototype.bind = function(cb) { - var self = this; + const self = this; function runBound() { return bound(this, self, cb, arguments); diff --git a/lib/events.js b/lib/events.js index 8a676773b6507a..fd36e20881fe3f 100644 --- a/lib/events.js +++ b/lib/events.js @@ -283,8 +283,8 @@ function onceWrapper(...args) { } function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target, type, listener }; - var wrapped = onceWrapper.bind(state); + const state = { fired: false, wrapFn: undefined, target, type, listener }; + const wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; @@ -308,15 +308,15 @@ EventEmitter.prototype.prependOnceListener = // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { - var list, events, position, i, originalListener; + let originalListener; checkListener(listener); - events = this._events; + const events = this._events; if (events === undefined) return this; - list = events[type]; + const list = events[type]; if (list === undefined) return this; @@ -329,9 +329,9 @@ EventEmitter.prototype.removeListener = this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { - position = -1; + let position = -1; - for (i = list.length - 1; i >= 0; i--) { + for (var i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; @@ -364,9 +364,7 @@ EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; + const events = this._events; if (events === undefined) return this; @@ -396,13 +394,13 @@ EventEmitter.prototype.removeAllListeners = return this; } - listeners = events[type]; + const listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { + for (var i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } @@ -465,7 +463,7 @@ EventEmitter.prototype.eventNames = function eventNames() { }; function arrayClone(arr, n) { - var copy = new Array(n); + const copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; diff --git a/lib/http.js b/lib/http.js index 5f2fe6dc68f571..5f0b383a480440 100644 --- a/lib/http.js +++ b/lib/http.js @@ -43,7 +43,7 @@ function request(url, options, cb) { } function get(url, options, cb) { - var req = request(url, options, cb); + const req = request(url, options, cb); req.end(); return req; } diff --git a/lib/internal/assert/assertion_error.js b/lib/internal/assert/assertion_error.js index 0e7e8c68954726..2d272907f6b650 100644 --- a/lib/internal/assert/assertion_error.js +++ b/lib/internal/assert/assertion_error.js @@ -292,13 +292,15 @@ class AssertionError extends Error { if (typeof options !== 'object' || options === null) { throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); } - var { - actual, - expected, + const { message, operator, stackStartFn } = options; + let { + actual, + expected + } = options; if (message != null) { super(String(message)); diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 503564df787172..a8c81eae45a495 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -86,7 +86,7 @@ const handleConversion = { }, got(message, handle, emit) { - var server = new net.Server(); + const server = new net.Server(); server.listen(handle, () => { emit(server); }); @@ -116,7 +116,7 @@ const handleConversion = { socket.server._connections--; } - var handle = socket._handle; + const handle = socket._handle; // Remove handle from socket object, it will be closed when the socket // will be sent @@ -161,7 +161,7 @@ const handleConversion = { }, got(message, handle, emit) { - var socket = new net.Socket({ + const socket = new net.Socket({ handle: handle, readable: true, writable: true @@ -203,7 +203,7 @@ const handleConversion = { }, got(message, handle, emit) { - var socket = new dgram.Socket(message.dgramType); + const socket = new dgram.Socket(message.dgramType); socket.bind(handle, () => { emit(socket); @@ -304,21 +304,19 @@ function closePendingHandle(target) { ChildProcess.prototype.spawn = function(options) { - var ipc; - var ipcFd; - var i; + let i = 0; if (options === null || typeof options !== 'object') { throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); } // If no `stdio` option was given - use default - var stdio = options.stdio || 'pipe'; + let stdio = options.stdio || 'pipe'; stdio = _validateStdio(stdio, false); - ipc = stdio.ipc; - ipcFd = stdio.ipcFd; + const ipc = stdio.ipc; + const ipcFd = stdio.ipcFd; stdio = options.stdio = stdio.stdio; if (ipc !== undefined) { @@ -344,7 +342,7 @@ ChildProcess.prototype.spawn = function(options) { else throw new ERR_INVALID_ARG_TYPE('options.args', 'Array', options.args); - var err = this._handle.spawn(options); + const err = this._handle.spawn(options); // Run-time errors should emit an error, not throw an exception. if (err === UV_EACCES || @@ -505,7 +503,7 @@ function setupChannel(target, channel) { if (StringDecoder === undefined) StringDecoder = require('string_decoder').StringDecoder; - var decoder = new StringDecoder('utf8'); + const decoder = new StringDecoder('utf8'); var jsonBuffer = ''; var pendingHandle = null; channel.buffering = false; @@ -619,7 +617,7 @@ function setupChannel(target, channel) { // a message. target._send({ cmd: 'NODE_HANDLE_ACK' }, null, true); - var obj = handleConversion[message.type]; + const obj = handleConversion[message.type]; // Update simultaneous accepts on Windows if (process.platform === 'win32') { @@ -747,11 +745,11 @@ function setupChannel(target, channel) { return this._handleQueue.length === 1; } - var req = new WriteWrap(); + const req = new WriteWrap(); - var string = JSON.stringify(message) + '\n'; - var err = channel.writeUtf8String(req, string, handle); - var wasAsyncWrite = streamBaseState[kLastWriteWasAsync]; + const string = JSON.stringify(message) + '\n'; + const err = channel.writeUtf8String(req, string, handle); + const wasAsyncWrite = streamBaseState[kLastWriteWasAsync]; if (err === 0) { if (handle) { @@ -854,7 +852,7 @@ function setupChannel(target, channel) { if (!target.channel) return; - var eventName = (internal ? 'internalMessage' : 'message'); + const eventName = (internal ? 'internalMessage' : 'message'); process.nextTick(emit, eventName, message, handle); } @@ -984,7 +982,7 @@ function _validateStdio(stdio, sync) { function getSocketList(type, worker, key) { - var sockets = worker.channel.sockets[type]; + const sockets = worker.channel.sockets[type]; var socketList = sockets[key]; if (!socketList) { var Construct = type === 'send' ? SocketListSend : SocketListReceive; @@ -1003,8 +1001,8 @@ function maybeClose(subprocess) { } function spawnSync(opts) { - var options = opts.options; - var result = spawn_sync.spawn(options); + const options = opts.options; + const result = spawn_sync.spawn(options); if (result.output && options.encoding && options.encoding !== 'buffer') { for (var i = 0; i < result.output.length; i++) { diff --git a/lib/internal/console/constructor.js b/lib/internal/console/constructor.js index 12dcee7c7715ff..d329710c88787d 100644 --- a/lib/internal/console/constructor.js +++ b/lib/internal/console/constructor.js @@ -106,7 +106,7 @@ function Console(options /* or: stdout, stderr, ignoreErrors = true */) { } // Bind the prototype functions to this Console instance - var keys = Object.keys(Console.prototype); + const keys = Object.keys(Console.prototype); for (var v = 0; v < keys.length; v++) { var k = keys[v]; // We have to bind the methods grabbed from the instance instead of from diff --git a/lib/internal/crypto/sig.js b/lib/internal/crypto/sig.js index 10c044f82d0a2e..2c3ebc80c4ba36 100644 --- a/lib/internal/crypto/sig.js +++ b/lib/internal/crypto/sig.js @@ -118,9 +118,9 @@ Verify.prototype.verify = function verify(options, signature, sigEncoding) { sigEncoding = sigEncoding || getDefaultEncoding(); // Options specific to RSA - var rsaPadding = getPadding(options); + const rsaPadding = getPadding(options); - var pssSaltLength = getSaltLength(options); + const pssSaltLength = getSaltLength(options); signature = validateArrayBufferView(toBuf(signature, sigEncoding), 'signature'); diff --git a/lib/internal/encoding.js b/lib/internal/encoding.js index 33cfcf9d53a4c4..30458784fbddc8 100644 --- a/lib/internal/encoding.js +++ b/lib/internal/encoding.js @@ -321,8 +321,8 @@ class TextEncoder { validateEncoder(this); if (typeof depth === 'number' && depth < 0) return opts.stylize('[Object]', 'special'); - var ctor = getConstructorOf(this); - var obj = Object.create({ + const ctor = getConstructorOf(this); + const obj = Object.create({ constructor: ctor === null ? TextEncoder : ctor }); obj.encoding = this.encoding; @@ -516,8 +516,8 @@ function makeTextDecoderJS() { validateDecoder(this); if (typeof depth === 'number' && depth < 0) return opts.stylize('[Object]', 'special'); - var ctor = getConstructorOf(this); - var obj = Object.create({ + const ctor = getConstructorOf(this); + const obj = Object.create({ constructor: ctor === null ? TextDecoder : ctor }); obj.encoding = this.encoding; diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index c796371ef242ed..fcbe16ca4893f8 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -97,7 +97,7 @@ function stat(filename) { } function updateChildren(parent, child, scan) { - var children = parent && parent.children; + const children = parent && parent.children; if (children && !(scan && children.includes(child))) children.push(child); } @@ -294,9 +294,9 @@ Module._findPath = function(request, paths, isMain) { return false; } - var cacheKey = request + '\x00' + + const cacheKey = request + '\x00' + (paths.length === 1 ? paths[0] : paths.join('\x00')); - var entry = Module._pathCache[cacheKey]; + const entry = Module._pathCache[cacheKey]; if (entry) return entry; @@ -378,8 +378,8 @@ Module._findPath = function(request, paths, isMain) { }; // 'node_modules' character codes reversed -var nmChars = [ 115, 101, 108, 117, 100, 111, 109, 95, 101, 100, 111, 110 ]; -var nmLen = nmChars.length; +const nmChars = [ 115, 101, 108, 117, 100, 111, 109, 95, 101, 100, 111, 110 ]; +const nmLen = nmChars.length; if (isWindows) { // 'from' is the __dirname of the module. Module._nodeModulePaths = function(from) { @@ -465,8 +465,8 @@ if (isWindows) { // 'index.' character codes -var indexChars = [ 105, 110, 100, 101, 120, 46 ]; -var indexLen = indexChars.length; +const indexChars = [ 105, 110, 100, 101, 120, 46 ]; +const indexLen = indexChars.length; Module._resolveLookupPaths = function(request, parent, newReturn) { if (NativeModule.canBeRequiredByUsers(request)) { debug('looking for %j in []', request); @@ -560,7 +560,7 @@ Module._resolveLookupPaths = function(request, parent, newReturn) { debug('RELATIVE: requested: %s set ID to: %s from %s', request, id, parent.id); - var parentDir = [path.dirname(parent.filename)]; + const parentDir = [path.dirname(parent.filename)]; debug('looking for %j in %j', id, parentDir); return (newReturn ? parentDir : [id, parentDir]); }; @@ -577,9 +577,9 @@ Module._load = function(request, parent, isMain) { debug('Module._load REQUEST %s parent: %s', request, parent.id); } - var filename = Module._resolveFilename(request, parent, isMain); + const filename = Module._resolveFilename(request, parent, isMain); - var cachedModule = Module._cache[filename]; + const cachedModule = Module._cache[filename]; if (cachedModule) { updateChildren(parent, cachedModule, true); return cachedModule.exports; @@ -592,7 +592,7 @@ Module._load = function(request, parent, isMain) { } // Don't call updateChildren(), Module constructor already does. - var module = new Module(filename, parent); + const module = new Module(filename, parent); if (isMain) { process.mainModule = module; @@ -649,7 +649,7 @@ Module._resolveFilename = function(request, parent, isMain, options) { } // Look up the filename first, since that's the cache key. - var filename = Module._findPath(request, paths, isMain); + const filename = Module._findPath(request, paths, isMain); if (!filename) { // eslint-disable-next-line no-restricted-syntax var err = new Error(`Cannot find module '${request}'`); @@ -668,7 +668,7 @@ Module.prototype.load = function(filename) { this.filename = filename; this.paths = Module._nodeModulePaths(path.dirname(filename)); - var extension = findLongestRegisteredExtension(filename); + const extension = findLongestRegisteredExtension(filename); Module._extensions[extension](this, filename); this.loaded = true; @@ -792,12 +792,12 @@ Module.prototype._compile = function(content, filename) { inspectorWrapper = internalBinding('inspector').callAndPauseOnStart; } } - var dirname = path.dirname(filename); - var require = makeRequireFunction(this); + const dirname = path.dirname(filename); + const require = makeRequireFunction(this); var result; - var exports = this.exports; - var thisValue = exports; - var module = this; + const exports = this.exports; + const thisValue = exports; + const module = this; if (inspectorWrapper) { result = inspectorWrapper(compiledWrapper, thisValue, exports, require, module, filename, dirname); @@ -812,7 +812,7 @@ Module.prototype._compile = function(content, filename) { // Native extension for .js Module._extensions['.js'] = function(module, filename) { - var content = fs.readFileSync(filename, 'utf8'); + const content = fs.readFileSync(filename, 'utf8'); module._compile(stripBOM(content), filename); }; @@ -924,7 +924,7 @@ Module._preloadModules = function(requests) { // Preloaded modules have a dummy parent module which is deemed to exist // in the current working directory. This seeds the search path for // preloaded modules. - var parent = new Module('internal/preload', null); + const parent = new Module('internal/preload', null); try { parent.paths = Module._nodeModulePaths(process.cwd()); } catch (e) { diff --git a/lib/internal/socket_list.js b/lib/internal/socket_list.js index 8cd7b1e0ed9057..e6b2a1d7c6a84d 100644 --- a/lib/internal/socket_list.js +++ b/lib/internal/socket_list.js @@ -14,7 +14,7 @@ class SocketListSend extends EventEmitter { } _request(msg, cmd, swallowErrors, callback) { - var self = this; + const self = this; if (!this.child.connected) return onclose(); this.child._send(msg, undefined, swallowErrors); diff --git a/lib/internal/stream_base_commons.js b/lib/internal/stream_base_commons.js index 4f52553692a402..a6805e39be8390 100644 --- a/lib/internal/stream_base_commons.js +++ b/lib/internal/stream_base_commons.js @@ -77,7 +77,7 @@ function onWriteComplete(status) { } function createWriteWrap(handle) { - var req = new WriteWrap(); + const req = new WriteWrap(); req.handle = handle; req.oncomplete = onWriteComplete; @@ -90,7 +90,7 @@ function createWriteWrap(handle) { function writevGeneric(self, data, cb) { const req = createWriteWrap(self[kHandle]); - var allBuffers = data.allBuffers; + const allBuffers = data.allBuffers; var chunks; var i; if (allBuffers) { @@ -105,7 +105,7 @@ function writevGeneric(self, data, cb) { chunks[i * 2 + 1] = entry.encoding; } } - var err = req.handle.writev(req, chunks, allBuffers); + const err = req.handle.writev(req, chunks, allBuffers); // Retain chunks if (err === 0) req._chunks = chunks; @@ -116,7 +116,7 @@ function writevGeneric(self, data, cb) { function writeGeneric(self, data, encoding, cb) { const req = createWriteWrap(self[kHandle]); - var err = handleWriteReq(req, data, encoding); + const err = handleWriteReq(req, data, encoding); afterWriteDispatched(self, req, err, cb); return req; diff --git a/lib/internal/streams/legacy.js b/lib/internal/streams/legacy.js index 41f39cc5f441bf..3898fde80a7f5a 100644 --- a/lib/internal/streams/legacy.js +++ b/lib/internal/streams/legacy.js @@ -9,7 +9,7 @@ function Stream() { util.inherits(Stream, EE); Stream.prototype.pipe = function(dest, options) { - var source = this; + const source = this; function ondata(chunk) { if (dest.writable && dest.write(chunk) === false && source.pause) { diff --git a/lib/internal/url.js b/lib/internal/url.js index f5295e98dfb52e..c066059f2c31fc 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -192,19 +192,19 @@ class URLSearchParams { if (typeof recurseTimes === 'number' && recurseTimes < 0) return ctx.stylize('[Object]', 'special'); - var separator = ', '; - var innerOpts = { ...ctx }; + const separator = ', '; + const innerOpts = { ...ctx }; if (recurseTimes !== null) { innerOpts.depth = recurseTimes - 1; } - var innerInspect = (v) => inspect(v, innerOpts); + const innerInspect = (v) => inspect(v, innerOpts); - var list = this[searchParams]; - var output = []; + const list = this[searchParams]; + const output = []; for (var i = 0; i < list.length; i += 2) output.push(`${innerInspect(list[i])} => ${innerInspect(list[i + 1])}`); - var length = output.reduce( + const length = output.reduce( (prev, cur) => prev + removeColors(cur).length + separator.length, -separator.length ); @@ -220,7 +220,7 @@ class URLSearchParams { function onParseComplete(flags, protocol, username, password, host, port, path, query, fragment) { - var ctx = this[context]; + const ctx = this[context]; ctx.flags = flags; ctx.scheme = protocol; ctx.username = (flags & URL_FLAGS_HAS_USERNAME) !== 0 ? username : ''; @@ -343,9 +343,9 @@ class URL { if (typeof depth === 'number' && depth < 0) return opts.stylize('[Object]', 'special'); - var ctor = getConstructorOf(this); + const ctor = getConstructorOf(this); - var obj = Object.create({ + const obj = Object.create({ constructor: ctor === null ? URL : ctor }); @@ -1253,7 +1253,7 @@ function domainToUnicode(domain) { // options object as expected by the http.request and https.request // APIs. function urlToOptions(url) { - var options = { + const options = { protocol: url.protocol, hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : @@ -1276,7 +1276,7 @@ function urlToOptions(url) { const forwardSlashRegEx = /\//g; function getPathFromURLWin32(url) { - var hostname = url.hostname; + const hostname = url.hostname; var pathname = url.pathname; for (var n = 0; n < pathname.length; n++) { if (pathname[n] === '%') { @@ -1315,7 +1315,7 @@ function getPathFromURLPosix(url) { if (url.hostname !== '') { throw new ERR_INVALID_FILE_URL_HOST(platform); } - var pathname = url.pathname; + const pathname = url.pathname; for (var n = 0; n < pathname.length; n++) { if (pathname[n] === '%') { var third = pathname.codePointAt(n + 2) | 0x20; @@ -1389,7 +1389,7 @@ function toPathIfFileURL(fileURLOrPath) { function constructUrl(flags, protocol, username, password, host, port, path, query, fragment) { - var ctx = new URLContext(); + const ctx = new URLContext(); ctx.flags = flags; ctx.scheme = protocol; ctx.username = (flags & URL_FLAGS_HAS_USERNAME) !== 0 ? username : ''; diff --git a/lib/internal/util.js b/lib/internal/util.js index f5b5fbedd46b4f..2800f6122f8441 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -212,7 +212,7 @@ function getSignalsToNamesMapping() { return signalsToNamesMapping; signalsToNamesMapping = Object.create(null); - for (var key in signals) { + for (const key in signals) { signalsToNamesMapping[signals[key]] = key; } diff --git a/lib/net.js b/lib/net.js index d6d5327f7c513a..fb74e7eb6b0f35 100644 --- a/lib/net.js +++ b/lib/net.js @@ -153,10 +153,10 @@ function createServer(options, connectionListener) { // connect(path, [cb]); // function connect(...args) { - var normalized = normalizeArgs(args); - var options = normalized[0]; + const normalized = normalizeArgs(args); + const options = normalized[0]; debug('createConnection', normalized); - var socket = new Socket(options); + const socket = new Socket(options); if (options.timeout) { socket.setTimeout(options.timeout); @@ -201,7 +201,7 @@ function normalizeArgs(args) { } } - var cb = args[args.length - 1]; + const cb = args[args.length - 1]; if (typeof cb !== 'function') arr = [options, null]; else @@ -359,11 +359,11 @@ Socket.prototype._final = function(cb) { debug('_final: not ended, call shutdown()'); - var req = new ShutdownWrap(); + const req = new ShutdownWrap(); req.oncomplete = afterShutdown; req.handle = this._handle; req.callback = cb; - var err = this._handle.shutdown(req); + const err = this._handle.shutdown(req); if (err === 1) // synchronous finish return afterShutdown.call(req, 0); @@ -373,7 +373,7 @@ Socket.prototype._final = function(cb) { function afterShutdown(status) { - var self = this.handle[owner_symbol]; + const self = this.handle[owner_symbol]; debug('afterShutdown destroyed=%j', self.destroyed, self._readableState); @@ -400,7 +400,7 @@ function writeAfterFIN(chunk, encoding, cb) { } // eslint-disable-next-line no-restricted-syntax - var er = new Error('This socket has been ended by the other party'); + const er = new Error('This socket has been ended by the other party'); er.code = 'EPIPE'; // TODO: defer error events consistently everywhere, not just the cb this.emit('error', er); @@ -875,8 +875,8 @@ Socket.prototype.connect = function(...args) { } else { normalized = normalizeArgs(args); } - var options = normalized[0]; - var cb = normalized[1]; + const options = normalized[0]; + const cb = normalized[1]; if (this.write !== Socket.prototype.write) this.write = Socket.prototype.write; @@ -889,7 +889,7 @@ Socket.prototype.connect = function(...args) { } const { path } = options; - var pipe = !!path; + const pipe = !!path; debug('pipe', pipe, path); if (!this._handle) { @@ -921,8 +921,9 @@ Socket.prototype.connect = function(...args) { function lookupAndConnect(self, options) { - var { port, localAddress, localPort } = options; - var host = options.host || 'localhost'; + const { localAddress, localPort } = options; + const host = options.host || 'localhost'; + let { port } = options; if (localAddress && !isIP(localAddress)) { throw new ERR_INVALID_IP_ADDRESS(localAddress); @@ -944,7 +945,7 @@ function lookupAndConnect(self, options) { port |= 0; // If host is an IP, skip performing a lookup - var addressType = isIP(host); + const addressType = isIP(host); if (addressType) { defaultTriggerAsyncIdScope(self[async_id_symbol], process.nextTick, () => { if (self.connecting) @@ -963,7 +964,7 @@ function lookupAndConnect(self, options) { if (dns === undefined) dns = require('dns'); - var dnsopts = { + const dnsopts = { family: options.family, hints: options.hints || 0 }; @@ -978,7 +979,7 @@ function lookupAndConnect(self, options) { debug('connect: find host', host); debug('connect: dns options', dnsopts); self._host = host; - var lookup = options.lookup || dns.lookup; + const lookup = options.lookup || dns.lookup; defaultTriggerAsyncIdScope(self[async_id_symbol], function() { lookup(host, dnsopts, function emitLookup(err, ip, addressType) { self.emit('lookup', err, ip, addressType, host); @@ -1051,7 +1052,7 @@ Socket.prototype.unref = function() { function afterConnect(status, handle, req, readable, writable) { - var self = handle[owner_symbol]; + const self = handle[owner_symbol]; // Callback may come after call to destroy if (self.destroyed) { @@ -1252,7 +1253,7 @@ function setupListenHandle(address, port, addressType, backlog, fd, flags) { // Use a backlog of 512 entries. We pass 511 to the listen() call because // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1); // which will thus give us a backlog of 512 entries. - var err = this._handle.listen(backlog || 511); + const err = this._handle.listen(backlog || 511); if (err) { var ex = uvExceptionWithHostPort(err, 'listen', address, port); @@ -1336,9 +1337,9 @@ function listenInCluster(server, address, port, addressType, Server.prototype.listen = function(...args) { - var normalized = normalizeArgs(args); + const normalized = normalizeArgs(args); var options = normalized[0]; - var cb = normalized[1]; + const cb = normalized[1]; if (this._handle) { throw new ERR_SERVER_ALREADY_LISTEN(); @@ -1347,7 +1348,7 @@ Server.prototype.listen = function(...args) { if (cb !== null) { this.once('listening', cb); } - var backlogFromArgs = + const backlogFromArgs = // (handle, backlog) or (path, backlog) or (port, backlog) toNumber(args.length > 1 && args[1]) || toNumber(args.length > 2 && args[2]); // (port, host, backlog) @@ -1472,8 +1473,8 @@ Server.prototype.address = function() { }; function onconnection(err, clientHandle) { - var handle = this; - var self = handle[owner_symbol]; + const handle = this; + const self = handle[owner_symbol]; debug('onconnection'); @@ -1487,7 +1488,7 @@ function onconnection(err, clientHandle) { return; } - var socket = new Socket({ + const socket = new Socket({ handle: clientHandle, allowHalfOpen: self.allowHalfOpen, pauseOnCreate: self.pauseOnConnect, diff --git a/lib/path.js b/lib/path.js index a41787dd66f61e..3bfb746251b05b 100644 --- a/lib/path.js +++ b/lib/path.js @@ -819,7 +819,7 @@ const win32 = { if (path.length === 0) return ret; - var len = path.length; + const len = path.length; var rootEnd = 0; let code = path.charCodeAt(0); diff --git a/lib/querystring.js b/lib/querystring.js index bfb6fa33327d0c..240e2e70d6a3f8 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -64,14 +64,14 @@ const unhexTable = [ ]; // A safe fast alternative to decodeURIComponent function unescapeBuffer(s, decodeSpaces) { - var out = Buffer.allocUnsafe(s.length); + const out = Buffer.allocUnsafe(s.length); var index = 0; var outIndex = 0; var currentChar; var nextChar; var hexHigh; var hexLow; - var maxLength = s.length - 2; + const maxLength = s.length - 2; // Flag to know if some hex chars have been decoded var hasHex = false; while (index < s.length) { @@ -214,8 +214,8 @@ function parse(qs, sep, eq, options) { return obj; } - var sepCodes = (!sep ? defSepCodes : charCodes(sep + '')); - var eqCodes = (!eq ? defEqCodes : charCodes(eq + '')); + const sepCodes = (!sep ? defSepCodes : charCodes(sep + '')); + const eqCodes = (!eq ? defEqCodes : charCodes(eq + '')); const sepLen = sepCodes.length; const eqLen = eqCodes.length; diff --git a/lib/readline.js b/lib/readline.js index ffd7cf187411ff..b419c0e12fe760 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -140,7 +140,7 @@ function Interface(input, output, completer, terminal) { terminal = !!output.isTTY; } - var self = this; + const self = this; this.output = output; this.input = input; @@ -346,16 +346,16 @@ Interface.prototype._addHistory = function() { Interface.prototype._refreshLine = function() { // line length - var line = this._prompt + this.line; - var dispPos = this._getDisplayPos(line); - var lineCols = dispPos.cols; - var lineRows = dispPos.rows; + const line = this._prompt + this.line; + const dispPos = this._getDisplayPos(line); + const lineCols = dispPos.cols; + const lineRows = dispPos.rows; // cursor position - var cursorPos = this._getCursorPos(); + const cursorPos = this._getCursorPos(); // First move to the bottom of the current line, based on cursor pos - var prevRows = this.prevRows || 0; + const prevRows = this.prevRows || 0; if (prevRows > 0) { moveCursor(this.output, 0, -prevRows); } @@ -376,7 +376,7 @@ Interface.prototype._refreshLine = function() { // Move cursor to original position. cursorTo(this.output, cursorPos.cols); - var diff = lineRows - cursorPos.rows; + const diff = lineRows - cursorPos.rows; if (diff > 0) { moveCursor(this.output, 0, -diff); } @@ -431,7 +431,7 @@ Interface.prototype._normalWrite = function(b) { } // Run test() on the new string chunk, not on the entire line buffer. - var newPartContainsEnding = lineEnding.test(string); + const newPartContainsEnding = lineEnding.test(string); if (this._line_buffer) { string = this._line_buffer + string; @@ -476,7 +476,7 @@ Interface.prototype._insertString = function(c) { }; Interface.prototype._tabComplete = function(lastKeypressWasTab) { - var self = this; + const self = this; self.pause(); self.completer(self.line.slice(0, self.cursor), function onComplete(err, rv) { @@ -530,7 +530,7 @@ function handleGroup(self, group, width, maxColumns) { if (group.length === 0) { return; } - var minRows = Math.ceil(group.length / maxColumns); + const minRows = Math.ceil(group.length / maxColumns); for (var row = 0; row < minRows; row++) { for (var col = 0; col < maxColumns; col++) { var idx = row * maxColumns + col; @@ -555,9 +555,9 @@ function commonPrefix(strings) { return ''; } if (strings.length === 1) return strings[0]; - var sorted = strings.slice().sort(); - var min = sorted[0]; - var max = sorted[sorted.length - 1]; + const sorted = strings.slice().sort(); + const min = sorted[0]; + const max = sorted[sorted.length - 1]; for (var i = 0, len = min.length; i < len; i++) { if (min[i] !== max[i]) { return min.slice(0, i); @@ -670,7 +670,7 @@ Interface.prototype.clearLine = function() { Interface.prototype._line = function() { - var line = this._addHistory(); + const line = this._addHistory(); this.clearLine(); this._onLine(line); }; @@ -706,7 +706,7 @@ Interface.prototype._historyPrev = function() { // Returns the last character's display position of the given string Interface.prototype._getDisplayPos = function(str) { var offset = 0; - var col = this.columns; + const col = this.columns; var row = 0; var code; str = stripVTControlCharacters(str); @@ -730,17 +730,18 @@ Interface.prototype._getDisplayPos = function(str) { offset += 2; } } - var cols = offset % col; - var rows = row + (offset - cols) / col; + const cols = offset % col; + const rows = row + (offset - cols) / col; return { cols: cols, rows: rows }; }; // Returns current cursor's position and line Interface.prototype._getCursorPos = function() { - var columns = this.columns; - var strBeforeCursor = this._prompt + this.line.substring(0, this.cursor); - var dispPos = this._getDisplayPos(stripVTControlCharacters(strBeforeCursor)); + const columns = this.columns; + const strBeforeCursor = this._prompt + this.line.substring(0, this.cursor); + const dispPos = this._getDisplayPos( + stripVTControlCharacters(strBeforeCursor)); var cols = dispPos.cols; var rows = dispPos.rows; // If the cursor is on a full-width character which steps over the line, @@ -758,15 +759,15 @@ Interface.prototype._getCursorPos = function() { // This function moves cursor dx places to the right // (-dx for left) and refreshes the line if it is needed Interface.prototype._moveCursor = function(dx) { - var oldcursor = this.cursor; - var oldPos = this._getCursorPos(); + const oldcursor = this.cursor; + const oldPos = this._getCursorPos(); this.cursor += dx; // bounds check if (this.cursor < 0) this.cursor = 0; else if (this.cursor > this.line.length) this.cursor = this.line.length; - var newPos = this._getCursorPos(); + const newPos = this._getCursorPos(); // Check if cursors are in the same line if (oldPos.rows === newPos.rows) { diff --git a/lib/repl.js b/lib/repl.js index 2770478e83ce2a..28c18859697655 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -548,7 +548,7 @@ function REPLServer(prompt, } function _parseREPLKeyword(keyword, rest) { - var cmd = this.commands[keyword]; + const cmd = this.commands[keyword]; if (cmd) { cmd.action.call(this, rest); return true; @@ -580,7 +580,7 @@ function REPLServer(prompt, return; } - var empty = self.line.length === 0; + const empty = self.line.length === 0; self.clearLine(); _turnOffEditorMode(self); @@ -774,12 +774,12 @@ exports.start = function(prompt, useGlobal, ignoreUndefined, replMode) { - var repl = new REPLServer(prompt, - source, - eval_, - useGlobal, - ignoreUndefined, - replMode); + const repl = new REPLServer(prompt, + source, + eval_, + useGlobal, + ignoreUndefined, + replMode); if (!exports.repl) exports.repl = repl; replMap.set(repl, repl); return repl; @@ -835,7 +835,7 @@ REPLServer.prototype.createContext = function() { }); } - var module = new CJSModule(''); + const module = new CJSModule(''); module.paths = CJSModule._resolveLookupPaths('', parentModule, true) || []; diff --git a/lib/tls.js b/lib/tls.js index b1bb591760f10c..2be6a15bc5c5e6 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -66,7 +66,7 @@ exports.getCiphers = internalUtil.cachedResult( function convertProtocols(protocols) { const lens = new Array(protocols.length); const buff = Buffer.allocUnsafe(protocols.reduce((p, c, i) => { - var len = Buffer.byteLength(c); + const len = Buffer.byteLength(c); if (len > 255) { throw new ERR_OUT_OF_RANGE('The byte length of the protocol at index ' + `${i} exceeds the maximum length.`, '<= 255', len, true); diff --git a/lib/url.js b/lib/url.js index a51e98ceb82a21..079e54b94dfdd3 100644 --- a/lib/url.js +++ b/lib/url.js @@ -145,7 +145,7 @@ let querystring; function urlParse(url, parseQueryString, slashesDenoteHost) { if (url instanceof Url) return url; - var urlObject = new Url(); + const urlObject = new Url(); urlObject.parse(url, parseQueryString, slashesDenoteHost); return urlObject; } @@ -675,8 +675,8 @@ Url.prototype.resolveObject = function resolveObject(relative) { relative = rel; } - var result = new Url(); - var tkeys = Object.keys(this); + const result = new Url(); + const tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; @@ -762,16 +762,16 @@ Url.prototype.resolveObject = function resolveObject(relative) { return result; } - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'); - var isRelAbs = ( + const isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'); + const isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ); var mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)); - var removeAllDots = mustEndAbs; + const removeAllDots = mustEndAbs; var srcPath = result.pathname && result.pathname.split('/') || []; - var relPath = relative.pathname && relative.pathname.split('/') || []; - var noLeadingSlashes = result.protocol && + const relPath = relative.pathname && relative.pathname.split('/') || []; + const noLeadingSlashes = result.protocol && !slashedProtocol.has(result.protocol); // If the url is a non-slashed url, then relative @@ -868,7 +868,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( + const hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); @@ -904,7 +904,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { srcPath.push(''); } - var isAbsolute = srcPath[0] === '' || + const isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back diff --git a/lib/zlib.js b/lib/zlib.js index 09c3419b4d0b7c..116c89d674fef5 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -152,7 +152,7 @@ function zlibBufferSync(engine, buffer) { } function zlibOnError(message, errno, code) { - var self = this[owner_symbol]; + const self = this[owner_symbol]; // There is no way to cleanly recover. // Continuing only obscures problems. _close(self); @@ -322,7 +322,7 @@ function maxFlush(a, b) { const flushBuffer = Buffer.alloc(0); ZlibBase.prototype.flush = function(kind, callback) { - var ws = this._writableState; + const ws = this._writableState; if (typeof kind === 'function' || (kind === undefined && !callback)) { callback = kind; @@ -365,7 +365,7 @@ ZlibBase.prototype._transform = function(chunk, encoding, cb) { } // For the last chunk, also apply `_finishFlushFlag`. - var ws = this._writableState; + const ws = this._writableState; if ((ws.ending || ws.ended) && ws.length === chunk.byteLength) { flushFlag = maxFlush(flushFlag, this._finishFlushFlag); } @@ -390,11 +390,11 @@ function processChunkSync(self, chunk, flushFlag) { var buffers = null; var nread = 0; var inputRead = 0; - var state = self._writeState; - var handle = self._handle; + const state = self._writeState; + const handle = self._handle; var buffer = self._outBuffer; var offset = self._outOffset; - var chunkSize = self._chunkSize; + const chunkSize = self._chunkSize; var error; self.on('error', function onError(er) { @@ -464,7 +464,7 @@ function processChunkSync(self, chunk, flushFlag) { } function processChunk(self, chunk, flushFlag, cb) { - var handle = self._handle; + const handle = self._handle; assert(handle, 'zlib binding closed'); handle.buffer = chunk; @@ -487,9 +487,9 @@ function processCallback() { // This callback's context (`this`) is the `_handle` (ZCtx) object. It is // important to null out the values once they are no longer needed since // `_handle` can stay in memory long after the buffer is needed. - var handle = this; - var self = this[owner_symbol]; - var state = self._writeState; + const handle = this; + const self = this[owner_symbol]; + const state = self._writeState; if (self._hadError) { this.buffer = null; @@ -501,13 +501,13 @@ function processCallback() { return; } - var availOutAfter = state[0]; - var availInAfter = state[1]; + const availOutAfter = state[0]; + const availInAfter = state[1]; const inDelta = handle.availInBefore - availInAfter; self.bytesWritten += inDelta; - var have = handle.availOutBefore - availOutAfter; + const have = handle.availOutBefore - availOutAfter; if (have > 0) { var out = self._outBuffer.slice(self._outOffset, self._outOffset + have); self._outOffset += have;