diff --git a/lib/_http_agent.js b/lib/_http_agent.js index ddd36c158ec3ca..645f884bf7633d 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -46,7 +46,7 @@ function Agent(options) { EventEmitter.call(this); - var self = this; + const self = this; self.defaultPort = 80; self.protocol = 'http:'; @@ -64,7 +64,7 @@ function Agent(options) { self.maxFreeSockets = self.options.maxFreeSockets || 256; self.on('free', function(socket, options) { - var name = self.getName(options); + const name = self.getName(options); debug('agent.on(free)', name); if (socket.writable && @@ -77,13 +77,13 @@ function Agent(options) { } else { // If there are no pending requests, then put it in // the freeSockets pool, but only if we're allowed to do so. - var req = socket._httpMessage; + const req = socket._httpMessage; if (req && req.shouldKeepAlive && socket.writable && self.keepAlive) { var freeSockets = self.freeSockets[name]; - var freeLen = freeSockets ? freeSockets.length : 0; + const freeLen = freeSockets ? freeSockets.length : 0; var count = freeLen; if (self.sockets[name]) count += self.sockets[name].length; @@ -156,17 +156,17 @@ Agent.prototype.addRequest = function addRequest(req, options, port/*legacy*/, } } - 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. - var socket = this.freeSockets[name].shift(); + const socket = this.freeSockets[name].shift(); // Guard against an uninitialized or user supplied Socket. if (socket._handle && typeof socket._handle.asyncReset === 'function') { // Assign the handle a new asyncId and run any init() hooks. @@ -196,7 +196,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/*legacy*/, }; Agent.prototype.createSocket = function createSocket(req, options, cb) { - var self = this; + const self = this; options = util._extend({}, options); util._extend(options, self.options); @@ -208,7 +208,7 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) { } } - var name = self.getName(options); + const name = self.getName(options); options._agentKey = name; debug('createConnection', name, options); @@ -264,19 +264,19 @@ 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) sets.push(this.freeSockets); for (var sk = 0; sk < sets.length; sk++) { - var sockets = sets[sk]; + const sockets = sets[sk]; if (sockets[name]) { - var index = sockets[name].indexOf(s); + const index = sockets[name].indexOf(s); if (index !== -1) { sockets[name].splice(index, 1); // Don't leak @@ -288,7 +288,7 @@ Agent.prototype.removeSocket = function removeSocket(s, options) { if (this.requests[name] && this.requests[name].length) { debug('removeSocket, have a request, make a socket'); - var req = this.requests[name][0]; + const req = this.requests[name][0]; // If we have pending requests and a socket gets closed make a new one this.createSocket(req, options, handleSocketCreation(req, false)); } @@ -307,12 +307,12 @@ 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); + const set = sets[s]; + const keys = Object.keys(set); for (var v = 0; v < keys.length; v++) { - var setName = set[keys[v]]; + const setName = set[keys[v]]; for (var n = 0; n < setName.length; n++) { setName[n].destroy(); } diff --git a/lib/_http_client.js b/lib/_http_client.js index e972a3d5b9e9fd..33bbed9d69a28b 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -92,7 +92,7 @@ function ClientRequest(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) { @@ -107,7 +107,7 @@ function ClientRequest(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; @@ -129,20 +129,20 @@ function ClientRequest(options, cb) { throw new errors.Error('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); + const setHost = (options.setHost === undefined); 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 && !methodIsString) { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'method', 'string', method); @@ -162,12 +162,12 @@ function ClientRequest(options, cb) { this.once('response', cb); } - var headersArray = Array.isArray(options.headers); + const headersArray = Array.isArray(options.headers); if (!headersArray) { if (options.headers) { - var keys = Object.keys(options.headers); + const keys = Object.keys(options.headers); for (var i = 0; i < keys.length; i++) { - var key = keys[i]; + const key = keys[i]; this.setHeader(key, options.headers[key]); } } @@ -177,7 +177,7 @@ function ClientRequest(options, cb) { // For the Host header, ensure that IPv6 addresses are enclosed // in square brackets, as defined by URI formatting // https://tools.ietf.org/html/rfc3986#section-3.2.2 - var posColon = hostHeader.indexOf(':'); + const posColon = hostHeader.indexOf(':'); if (posColon !== -1 && hostHeader.indexOf(':', posColon + 1) !== -1 && hostHeader.charCodeAt(0) !== 91/*'['*/) { @@ -228,7 +228,7 @@ function ClientRequest(options, cb) { var called = false; - var oncreate = (err, socket) => { + const oncreate = (err, socket) => { if (called) return; called = true; @@ -244,7 +244,7 @@ function ClientRequest(options, cb) { if (this.socketPath) { this._last = true; this.shouldKeepAlive = false; - var optionsPath = { + const optionsPath = { path: this.socketPath, timeout: this.timeout, rejectUnauthorized: !!options.rejectUnauthorized @@ -341,15 +341,15 @@ function emitAbortNT() { function createHangUpError() { - 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. @@ -359,12 +359,12 @@ function socketCloseListener() { // NOTE: It's important to get parser here, because it could be freed by // the `socketOnData`. - var parser = socket.parser; + const parser = socket.parser; req.emit('close'); if (req.res && req.res.readable) { // Socket closed before we emitted 'end' below. req.res.emit('aborted'); - var res = req.res; + const res = req.res; res.on('end', function() { res.emit('close'); }); @@ -392,8 +392,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) { @@ -406,7 +406,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); @@ -419,16 +419,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 @@ -444,13 +444,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); @@ -459,17 +459,17 @@ function socketOnData(d) { req.emit('error', ret); } else if (parser.incoming && parser.incoming.upgrade) { // Upgrade or CONNECT - var bytesParsed = ret; - var res = parser.incoming; + const bytesParsed = ret; + const res = parser.incoming; req.res = res; socket.removeListener('data', socketOnData); socket.removeListener('end', socketOnEnd); parser.finish(); - var bodyHead = d.slice(bytesParsed, d.length); + const bodyHead = d.slice(bytesParsed, d.length); - var eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade'; + const eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade'; if (req.listenerCount(eventName) > 0) { req.upgradeOrConnect = true; @@ -503,8 +503,8 @@ function socketOnData(d) { // client function parserOnIncomingClient(res, shouldKeepAlive) { - var socket = this.socket; - var req = socket._httpMessage; + const socket = this.socket; + const req = socket._httpMessage; // propagate "domain" setting... @@ -534,7 +534,7 @@ function parserOnIncomingClient(res, shouldKeepAlive) { // but *can* have a content-length which actually corresponds // to the content-length of the entity-body had the request // been a GET. - var isHeadResponse = req.method === 'HEAD'; + const isHeadResponse = req.method === 'HEAD'; debug('AGENT isHeadResponse', isHeadResponse); if (res.statusCode === 100) { @@ -561,7 +561,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 @@ -574,7 +574,7 @@ function parserOnIncomingClient(res, shouldKeepAlive) { // client function responseKeepAlive(res, req) { - var socket = req.socket; + const socket = req.socket; if (!req.shouldKeepAlive) { if (socket.writable) { @@ -625,7 +625,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); @@ -731,7 +731,7 @@ ClientRequest.prototype.setTimeout = function setTimeout(msecs, callback) { // Set timeoutCb so that it'll get cleaned up on request end this.timeoutCb = emitTimeout; if (this.socket) { - var sock = this.socket; + const sock = this.socket; this.socket.once('connect', function() { sock.setTimeout(msecs, emitTimeout); }); diff --git a/lib/_http_common.js b/lib/_http_common.js index 59eaec5811618e..d66df35f18d914 100644 --- a/lib/_http_common.js +++ b/lib/_http_common.js @@ -62,7 +62,7 @@ function parserOnHeaders(headers, url) { function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, url, statusCode, statusMessage, upgrade, shouldKeepAlive) { - var parser = this; + const parser = this; if (!headers) { headers = parser._headers; @@ -125,32 +125,32 @@ function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, // XXX This is a mess. // TODO: http.Parser should be a Writable emits request/response events. function parserOnBody(b, start, len) { - var parser = this; - var stream = parser.incoming; + const parser = this; + const stream = parser.incoming; // if the stream has already been removed, then drop it. if (!stream) return; - var socket = stream.socket; + const socket = stream.socket; // pretend this was the result of a stream._read call. if (len > 0 && !stream._dumped) { - var slice = b.slice(start, start + len); - var ret = stream.push(slice); + const slice = b.slice(start, start + len); + const ret = stream.push(slice); if (!ret) readStop(socket); } } function parserOnMessageComplete() { - var parser = this; - var stream = parser.incoming; + const parser = this; + const stream = parser.incoming; if (stream) { stream.complete = true; // Emit any trailing headers. - var headers = parser._headers; + const headers = parser._headers; if (headers) { parser.incoming._addHeaderLines(headers, headers.length); parser._headers = []; @@ -166,8 +166,8 @@ function parserOnMessageComplete() { } -var parsers = new FreeList('parsers', 1000, function() { - var parser = new HTTPParser(HTTPParser.REQUEST); +const parsers = new FreeList('parsers', 1000, function() { + const parser = new HTTPParser(HTTPParser.REQUEST); parser._headers = []; parser._url = ''; @@ -260,7 +260,7 @@ function httpSocketSetup(socket) { * so take care when making changes to the implementation so that the source * code size does not exceed v8's default max_inlined_source_size setting. **/ -var validTokens = [ +const validTokens = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 @@ -310,7 +310,7 @@ function checkIsHttpToken(val) { * so take care when making changes to the implementation so that the source * code size does not exceed v8's default max_inlined_source_size setting. **/ -var validHdrChars = [ +const validHdrChars = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 32 - 47 diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index 6e5aff1cc9c1f2..9581b9be9ca34c 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -285,7 +285,7 @@ function matchKnownFields(field) { 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 451cc91a485bda..d9e304d3ddb602 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -39,10 +39,10 @@ const CRLF = common.CRLF; const debug = common.debug; const utcDate = internalHttp.utcDate; -var RE_FIELDS = +const RE_FIELDS = /^(?:Connection|Transfer-Encoding|Content-Length|Date|Expect|Trailer|Upgrade)$/i; -var RE_CONN_VALUES = /(?:^|\W)close|upgrade(?:$|\W)/ig; -var RE_TE_CHUNKED = common.chunkExpression; +const RE_CONN_VALUES = /(?:^|\W)close|upgrade(?:$|\W)/ig; +const RE_TE_CHUNKED = common.chunkExpression; // isCookieField performs a case-insensitive comparison of a provided string // against the word "cookie." This method (at least as of V8 5.4) is faster than @@ -166,14 +166,14 @@ OutgoingMessage.prototype._renderHeaders = function _renderHeaders() { throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'render'); } - var headersMap = this[outHeadersKey]; + const headersMap = this[outHeadersKey]; if (!headersMap) return {}; - var headers = {}; - var keys = Object.keys(headersMap); + const headers = {}; + const keys = Object.keys(headersMap); for (var i = 0, l = keys.length; i < l; i++) { - var key = keys[i]; + const key = keys[i]; headers[headersMap[key][0]] = headersMap[key][1]; } return headers; @@ -224,7 +224,7 @@ OutgoingMessage.prototype._send = function _send(data, encoding, callback) { (encoding === 'utf8' || encoding === 'latin1' || !encoding)) { data = this._header + data; } else { - var header = this._header; + const header = this._header; if (this.output.length === 0) { this.output = [header]; this.outputEncodings = ['latin1']; @@ -284,7 +284,7 @@ OutgoingMessage.prototype._storeHeader = _storeHeader; function _storeHeader(firstLine, headers) { // firstLine in the case of request is: 'GET /index.html HTTP/1.1\r\n' // in the case of response it is: 'HTTP/1.1 200 OK\r\n' - var state = { + const state = { connection: false, connUpgrade: false, contLen: false, @@ -303,7 +303,7 @@ function _storeHeader(firstLine, headers) { var j; if (headers === this[outHeadersKey]) { for (key in headers) { - var entry = headers[key]; + const entry = headers[key]; field = entry[0]; value = entry[1]; @@ -331,7 +331,7 @@ function _storeHeader(firstLine, headers) { } } } else if (headers) { - var keys = Object.keys(headers); + const keys = Object.keys(headers); for (i = 0; i < keys.length; i++) { field = keys[i]; value = headers[field]; @@ -368,7 +368,7 @@ function _storeHeader(firstLine, headers) { // It was pointed out that this might confuse reverse proxies to the point // of creating security liabilities, so suppress the zero chunk and force // the connection to close. - var statusCode = this.statusCode; + const statusCode = this.statusCode; if ((statusCode === 204 || statusCode === 304) && this.chunkedEncoding) { debug(statusCode + ' response should not use chunked encoding,' + ' closing connection.'); @@ -381,7 +381,7 @@ function _storeHeader(firstLine, headers) { this._last = true; this.shouldKeepAlive = false; } else if (!state.connection) { - var shouldSendKeepAlive = this.shouldKeepAlive && + const shouldSendKeepAlive = this.shouldKeepAlive && (state.contLen || this.useChunkedEncodingByDefault || this.agent); if (shouldSendKeepAlive) { state.header += 'Connection: keep-alive\r\n'; @@ -464,10 +464,10 @@ function matchConnValue(self, state, value) { } function matchHeader(self, state, field, value) { - var m = RE_FIELDS.exec(field); + const m = RE_FIELDS.exec(field); if (!m) return; - var len = m[0].length; + const len = m[0].length; if (len === 10) { state.connection = true; matchConnValue(self, state, value); @@ -481,7 +481,7 @@ function matchHeader(self, state, field, value) { } else if (len === 6) { state.expect = true; } else if (len === 7) { - var ch = m[0].charCodeAt(0); + const ch = m[0].charCodeAt(0); if (ch === 85 || ch === 117) state.upgrade = true; else @@ -534,7 +534,7 @@ OutgoingMessage.prototype.getHeader = function getHeader(name) { if (!this[outHeadersKey]) return; - var entry = this[outHeadersKey][name.toLowerCase()]; + const entry = this[outHeadersKey][name.toLowerCase()]; if (!entry) return; return entry[1]; @@ -581,7 +581,7 @@ OutgoingMessage.prototype.removeHeader = function removeHeader(name) { throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'remove'); } - var key = name.toLowerCase(); + const key = name.toLowerCase(); switch (key.length) { case 10: @@ -626,7 +626,7 @@ OutgoingMessage.prototype.write = function write(chunk, encoding, callback) { function write_(msg, chunk, encoding, callback, fromEnd) { if (msg.finished) { - var err = new Error('write after end'); + const err = new Error('write after end'); nextTick(msg.socket && msg.socket[async_id_symbol], writeAfterEndNT.bind(msg), err, @@ -700,11 +700,11 @@ function escapeHeaderValue(value) { 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]; + const key = keys[i]; if (isArray) { field = headers[key][0]; value = headers[key][1]; @@ -766,7 +766,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); var ret; if (this._hasBody && this.chunkedEncoding) { @@ -821,7 +821,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) { @@ -840,13 +840,13 @@ OutgoingMessage.prototype._flush = function _flush() { OutgoingMessage.prototype._flushOutput = function _flushOutput(socket) { var ret; - var outputLength = this.output.length; + const outputLength = this.output.length; if (outputLength <= 0) return ret; - var output = this.output; - var outputEncodings = this.outputEncodings; - var outputCallbacks = this.outputCallbacks; + const output = this.output; + const outputEncodings = this.outputEncodings; + const outputCallbacks = this.outputCallbacks; socket.cork(); for (var i = 0; i < outputLength; i++) { ret = socket.write(output[i], outputEncodings[i], outputCallbacks[i]); diff --git a/lib/_http_server.js b/lib/_http_server.js index 8ea7cfbace9df0..305b10d2b46266 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -182,7 +182,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) { @@ -207,7 +207,7 @@ function writeHead(statusCode, reason, obj) { // Slow-case: when progressive API and header fields are passed. var k; if (obj) { - var keys = Object.keys(obj); + const keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { k = keys[i]; if (k) this.setHeader(k, obj[k]); @@ -226,7 +226,7 @@ function writeHead(statusCode, reason, obj) { if (common._checkInvalidHeaderChar(this.statusMessage)) throw new errors.Error('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)) { @@ -304,7 +304,7 @@ function connectionListener(socket) { socket.setTimeout(this.timeout); socket.on('timeout', socketOnTimeout); - var parser = parsers.alloc(); + const parser = parsers.alloc(); parser.reinitialize(HTTPParser.REQUEST); parser.socket = socket; socket.parser = parser; @@ -318,7 +318,7 @@ function connectionListener(socket) { parser.maxHeaderPairs = 2000; } - var state = { + const state = { onData: null, onEnd: null, onClose: null, @@ -351,7 +351,7 @@ function connectionListener(socket) { socket.on = socketOnWrap; // We only consume the socket if it has never been consumed before. - var external = socket._handle._externalStream; + const external = socket._handle._externalStream; if (!socket._handle._consumed && external) { parser._consumed = true; socket._handle._consumed = true; @@ -373,7 +373,7 @@ function updateOutgoingData(socket, state, delta) { } function socketOnDrain(socket, state) { - var needPause = state.outgoingData > socket._writableState.highWaterMark; + const needPause = state.outgoingData > socket._writableState.highWaterMark; // If we previously paused, then start reading again. if (socket._paused && !needPause) { @@ -385,11 +385,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(); @@ -407,7 +407,7 @@ function socketOnClose(socket, state) { function abortIncoming(incoming) { while (incoming.length) { - var req = incoming.shift(); + const req = incoming.shift(); req.emit('aborted'); req.emit('close'); } @@ -415,7 +415,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'); @@ -439,7 +439,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); } @@ -466,8 +466,8 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) { socketOnError.call(socket, ret); } else if (parser.incoming && parser.incoming.upgrade) { // Upgrade or CONNECT - var bytesParsed = ret; - var req = parser.incoming; + const bytesParsed = ret; + const req = parser.incoming; debug('SERVER upgrade or connect', req.method); if (!d) @@ -483,10 +483,10 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) { freeParser(parser, req, null); parser = null; - var eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade'; + const eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade'; if (server.listenerCount(eventName) > 0) { debug('SERVER have listener for %s', eventName); - var bodyHead = d.slice(bytesParsed, d.length); + const bodyHead = d.slice(bytesParsed, d.length); // TODO(isaacs): Need a way to reset a stream to fresh state // IE, not flowing, and not explicitly paused. @@ -531,7 +531,7 @@ function resOnFinish(req, res, socket, state, server) { } } else { // start sending the next message - var m = state.outgoing.shift(); + const m = state.outgoing.shift(); if (m) { m.assignSocket(socket); } @@ -550,7 +550,7 @@ function parserOnIncoming(server, socket, state, req, keepAlive) { // so that we don't become overwhelmed by a flood of // pipelined requests that may never be resolved. if (!socket._paused) { - var ws = socket._writableState; + const ws = socket._writableState; if (ws.needDrain || state.outgoingData >= ws.highWaterMark) { socket._paused = true; // We also need to pause the parser, but don't do that until after @@ -560,7 +560,7 @@ function parserOnIncoming(server, socket, state, req, keepAlive) { } } - var res = new ServerResponse(req); + const res = new ServerResponse(req); res._onPendingData = updateOutgoingData.bind(undefined, socket, state); res.shouldKeepAlive = keepAlive; @@ -649,7 +649,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_duplex.js b/lib/_stream_duplex.js index 7440cd08729e1c..0233351748f337 100644 --- a/lib/_stream_duplex.js +++ b/lib/_stream_duplex.js @@ -34,9 +34,9 @@ const Writable = require('_stream_writable'); util.inherits(Duplex, Readable); -var keys = Object.keys(Writable.prototype); +const keys = Object.keys(Writable.prototype); for (var v = 0; v < keys.length; v++) { - var method = keys[v]; + const method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 1a0bc8902ac802..ca7638447ab9fa 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -28,7 +28,7 @@ const EE = require('events'); const Stream = require('stream'); // TODO(bmeurer): Change this back to const once hole checks are // properly optimized away early in Ignition+TurboFan. -var Buffer = require('buffer').Buffer; +const Buffer = require('buffer').Buffer; const util = require('util'); const debug = util.debuglog('stream'); const BufferList = require('internal/streams/BufferList'); @@ -66,7 +66,7 @@ function ReadableState(options, stream) { // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Stream.Duplex; + const isDuplex = stream instanceof Stream.Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away @@ -77,9 +77,9 @@ function ReadableState(options, stream) { // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + const hwm = options.highWaterMark; + const readableHwm = options.readableHighWaterMark; + const defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm; @@ -192,7 +192,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) { @@ -217,7 +217,7 @@ Readable.prototype.unshift = function(chunk) { }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; + const state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); @@ -368,8 +368,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; @@ -483,7 +483,7 @@ Readable.prototype.read = function(n) { function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { - var chunk = state.decoder.end(); + const chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; @@ -499,7 +499,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; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); @@ -555,8 +555,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: @@ -572,11 +572,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 @@ -602,7 +602,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; @@ -639,7 +639,7 @@ Readable.prototype.pipe = function(dest, pipeOpts) { function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; - var ret = dest.write(chunk); + const ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write @@ -701,7 +701,7 @@ Readable.prototype.pipe = function(dest, pipeOpts) { function pipeOnDrain(src) { return function() { - var state = src._readableState; + const state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; @@ -714,8 +714,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) @@ -743,8 +743,8 @@ Readable.prototype.unpipe = function(dest) { if (!dest) { // remove all. - var dests = state.pipes; - var len = state.pipesCount; + const dests = state.pipes; + const len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; @@ -755,7 +755,7 @@ Readable.prototype.unpipe = function(dest) { } // try to find the right one. - var index = state.pipes.indexOf(dest); + const index = state.pipes.indexOf(dest); if (index === -1) return this; @@ -803,7 +803,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'); state.flowing = true; @@ -853,14 +853,14 @@ 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; - var self = this; + const self = this; stream.on('end', function() { debug('wrapped end'); if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); + const chunk = state.decoder.end(); if (chunk && chunk.length) self.push(chunk); } @@ -879,7 +879,7 @@ Readable.prototype.wrap = function(stream) { else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = self.push(chunk); + const ret = self.push(chunk); if (!ret) { paused = true; stream.pause(); @@ -888,7 +888,7 @@ Readable.prototype.wrap = function(stream) { // proxy all the other methods. // important when wrapping filters and duplexes. - for (var i in stream) { + for (const i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function(method) { return function() { @@ -1038,7 +1038,7 @@ function copyFromBuffer(n, list) { } function endReadable(stream) { - var state = stream._readableState; + const state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js index ba80f5c09cf94f..b74a9939eb2f70 100644 --- a/lib/_stream_transform.js +++ b/lib/_stream_transform.js @@ -71,10 +71,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 errors.Error('ERR_MULTIPLE_CALLBACK')); @@ -88,7 +88,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); @@ -161,12 +161,12 @@ 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; if (!ts.transforming) { - var rs = this._readableState; + const rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) @@ -178,7 +178,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.writecb && !ts.transforming) { ts.transforming = true; diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 7de77958d56b4c..927fc2c63f21af 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -46,7 +46,7 @@ function WritableState(options, stream) { // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Stream.Duplex; + const isDuplex = stream instanceof Stream.Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. @@ -58,9 +58,9 @@ function WritableState(options, stream) { // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + const hwm = options.highWaterMark; + const writableHwm = options.writableHighWaterMark; + const defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm; @@ -90,7 +90,7 @@ function WritableState(options, stream) { // 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 @@ -148,14 +148,14 @@ function WritableState(options, stream) { // 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; @@ -233,7 +233,7 @@ Writable.prototype.pipe = function() { function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); + const er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); process.nextTick(cb, er); @@ -262,9 +262,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); @@ -294,13 +294,13 @@ Writable.prototype.write = function(chunk, encoding, cb) { }; Writable.prototype.cork = function() { - var state = this._writableState; + const state = this._writableState; state.corked++; }; Writable.prototype.uncork = function() { - var state = this._writableState; + const state = this._writableState; if (state.corked) { state.corked--; @@ -338,24 +338,24 @@ function decodeChunk(state, chunk, encoding) { // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); + const newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; 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; if (state.writing || state.corked) { - var last = state.lastBufferedRequest; + const last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk, encoding, @@ -420,9 +420,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; onwriteStateUpdate(state); @@ -430,7 +430,7 @@ function onwrite(stream, er) { onwriteError(stream, state, sync, er, cb); else { // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + const finished = needFinish(state); if (!finished && !state.corked && @@ -472,9 +472,9 @@ function clearBuffer(stream, state) { if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; + const l = state.bufferedRequestCount; + const buffer = new Array(l); + const holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; @@ -498,17 +498,17 @@ function clearBuffer(stream, state) { state.corkedRequestsFree = holder.next; holder.next = null; } else { - var corkReq = { next: null, entry: null, finish: undefined }; + const corkReq = { next: null, entry: null, finish: undefined }; corkReq.finish = onCorkedFinish.bind(undefined, corkReq, state); state.corkedRequestsFree = corkReq; } } else { // Slow case, write chunks one-by-one while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + const chunk = entry.chunk; + const encoding = entry.encoding; + const cb = entry.callback; + const len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; @@ -537,7 +537,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; @@ -595,7 +595,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) { @@ -623,7 +623,7 @@ function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { - var cb = entry.callback; + const cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; diff --git a/lib/_tls_common.js b/lib/_tls_common.js index fa31fd7de64654..7b53669898eb4c 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -72,7 +72,7 @@ exports.createSecureContext = function createSecureContext(options, context) { if (options.honorCipherOrder) secureOptions |= SSL_OP_CIPHER_SERVER_PREFERENCE; - var c = new SecureContext(options.secureProtocol, secureOptions, context); + const c = new SecureContext(options.secureProtocol, secureOptions, context); var i; var val; @@ -80,7 +80,7 @@ exports.createSecureContext = function createSecureContext(options, context) { // NOTE: It's important to add CA before the cert to be able to load // cert's issuer in C++ code. - var ca = options.ca; + const ca = options.ca; if (ca) { if (Array.isArray(ca)) { for (i = 0; i < ca.length; ++i) { @@ -96,7 +96,7 @@ exports.createSecureContext = function createSecureContext(options, context) { c.context.addRootCerts(); } - var cert = options.cert; + const cert = options.cert; if (cert) { if (Array.isArray(cert)) { for (i = 0; i < cert.length; ++i) { @@ -114,8 +114,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) { @@ -209,7 +209,7 @@ exports.translatePeerCertificate = function translatePeerCertificate(c) { } if (c.subject != null) c.subject = parseCertString(c.subject); if (c.infoAccess != null) { - var info = c.infoAccess; + const info = c.infoAccess; c.infoAccess = Object.create(null); // XXX: More key validation? diff --git a/lib/_tls_legacy.js b/lib/_tls_legacy.js index b25be2d6a3b444..445ac497da2361 100644 --- a/lib/_tls_legacy.js +++ b/lib/_tls_legacy.js @@ -59,7 +59,7 @@ SlabBuffer.prototype.use = function use(context, fn, size) { if (size !== null) actualSize = Math.min(size, actualSize); - var bytes = fn.call(context, this.pool, this.offset, actualSize); + const bytes = fn.call(context, this.pool, this.offset, actualSize); if (bytes > 0) { this.offset += bytes; this.remaining -= bytes; @@ -151,10 +151,10 @@ function onCryptoStreamEnd() { // NOTE: Called once `this._opposite` is set. CryptoStream.prototype.init = function init() { - var self = this; + const self = this; this._opposite.on('sslOutEnd', function() { if (self._sslOutCb) { - var cb = self._sslOutCb; + const cb = self._sslOutCb; self._sslOutCb = null; cb(null); } @@ -297,7 +297,7 @@ CryptoStream.prototype._read = function _read(size) { this.pair.maybeInitFinished(); // Create new buffer if previous was filled up - var pool = this._buffer.pool; + const pool = this._buffer.pool; if (this._buffer.isFull) this._buffer.create(); assert(bytesRead >= 0); @@ -338,8 +338,8 @@ CryptoStream.prototype._read = function _read(size) { this.push(pool.slice(start, start + bytesRead)); } - // Let users know that we've some internal data to read - var halfRead = this._internallyPendingBytes() !== 0; + // var users know that we've some internal data to read + const halfRead = this._internallyPendingBytes() !== 0; // Smart check to avoid invoking 'sslOutEnd' in the most of the cases if (this._halfRead !== halfRead) { @@ -446,7 +446,7 @@ CryptoStream.prototype.destroySoon = function(err) { } else { // Wait for both `finish` and `end` events to ensure that all data that // was written on this side was read from the other side. - var self = this; + const self = this; var waiting = 1; function finish() { if (--waiting === 0) self.destroy(); @@ -525,7 +525,7 @@ function CleartextStream(pair, options) { // This is a fake kludge to support how the http impl sits // on top of net Sockets - var self = this; + const self = this; this._handle = { readStop: function() { self._reading = false; @@ -613,9 +613,9 @@ EncryptedStream.prototype._internallyPendingBytes = function() { function onhandshakestart() { debug('onhandshakestart'); - var self = this; - var ssl = self.ssl; - var now = Timer.now(); + const self = this; + const ssl = self.ssl; + const now = Timer.now(); assert(now >= ssl.lastHandshakeTime); @@ -623,7 +623,7 @@ function onhandshakestart() { ssl.handshakes = 0; } - var first = (ssl.lastHandshakeTime === 0); + const first = (ssl.lastHandshakeTime === 0); ssl.lastHandshakeTime = now; if (first) return; @@ -632,7 +632,7 @@ function onhandshakestart() { // state machine and OpenSSL is not re-entrant. We cannot allow the user's // callback to destroy the connection right now, it would crash and burn. setImmediate(function() { - var err = new Error('TLS session renegotiation attack detected'); + const err = new Error('TLS session renegotiation attack detected'); if (self.cleartext) self.cleartext.emit('error', err); }); } @@ -678,7 +678,7 @@ function onclienthello(hello) { function onnewsession(key, session) { if (!this.server) return; - var self = this; + const self = this; var once = false; if (!self.server.emit('newSession', key, session, done)) @@ -865,7 +865,7 @@ SecurePair.prototype.error = function(returnOnly) { if (!this._secureEstablished) { // Emit ECONNRESET instead of zero return if (!err || err.message === 'ZERO_RETURN') { - var connReset = new Error('socket hang up'); + const connReset = new Error('socket hang up'); connReset.code = 'ECONNRESET'; connReset.sslError = err && err.message; @@ -894,7 +894,7 @@ function pipe(pair, socket) { }); pair.fd = socket.fd; - var cleartext = pair.cleartext; + const cleartext = pair.cleartext; cleartext.socket = socket; cleartext.encrypted = pair.encrypted; cleartext.authorized = false; diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 7615de6bd71cb5..83b6e28854045c 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -42,9 +42,9 @@ const kDisableRenegotiation = Symbol('disable-renegotiation'); function onhandshakestart() { debug('onhandshakestart'); - var self = this; - var ssl = self._handle; - var now = Timer.now(); + const self = this; + const ssl = self._handle; + const now = Timer.now(); assert(now >= ssl.lastHandshakeTime); @@ -52,7 +52,7 @@ function onhandshakestart() { ssl.handshakes = 0; } - var first = (ssl.lastHandshakeTime === 0); + const first = (ssl.lastHandshakeTime === 0); ssl.lastHandshakeTime = now; if (first) return; @@ -61,7 +61,7 @@ function onhandshakestart() { // state machine and OpenSSL is not re-entrant. We cannot allow the user's // callback to destroy the connection right now, it would crash and burn. setImmediate(function() { - var err = new errors.Error('ERR_TLS_SESSION_ATTACK'); + const err = new errors.Error('ERR_TLS_SESSION_ATTACK'); self._emitTLSError(err); }); } @@ -176,7 +176,7 @@ function requestOCSP(self, hello, ctx, cb) { function onclienthello(hello) { - var self = this; + const self = this; loadSession(self, hello, function(err) { if (err) @@ -188,8 +188,8 @@ function onclienthello(hello) { function oncertcb(info) { - var self = this; - var servername = info.servername; + const self = this; + const servername = info.servername; loadSNI(self, servername, function(err, ctx) { if (err) @@ -215,7 +215,7 @@ function onnewsession(key, session) { if (!this.server) return; - var self = this; + const self = this; var once = false; this._newSessionPending = true; @@ -315,7 +315,7 @@ function TLSSocket(socket, options) { 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', @@ -375,14 +375,14 @@ 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() : new TCP(); handle.owner = this; } // Wrap socket's handle - var context = options.secureContext || + const context = options.secureContext || options.credentials || tls.createSecureContext(options); res = tls_wrap.wrap(handle._externalStream, @@ -425,9 +425,9 @@ TLSSocket.prototype._destroySSL = function _destroySSL() { }; TLSSocket.prototype._init = function(socket, wrap) { - var self = this; - var options = this._tlsOptions; - var ssl = this._handle; + const self = this; + const options = this._tlsOptions; + const ssl = this._handle; // lib/net.js expect this value to be non-zero if write hasn't been flushed // immediately @@ -593,7 +593,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); }; @@ -797,12 +797,12 @@ function Server(options, listener) { this._contexts = []; - var self = this; + const self = this; // Handle option defaults: this.setOptions(options); - var sharedCreds = tls.createSecureContext({ + const sharedCreds = tls.createSecureContext({ pfx: self.pfx, key: self.key, passphrase: self.passphrase, @@ -819,7 +819,7 @@ function Server(options, listener) { }); this._sharedCreds = sharedCreds; - var timeout = options.handshakeTimeout || (120 * 1000); + const timeout = options.handshakeTimeout || (120 * 1000); if (typeof timeout !== 'number') { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'timeout', 'number'); @@ -835,7 +835,7 @@ function Server(options, listener) { // constructor call net.Server.call(this, function(raw_socket) { - var socket = new TLSSocket(raw_socket, { + const socket = new TLSSocket(raw_socket, { secureContext: sharedCreds, isServer: true, server: self, @@ -849,7 +849,7 @@ function Server(options, listener) { socket.on('secure', function() { if (socket._requestCert) { - var verifyError = socket._handle.verifyError(); + const verifyError = socket._handle.verifyError(); if (verifyError) { socket.authorizationError = verifyError.code; @@ -873,7 +873,7 @@ function Server(options, listener) { // Emit ECONNRESET if (!socket._controlReleased && !errorEmitted) { errorEmitted = true; - var connReset = new Error('socket hang up'); + const connReset = new Error('socket hang up'); connReset.code = 'ECONNRESET'; self.emit('tlsClientError', connReset, socket); } @@ -938,7 +938,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 @@ -963,7 +963,7 @@ Server.prototype.addContext = function(servername, context) { throw new errors.Error('ERR_TLS_REQUIRED_SERVER_NAME'); } - var re = new RegExp('^' + + const re = new RegExp('^' + servername.replace(/([.^$+?\-\\[\]{}])/g, '\\$1') .replace(/\*/g, '[^.]*') + '$'); @@ -999,9 +999,9 @@ function SNICallback(servername, callback) { // // function normalizeConnectArgs(listArgs) { - var args = net._normalizeArgs(listArgs); - var options = args[0]; - var cb = args[1]; + const args = net._normalizeArgs(listArgs); + const options = args[0]; + const cb = args[1]; // If args[0] was options, then normalize dealt with it. // If args[0] is port, or args[0], args[1] is host, port, we need to @@ -1020,9 +1020,9 @@ function normalizeConnectArgs(listArgs) { exports.connect = function(...args /* [port,] [host,] [options,] [cb] */) { args = normalizeConnectArgs(args); var options = args[0]; - var cb = args[1]; + const cb = args[1]; - var defaults = { + const defaults = { rejectUnauthorized: '0' !== process.env.NODE_TLS_REJECT_UNAUTHORIZED, ciphers: tls.DEFAULT_CIPHERS, checkServerIdentity: tls.checkServerIdentity, @@ -1040,7 +1040,7 @@ exports.connect = function(...args /* [port,] [host,] [options,] [cb] */) { 'options.minDHSize is not a positive number: ' + options.minDHSize); - var hostname = options.servername || + const hostname = options.servername || options.host || (options.socket && options.socket._host) || 'localhost'; @@ -1050,7 +1050,7 @@ exports.connect = function(...args /* [port,] [host,] [options,] [cb] */) { tls.convertNPNProtocols(options.NPNProtocols, NPN); tls.convertALPNProtocols(options.ALPNProtocols, ALPN); - var socket = new TLSSocket(options.socket, { + const socket = new TLSSocket(options.socket, { pipe: options.path && !options.port, secureContext: context, isServer: false, @@ -1097,9 +1097,9 @@ exports.connect = function(...args /* [port,] [host,] [options,] [cb] */) { socket.on('secure', function() { // Check the size of DHE parameter above minimum requirement // specified in options. - var ekeyinfo = socket.getEphemeralKeyInfo(); + const ekeyinfo = socket.getEphemeralKeyInfo(); if (ekeyinfo.type === 'DH' && ekeyinfo.size < options.minDHSize) { - var err = new errors.Error('ERR_TLS_DH_PARAM_SIZE', ekeyinfo.size); + const err = new errors.Error('ERR_TLS_DH_PARAM_SIZE', ekeyinfo.size); socket.emit('error', err); socket.destroy(); return; @@ -1110,7 +1110,7 @@ exports.connect = function(...args /* [port,] [host,] [options,] [cb] */) { // Verify that server's identity matches it's certificate's names // Unless server has resumed our existing session if (!verifyError && !socket.isSessionReused()) { - var cert = socket.getPeerCertificate(); + const cert = socket.getPeerCertificate(); verifyError = options.checkServerIdentity(hostname, cert); } @@ -1137,7 +1137,7 @@ exports.connect = function(...args /* [port,] [host,] [options,] [cb] */) { // NOTE: This logic is shared with _http_client.js if (!socket._hadError) { socket._hadError = true; - var error = new Error('socket hang up'); + const error = new Error('socket hang up'); error.code = 'ECONNRESET'; error.path = options.path; error.host = options.host; diff --git a/lib/buffer.js b/lib/buffer.js index 7a44ca0f260539..0f0414750fc1e9 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -211,7 +211,7 @@ Buffer.from = function from(value, encodingOrOffset, length) { if (valueOf !== null && valueOf !== undefined && valueOf !== value) return Buffer.from(valueOf, encodingOrOffset, length); - var b = fromObject(value); + const b = fromObject(value); if (b) return b; @@ -309,7 +309,7 @@ function allocate(size) { if (size < (Buffer.poolSize >>> 1)) { if (size > (poolSize - poolOffset)) createPool(); - var b = new FastBuffer(allocPool, poolOffset, size); + const b = new FastBuffer(allocPool, poolOffset, size); poolOffset += size; alignPool(); return b; @@ -465,10 +465,10 @@ Buffer.concat = function concat(list, length) { length = length >>> 0; } - var buffer = Buffer.allocUnsafe(length); + const buffer = Buffer.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; i++) { - var buf = list[i]; + const buf = list[i]; if (!isUint8Array(buf)) throw kConcatErr; _copy(buf, buffer, pos); @@ -682,7 +682,7 @@ Buffer.prototype.equals = function equals(b) { // Override how buffers are presented by util.inspect(). Buffer.prototype[customInspectSymbol] = function inspect() { var str = ''; - var max = exports.INSPECT_MAX_BYTES; + const max = exports.INSPECT_MAX_BYTES; str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); if (this.length > max) str += ' ... '; @@ -853,7 +853,7 @@ Buffer.prototype.fill = function fill(val, start, end, encoding) { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'encoding', 'string', encoding); } - var normalizedEncoding = normalizeEncoding(encoding); + const normalizedEncoding = normalizeEncoding(encoding); if (normalizedEncoding === undefined) { throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding); } @@ -863,7 +863,7 @@ Buffer.prototype.fill = function fill(val, start, end, encoding) { // which is rather surprising. val = 0; } else if (val.length === 1) { - var code = val.charCodeAt(0); + const code = val.charCodeAt(0); if ((normalizedEncoding === 'utf8' && code < 128) || normalizedEncoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. @@ -911,7 +911,7 @@ Buffer.prototype.write = function write(string, offset, length, encoding) { length = undefined; } - var remaining = this.length - offset; + const remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; @@ -1143,7 +1143,7 @@ Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); - var val = this[offset]; + const val = this[offset]; return !(val & 0x80) ? val : (0xff - val + 1) * -1; }; @@ -1152,7 +1152,7 @@ Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); + const val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val; }; @@ -1161,7 +1161,7 @@ Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); + const val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val; }; diff --git a/lib/child_process.js b/lib/child_process.js index b2679c5f50a186..f04298e2829a12 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -101,7 +101,7 @@ exports.fork = function(modulePath /*, args, options*/) { exports._forkChild = function(fd) { // set process.send() - var p = new Pipe(true); + const p = new Pipe(true); p.open(fd); p.unref(); const control = setupChannel(process, p); @@ -133,7 +133,7 @@ function normalizeExecArgs(command, options, callback) { exports.exec = function(command /*, options, callback*/) { - var opts = normalizeExecArgs.apply(null, arguments); + const opts = normalizeExecArgs.apply(null, arguments); return exports.execFile(opts.file, opts.options, opts.callback); @@ -164,7 +164,7 @@ Object.defineProperty(exports.exec, util.promisify.custom, { exports.execFile = function(file /*, args, options, callback*/) { var args = []; var callback; - var options = { + const options = { encoding: 'utf8', timeout: 0, maxBuffer: 200 * 1024, @@ -204,7 +204,7 @@ exports.execFile = function(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, @@ -464,10 +464,10 @@ function normalizeSpawnArguments(file, args, options) { args.unshift(file); } - var env = options.env || process.env; - var envPairs = []; + const env = options.env || process.env; + const envPairs = []; - for (var key in env) { + for (const key in env) { envPairs.push(key + '=' + env[key]); } @@ -483,9 +483,9 @@ function normalizeSpawnArguments(file, args, options) { var spawn = exports.spawn = function(/*file, args, options*/) { - var opts = normalizeSpawnArguments.apply(null, arguments); - var options = opts.options; - var child = new ChildProcess(); + const opts = normalizeSpawnArguments.apply(null, arguments); + const options = opts.options; + const child = new ChildProcess(); debug('spawn', opts.args, options); @@ -505,9 +505,9 @@ var spawn = exports.spawn = function(/*file, args, options*/) { }; function spawnSync(/*file, args, options*/) { - var opts = normalizeSpawnArguments.apply(null, arguments); + const opts = normalizeSpawnArguments.apply(null, arguments); - var options = opts.options; + const options = opts.options; debug('spawnSync', opts.args, options); @@ -527,15 +527,15 @@ function spawnSync(/*file, args, options*/) { options.stdio = _validateStdio(options.stdio || 'pipe', true).stdio; if (options.input) { - var stdin = options.stdio[0] = util._extend({}, options.stdio[0]); + const stdin = options.stdio[0] = util._extend({}, options.stdio[0]); stdin.input = options.input; } // We may want to pass data in on any given fd, ensure it is a valid buffer for (var i = 0; i < options.stdio.length; i++) { - var input = options.stdio[i] && options.stdio[i].input; + const input = options.stdio[i] && options.stdio[i].input; if (input != null) { - var pipe = options.stdio[i] = util._extend({}, options.stdio[i]); + const pipe = options.stdio[i] = util._extend({}, options.stdio[i]); if (isUint8Array(input)) { pipe.input = input; } else if (typeof input === 'string') { @@ -574,15 +574,15 @@ function checkExecSyncError(ret, args, cmd) { function execFileSync(/*command, args, options*/) { - var opts = normalizeSpawnArguments.apply(null, arguments); - var inheritStderr = !opts.options.stdio; + const opts = normalizeSpawnArguments.apply(null, arguments); + 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; @@ -593,15 +593,15 @@ exports.execFileSync = execFileSync; function execSync(command /*, options*/) { - var opts = normalizeExecArgs.apply(null, arguments); - var inheritStderr = !opts.options.stdio; + const opts = normalizeExecArgs.apply(null, arguments); + 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/console.js b/lib/console.js index 54c8aba8299565..c5e372bd231a46 100644 --- a/lib/console.js +++ b/lib/console.js @@ -41,7 +41,7 @@ function Console(stdout, stderr, ignoreErrors = true) { throw new errors.TypeError('ERR_CONSOLE_WRITABLE_STREAM', 'stderr'); } - var prop = { + const prop = { writable: true, enumerable: false, configurable: true @@ -65,9 +65,9 @@ function Console(stdout, stderr, ignoreErrors = true) { this[kGroupIndent] = ''; // 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]; + const k = keys[v]; this[k] = this[k].bind(this); } } diff --git a/lib/crypto.js b/lib/crypto.js index 56795e23f24af9..b1e09041289b50 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -304,8 +304,8 @@ Sign.prototype.sign = function sign(options, encoding) { if (!options) throw new Error('No key provided to sign'); - var key = options.key || options; - var passphrase = options.passphrase || null; + const key = options.key || options; + const passphrase = options.passphrase || null; // Options specific to RSA var rsaPadding = constants.RSA_PKCS1_PADDING; @@ -354,7 +354,7 @@ Verify.prototype._write = Sign.prototype._write; Verify.prototype.update = Sign.prototype.update; Verify.prototype.verify = function verify(options, signature, sigEncoding) { - var key = options.key || options; + const key = options.key || options; sigEncoding = sigEncoding || exports.DEFAULT_ENCODING; // Options specific to RSA @@ -382,18 +382,18 @@ Verify.prototype.verify = function verify(options, signature, sigEncoding) { function rsaPublic(method, defaultPadding) { return function(options, buffer) { - var key = options.key || options; - var padding = options.padding || defaultPadding; - var passphrase = options.passphrase || null; + const key = options.key || options; + const padding = options.padding || defaultPadding; + const passphrase = options.passphrase || null; return method(toBuf(key), buffer, padding, passphrase); }; } function rsaPrivate(method, defaultPadding) { return function(options, buffer) { - var key = options.key || options; - var passphrase = options.passphrase || null; - var padding = options.padding || defaultPadding; + const key = options.key || options; + const passphrase = options.passphrase || null; + const padding = options.padding || defaultPadding; return method(toBuf(key), buffer, padding, passphrase); }; } @@ -643,7 +643,7 @@ function pbkdf2(password, salt, iterations, keylen, digest, callback) { return binding.PBKDF2(password, salt, iterations, keylen, digest, callback); // at this point, we need to handle encodings. - var encoding = exports.DEFAULT_ENCODING; + const encoding = exports.DEFAULT_ENCODING; if (callback) { function next(er, ret) { if (ret) @@ -652,7 +652,7 @@ function pbkdf2(password, salt, iterations, keylen, digest, callback) { } binding.PBKDF2(password, salt, iterations, keylen, digest, next); } else { - var ret = binding.PBKDF2(password, salt, iterations, keylen, digest); + const ret = binding.PBKDF2(password, salt, iterations, keylen, digest); return ret.toString(encoding); } } diff --git a/lib/dgram.js b/lib/dgram.js index fa2f476096d993..cdf7808ee783d3 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -85,10 +85,10 @@ function _createSocketHandle(address, port, addressType, fd, flags) { // Opening an existing fd is not supported for UDP handles. assert(typeof fd !== 'number' || fd < 0); - var handle = newHandle(addressType); + const handle = newHandle(addressType); if (port || address) { - var err = handle.bind(address, port || 0, flags); + const err = handle.bind(address, port || 0, flags); if (err) { handle.close(); return err; @@ -113,7 +113,7 @@ function Socket(type, listener) { this[kOptionSymbol].sendBufferSize = options.sendBufferSize; } - var handle = newHandle(type, lookup); + const handle = newHandle(type, lookup); handle.owner = this; this._handle = handle; @@ -238,7 +238,7 @@ Socket.prototype.bind = function(port_, address_ /*, callback*/) { if (cluster.isWorker && !exclusive) { const onHandle = (err, handle) => { if (err) { - var ex = exceptionWithHostPort(err, 'bind', ip, port); + const ex = exceptionWithHostPort(err, 'bind', ip, port); this.emit('error', ex); this._bindState = BIND_STATE_UNBOUND; return; @@ -264,7 +264,7 @@ Socket.prototype.bind = function(port_, address_ /*, callback*/) { const err = this._handle.bind(ip, port || 0, flags); if (err) { - var ex = exceptionWithHostPort(err, 'bind', ip, port); + const ex = exceptionWithHostPort(err, 'bind', ip, port); this.emit('error', ex); this._bindState = BIND_STATE_UNBOUND; // Todo: close? @@ -326,7 +326,7 @@ function fixBufferList(list) { const newlist = new Array(list.length); for (var i = 0, l = list.length; i < l; i++) { - var buf = list[i]; + const buf = list[i]; if (typeof buf === 'string') newlist[i] = Buffer.from(buf); else if (!isUint8Array(buf)) @@ -469,7 +469,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; @@ -481,12 +481,12 @@ function doSend(ex, self, ip, list, address, port, callback) { // SendWrap above until send() is called. So don't set the init trigger id // until now. setInitTriggerId(self[async_id_symbol]); - var err = self._handle.send(req, - list, - list.length, - port, - ip, - !!callback); + const err = self._handle.send(req, + list, + list.length, + port, + ip, + !!callback); if (err && callback) { // don't emit as error, dgram_legacy.js compatibility const ex = exceptionWithHostPort(err, 'send', address, port); @@ -531,8 +531,8 @@ function socketCloseNT(self) { Socket.prototype.address = function() { this._healthCheck(); - var out = {}; - var err = this._handle.getsockname(out); + const out = {}; + const err = this._handle.getsockname(out); if (err) { throw errnoException(err, 'getsockname'); } @@ -542,7 +542,7 @@ Socket.prototype.address = function() { Socket.prototype.setBroadcast = function(arg) { - var err = this._handle.setBroadcast(arg ? 1 : 0); + const err = this._handle.setBroadcast(arg ? 1 : 0); if (err) { throw errnoException(err, 'setBroadcast'); } @@ -554,7 +554,7 @@ Socket.prototype.setTTL = function(ttl) { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'ttl', 'number', ttl); } - var err = this._handle.setTTL(ttl); + const err = this._handle.setTTL(ttl); if (err) { throw errnoException(err, 'setTTL'); } @@ -568,7 +568,7 @@ Socket.prototype.setMulticastTTL = function(ttl) { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'ttl', 'number', ttl); } - var err = this._handle.setMulticastTTL(ttl); + const err = this._handle.setMulticastTTL(ttl); if (err) { throw errnoException(err, 'setMulticastTTL'); } @@ -578,7 +578,7 @@ Socket.prototype.setMulticastTTL = function(ttl) { Socket.prototype.setMulticastLoopback = function(arg) { - var err = this._handle.setMulticastLoopback(arg ? 1 : 0); + const err = this._handle.setMulticastLoopback(arg ? 1 : 0); if (err) { throw errnoException(err, 'setMulticastLoopback'); } @@ -595,7 +595,7 @@ Socket.prototype.addMembership = function(multicastAddress, throw new errors.TypeError('ERR_MISSING_ARGS', 'multicastAddress'); } - var err = this._handle.addMembership(multicastAddress, interfaceAddress); + const err = this._handle.addMembership(multicastAddress, interfaceAddress); if (err) { throw errnoException(err, 'addMembership'); } @@ -610,7 +610,7 @@ Socket.prototype.dropMembership = function(multicastAddress, throw new errors.TypeError('ERR_MISSING_ARGS', 'multicastAddress'); } - var err = this._handle.dropMembership(multicastAddress, interfaceAddress); + const err = this._handle.dropMembership(multicastAddress, interfaceAddress); if (err) { throw errnoException(err, 'dropMembership'); } @@ -636,7 +636,7 @@ Socket.prototype._stopReceiving = function() { function onMessage(nread, handle, buf, rinfo) { - var self = handle.owner; + const self = handle.owner; if (nread < 0) { return self.emit('error', errnoException(nread, 'recvmsg')); } diff --git a/lib/dns.js b/lib/dns.js index e536f1b4f942de..7c77a50511bc55 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -112,7 +112,7 @@ function onlookupall(err, addresses) { return this.callback(errnoException(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] = { @@ -170,7 +170,7 @@ function lookup(hostname, options, callback) { return {}; } - var matchedFamily = isIP(hostname); + const matchedFamily = isIP(hostname); if (matchedFamily) { if (all) { process.nextTick( @@ -181,13 +181,13 @@ 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, hostname, family, hints, verbatim); + const err = cares.getaddrinfo(req, hostname, family, hints, verbatim); if (err) { process.nextTick(callback, errnoException(err, 'getaddrinfo', hostname)); return {}; @@ -223,13 +223,13 @@ function lookupService(host, port, callback) { port = +port; - var req = new GetNameInfoReqWrap(); + const req = new GetNameInfoReqWrap(); req.callback = callback; req.host = host; req.port = port; req.oncomplete = onlookupservice; - var err = cares.getnameinfo(req, host, port); + const err = cares.getnameinfo(req, host, port); if (err) throw errnoException(err, 'getnameinfo', host); return req; } @@ -274,13 +274,13 @@ function resolver(bindingName) { throw new errors.TypeError('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, name); + const err = this._handle[bindingName](req, name); if (err) throw errnoException(err, bindingName); return req; } @@ -288,7 +288,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'); @@ -378,7 +378,7 @@ function setServers(servers) { // reset the servers to the old servers, because ares probably unset them this._handle.setServers(orig.join(',')); - var err = cares.strerror(errorNumber); + const err = cares.strerror(errorNumber); throw new errors.Error('ERR_DNS_SET_SERVERS_FAILED', err, servers); } } diff --git a/lib/domain.js b/lib/domain.js index 5cef123da82b54..90d1fb737e1529 100644 --- a/lib/domain.js +++ b/lib/domain.js @@ -37,7 +37,7 @@ EventEmitter.usingDomains = true; // 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() { @@ -173,7 +173,7 @@ Domain.prototype.enter = function() { Domain.prototype.exit = function() { // skip disposed domains, as usual, but also don't do anything if this // domain is not on the stack. - var index = stack.lastIndexOf(this); + const index = stack.lastIndexOf(this); if (this._disposed || index === -1) return; // exit all domains until this one. @@ -217,7 +217,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); }; @@ -231,8 +231,8 @@ Domain.prototype.run = function(fn) { this.enter(); if (arguments.length >= 2) { - var len = arguments.length; - var args = new Array(len - 1); + const len = arguments.length; + const args = new Array(len - 1); for (var i = 1; i < len; i++) args[i - 1] = arguments[i]; @@ -252,7 +252,7 @@ function intercepted(_this, self, cb, fnargs) { return; if (fnargs[0] && fnargs[0] instanceof Error) { - var er = fnargs[0]; + const er = fnargs[0]; util._extend(er, { domainBound: cb, domainThrown: false, @@ -262,7 +262,7 @@ function intercepted(_this, self, cb, fnargs) { return; } - var args = []; + const args = []; var i, ret; self.enter(); @@ -280,7 +280,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); @@ -308,7 +308,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 dce1dc48fa42e8..6558bad1403f67 100644 --- a/lib/events.js +++ b/lib/events.js @@ -104,8 +104,8 @@ function emitNone(handler, isFn, self) { if (isFn) handler.call(self); else { - var len = handler.length; - var listeners = arrayClone(handler, len); + const len = handler.length; + const listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self); } @@ -114,8 +114,8 @@ function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1); else { - var len = handler.length; - var listeners = arrayClone(handler, len); + const len = handler.length; + const listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1); } @@ -124,8 +124,8 @@ function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2); else { - var len = handler.length; - var listeners = arrayClone(handler, len); + const len = handler.length; + const listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2); } @@ -134,8 +134,8 @@ function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3); else { - var len = handler.length; - var listeners = arrayClone(handler, len); + const len = handler.length; + const listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2, arg3); } @@ -145,8 +145,8 @@ function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args); else { - var len = handler.length; - var listeners = arrayClone(handler, len); + const len = handler.length; + const listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].apply(self, args); } @@ -199,7 +199,7 @@ EventEmitter.prototype.emit = function emit(type) { needDomainExit = true; } - var isFn = typeof handler === 'function'; + const isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases @@ -329,8 +329,8 @@ function onceWrapper() { } 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; @@ -428,7 +428,7 @@ EventEmitter.prototype.removeAllListeners = // emit removeListener for all listeners on all events if (arguments.length === 0) { - var keys = Object.keys(events); + const keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; @@ -458,7 +458,7 @@ EventEmitter.prototype.removeAllListeners = EventEmitter.prototype.listeners = function listeners(type) { var evlistener; var ret; - var events = this._events; + const events = this._events; if (!events) ret = []; @@ -512,7 +512,7 @@ function spliceOne(list, index) { } 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/fs.js b/lib/fs.js index fb1001c8c09d6f..33a3721d5ff39e 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -85,8 +85,8 @@ function getOptions(options, defaultOptions) { } function copyObject(source) { - var target = {}; - for (var key in source) + const target = {}; + for (const key in source) target[key] = source[key]; return target; } @@ -101,7 +101,7 @@ function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. if (DEBUG) { - var backtrace = new Error(); + const backtrace = new Error(); return function(err) { if (err) { backtrace.stack = err.name + ': ' + err.message + @@ -290,7 +290,7 @@ fs.access = function(path, mode, callback) { return; mode = mode | 0; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = makeCallback(callback); binding.access(pathModule._makeLong(path), mode, req); }; @@ -311,7 +311,7 @@ fs.exists = function(path, callback) { if (handleError((path = getPathFromURL(path)), cb)) return; if (!nullCheck(path, cb)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = cb; binding.stat(pathModule._makeLong(path), req); function cb(err) { @@ -348,9 +348,9 @@ fs.readFile = function(path, options, callback) { if (!nullCheck(path, callback)) return; - var context = new ReadFileContext(callback, options.encoding); + const context = new ReadFileContext(callback, options.encoding); context.isUserFd = isFd(path); // file descriptor ownership - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.context = context; req.oncomplete = readFileAfterOpen; @@ -396,7 +396,7 @@ ReadFileContext.prototype.read = function() { length = this.size - this.pos; } - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = readFileAfterRead; req.context = this; @@ -404,7 +404,7 @@ ReadFileContext.prototype.read = function() { }; ReadFileContext.prototype.close = function(err) { - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = readFileAfterClose; req.context = this; this.err = err; @@ -420,7 +420,7 @@ ReadFileContext.prototype.close = function(err) { }; function readFileAfterOpen(err, fd) { - var context = this.context; + const context = this.context; if (err) { context.callback(err); @@ -429,14 +429,14 @@ function readFileAfterOpen(err, fd) { context.fd = fd; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = readFileAfterStat; req.context = context; binding.fstat(fd, req); } function readFileAfterStat(err) { - var context = this.context; + const context = this.context; if (err) return context.close(err); @@ -466,7 +466,7 @@ function readFileAfterStat(err) { } function readFileAfterRead(err, bytesRead) { - var context = this.context; + const context = this.context; if (err) return context.close(err); @@ -489,9 +489,9 @@ function readFileAfterRead(err, bytesRead) { } function readFileAfterClose(err) { - var context = this.context; + const context = this.context; var buffer = null; - var callback = context.callback; + const callback = context.callback; if (context.err || err) return callback(context.err || err); @@ -555,8 +555,8 @@ function tryReadSync(fd, isUserFd, buffer, pos, len) { fs.readFileSync = function(path, options) { options = getOptions(options, { flag: 'r' }); - var isUserFd = isFd(path); // file descriptor ownership - var fd = isUserFd ? path : fs.openSync(path, options.flag || 'r', 0o666); + const isUserFd = isFd(path); // file descriptor ownership + const fd = isUserFd ? path : fs.openSync(path, options.flag || 'r', 0o666); tryStatSync(fd, isUserFd); // Use stats array directly to avoid creating an fs.Stats instance just for @@ -615,7 +615,7 @@ fs.readFileSync = function(path, options) { // list to make the arguments clear. fs.close = function(fd, callback) { - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = makeCallback(callback); binding.close(fd, req); }; @@ -635,14 +635,14 @@ function modeNum(m, def) { } fs.open = function(path, flags, mode, callback_) { - var callback = makeCallback(arguments[arguments.length - 1]); + const callback = makeCallback(arguments[arguments.length - 1]); mode = modeNum(mode, 0o666); if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.open(pathModule._makeLong(path), @@ -670,7 +670,7 @@ fs.read = function(fd, buffer, offset, length, position, callback) { callback && callback(err, bytesRead || 0, buffer); } - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = wrapper; binding.read(fd, buffer, offset, length, position, req); @@ -697,7 +697,7 @@ fs.write = function(fd, buffer, offset, length, position, callback) { callback(err, written || 0, buffer); } - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = wrapper; if (isUint8Array(buffer)) { @@ -763,7 +763,7 @@ fs.rename = function(oldPath, newPath, callback) { if (!nullCheck(oldPath, callback)) return; if (!nullCheck(newPath, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.rename(pathModule._makeLong(oldPath), pathModule._makeLong(newPath), @@ -793,7 +793,7 @@ fs.truncate = function(path, len, callback) { callback = maybeCallback(callback); fs.open(path, 'r+', function(er, fd) { if (er) return callback(er); - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = function oncomplete(er) { fs.close(fd, function(er2) { callback(er || er2); @@ -812,7 +812,7 @@ fs.truncateSync = function(path, len) { len = 0; } // allow error to be thrown, but still close fd. - var fd = fs.openSync(path, 'r+'); + const fd = fs.openSync(path, 'r+'); var ret; try { @@ -830,7 +830,7 @@ fs.ftruncate = function(fd, len, callback) { } else if (len === undefined) { len = 0; } - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = makeCallback(callback); binding.ftruncate(fd, len, req); }; @@ -847,7 +847,7 @@ fs.rmdir = function(path, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.rmdir(pathModule._makeLong(path), req); }; @@ -859,7 +859,7 @@ fs.rmdirSync = function(path) { }; fs.fdatasync = function(fd, callback) { - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = makeCallback(callback); binding.fdatasync(fd, req); }; @@ -869,7 +869,7 @@ fs.fdatasyncSync = function(fd) { }; fs.fsync = function(fd, callback) { - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = makeCallback(callback); binding.fsync(fd, req); }; @@ -884,7 +884,7 @@ fs.mkdir = function(path, mode, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.mkdir(pathModule._makeLong(path), modeNum(mode, 0o777), @@ -904,7 +904,7 @@ fs.readdir = function(path, options, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.readdir(pathModule._makeLong(path), options.encoding, req); }; @@ -917,7 +917,7 @@ fs.readdirSync = function(path, options) { }; fs.fstat = function(fd, callback) { - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = makeStatsCallback(callback); binding.fstat(fd, req); }; @@ -927,7 +927,7 @@ fs.lstat = function(path, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.lstat(pathModule._makeLong(path), req); }; @@ -937,7 +937,7 @@ fs.stat = function(path, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.stat(pathModule._makeLong(path), req); }; @@ -967,7 +967,7 @@ fs.readlink = function(path, options, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.readlink(pathModule._makeLong(path), options.encoding, req); }; @@ -995,8 +995,8 @@ function preprocessSymlinkDestination(path, type, linkPath) { } fs.symlink = function(target, path, type_, callback_) { - var type = (typeof type_ === 'string' ? type_ : null); - var callback = makeCallback(arguments[arguments.length - 1]); + const type = (typeof type_ === 'string' ? type_ : null); + const callback = makeCallback(arguments[arguments.length - 1]); if (handleError((target = getPathFromURL(target)), callback)) return; @@ -1007,7 +1007,7 @@ fs.symlink = function(target, path, type_, callback_) { if (!nullCheck(target, callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.symlink(preprocessSymlinkDestination(target, type, path), @@ -1040,7 +1040,7 @@ fs.link = function(existingPath, newPath, callback) { if (!nullCheck(existingPath, callback)) return; if (!nullCheck(newPath, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.link(pathModule._makeLong(existingPath), @@ -1062,7 +1062,7 @@ fs.unlink = function(path, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.unlink(pathModule._makeLong(path), req); }; @@ -1074,7 +1074,7 @@ fs.unlinkSync = function(path) { }; fs.fchmod = function(fd, mode, callback) { - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = makeCallback(callback); binding.fchmod(fd, modeNum(mode), req); }; @@ -1102,7 +1102,7 @@ if (constants.O_SYMLINK !== undefined) { }; fs.lchmodSync = function(path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); + const fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); // Prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. @@ -1126,7 +1126,7 @@ fs.chmod = function(path, mode, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.chmod(pathModule._makeLong(path), modeNum(mode), @@ -1152,13 +1152,13 @@ if (constants.O_SYMLINK !== undefined) { }; fs.lchownSync = function(path, uid, gid) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); + const fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); return fs.fchownSync(fd, uid, gid); }; } fs.fchown = function(fd, uid, gid, callback) { - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = makeCallback(callback); binding.fchown(fd, uid, gid, req); }; @@ -1172,7 +1172,7 @@ fs.chown = function(path, uid, gid, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.chown(pathModule._makeLong(path), uid, gid, req); }; @@ -1213,7 +1213,7 @@ fs.utimes = function(path, atime, mtime, callback) { if (handleError((path = getPathFromURL(path)), callback)) return; if (!nullCheck(path, callback)) return; - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.utimes(pathModule._makeLong(path), toUnixTimestamp(atime), @@ -1232,7 +1232,7 @@ fs.utimesSync = function(path, atime, mtime) { fs.futimes = function(fd, atime, mtime, callback) { atime = toUnixTimestamp(atime); mtime = toUnixTimestamp(mtime); - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = makeCallback(callback); binding.futimes(fd, atime, mtime, req); }; @@ -1292,9 +1292,9 @@ fs.writeFile = function(path, data, options, callback) { }); function writeFd(fd, isUserFd) { - var buffer = isUint8Array(data) ? + const buffer = isUint8Array(data) ? data : Buffer.from('' + data, options.encoding || 'utf8'); - var position = /a/.test(flag) ? null : 0; + const position = /a/.test(flag) ? null : 0; writeAll(fd, isUserFd, buffer, 0, buffer.length, position, callback); } @@ -1304,8 +1304,8 @@ fs.writeFileSync = function(path, data, options) { options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' }); const flag = options.flag || 'w'; - var isUserFd = isFd(path); // file descriptor ownership - var fd = isUserFd ? path : fs.openSync(path, flag, options.mode); + const isUserFd = isFd(path); // file descriptor ownership + const fd = isUserFd ? path : fs.openSync(path, flag, options.mode); if (!isUint8Array(data)) { data = Buffer.from('' + data, options.encoding || 'utf8'); @@ -1315,7 +1315,7 @@ fs.writeFileSync = function(path, data, options) { var position = /a/.test(flag) ? null : 0; try { while (length > 0) { - var written = fs.writeSync(fd, data, offset, length, position); + const written = fs.writeSync(fd, data, offset, length, position); offset += written; length -= written; if (position !== null) { @@ -1357,7 +1357,7 @@ fs.appendFileSync = function(path, data, options) { function FSWatcher() { EventEmitter.call(this); - var self = this; + const self = this; this._handle = new FSEvent(); this._handle.owner = this; @@ -1382,10 +1382,10 @@ FSWatcher.prototype.start = function(filename, encoding) { handleError((filename = getPathFromURL(filename))); nullCheck(filename); - var err = this._handle.start(pathModule._makeLong(filename), - persistent, - recursive, - encoding); + const err = this._handle.start(pathModule._makeLong(filename), + persistent, + recursive, + encoding); if (err) { this._handle.close(); const error = errnoException(err, `watch ${filename}`); @@ -1445,7 +1445,7 @@ function statsFromPrevValues() { function StatWatcher() { EventEmitter.call(this); - var self = this; + const self = this; this._handle = new binding.StatWatcher(); // uv_fs_poll is a little more powerful than ev_stat but we curb it for @@ -1488,7 +1488,7 @@ fs.watchFile = function(filename, options, listener) { filename = pathModule.resolve(filename); var stat; - var defaults = { + const defaults = { // Poll interval in milliseconds. 5007 is what libev used to use. It's // a little on the slow side but let's stick with it for now to keep // behavioral changes to a minimum. @@ -1526,7 +1526,7 @@ fs.unwatchFile = function(filename, listener) { handleError((filename = getPathFromURL(filename))); nullCheck(filename); filename = pathModule.resolve(filename); - var stat = statWatchers.get(filename); + const stat = statWatchers.get(filename); if (stat === undefined) return; @@ -1635,10 +1635,10 @@ fs.realpathSync = function realpathSync(p, options) { // NB: p.length changes. while (pos < p.length) { // find the next part - var result = nextPart(p, pos); + const result = nextPart(p, pos); previous = current; if (result === -1) { - var last = p.slice(pos); + const last = p.slice(pos); current += last; base = previous + last; pos = p.length; @@ -1658,14 +1658,14 @@ fs.realpathSync = function realpathSync(p, options) { } var resolvedLink; - var maybeCachedResolved = cache && cache.get(base); + const maybeCachedResolved = cache && cache.get(base); if (maybeCachedResolved) { resolvedLink = maybeCachedResolved; } else { // Use stats array directly to avoid creating an fs.Stats instance just // for our internal use. - var baseLong = pathModule._makeLong(base); + const baseLong = pathModule._makeLong(base); binding.lstat(baseLong); if ((statValues[1/*mode*/] & S_IFMT) !== S_IFLNK) { @@ -1679,8 +1679,8 @@ fs.realpathSync = function realpathSync(p, options) { var linkTarget = null; var id; if (!isWindows) { - var dev = statValues[0/*dev*/].toString(32); - var ino = statValues[7/*ino*/].toString(32); + const dev = statValues[0/*dev*/].toString(32); + const ino = statValues[7/*ino*/].toString(32); id = `${dev}:${ino}`; if (seenLinks[id]) { linkTarget = seenLinks[id]; @@ -1766,10 +1766,10 @@ fs.realpath = function realpath(p, options, callback) { } // find the next part - var result = nextPart(p, pos); + const result = nextPart(p, pos); previous = current; if (result === -1) { - var last = p.slice(pos); + const last = p.slice(pos); current += last; base = previous + last; pos = p.length; @@ -1808,8 +1808,8 @@ fs.realpath = function realpath(p, options, callback) { // dev/ino always return 0 on windows, so skip the check. let id; if (!isWindows) { - var dev = statValues[0/*ino*/].toString(32); - var ino = statValues[7/*ino*/].toString(32); + const dev = statValues[0/*ino*/].toString(32); + const ino = statValues[7/*ino*/].toString(32); id = `${dev}:${ino}`; if (seenLinks[id]) { return gotTarget(null, seenLinks[id], base); @@ -1828,7 +1828,7 @@ fs.realpath = function realpath(p, options, callback) { function gotTarget(err, target, base) { if (err) return callback(err); - var resolvedLink = pathModule.resolve(previous, target); + const resolvedLink = pathModule.resolve(previous, target); gotResolvedLink(resolvedLink); } @@ -1864,7 +1864,7 @@ fs.mkdtemp = function(prefix, options, callback) { return; } - var req = new FSReqWrap(); + const req = new FSReqWrap(); req.oncomplete = callback; binding.mkdtemp(prefix + 'XXXXXX', options.encoding, req); @@ -2016,7 +2016,7 @@ function ReadStream(path, options) { fs.FileReadStream = fs.ReadStream; // support the legacy name ReadStream.prototype.open = function() { - var self = this; + const self = this; fs.open(this.path, this.flags, this.mode, function(er, fd) { if (er) { if (self.autoClose) { @@ -2051,9 +2051,9 @@ ReadStream.prototype._read = function(n) { // 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 thisPool = pool; + const thisPool = pool; var toRead = Math.min(pool.length - pool.used, n); - var start = pool.used; + const start = pool.used; if (this.pos !== undefined) toRead = Math.min(this.end - this.pos + 1, toRead); @@ -2064,7 +2064,7 @@ ReadStream.prototype._read = function(n) { return this.push(null); // the actual read. - var self = this; + const self = this; fs.read(this.fd, pool, pool.used, toRead, this.pos, onread); // move the pool positions, and internal position for reading. @@ -2213,7 +2213,7 @@ WriteStream.prototype._write = function(data, encoding, cb) { }); } - var self = this; + const self = this; fs.write(this.fd, data, 0, data.length, this.pos, function(er, bytes) { if (er) { if (self.autoClose) { @@ -2255,7 +2255,7 @@ WriteStream.prototype._writev = function(data, cb) { var size = 0; for (var i = 0; i < len; i++) { - var chunk = data[i].chunk; + const chunk = data[i].chunk; chunks[i] = chunk; size += chunk.length; diff --git a/lib/http.js b/lib/http.js index af3e8a017ce1b9..8b4378585faf98 100644 --- a/lib/http.js +++ b/lib/http.js @@ -40,7 +40,7 @@ function request(options, cb) { } function get(options, cb) { - var req = request(options, cb); + const req = request(options, cb); req.end(); return req; } diff --git a/lib/https.js b/lib/https.js index fb220872598315..8912b84eeede4d 100644 --- a/lib/https.js +++ b/lib/https.js @@ -240,7 +240,7 @@ exports.request = function request(options, cb) { }; exports.get = function get(options, cb) { - var req = exports.request(options, cb); + const req = exports.request(options, cb); req.end(); return req; }; diff --git a/lib/internal/bootstrap_node.js b/lib/internal/bootstrap_node.js index b43a262682cb35..ed68a945d73c68 100644 --- a/lib/internal/bootstrap_node.js +++ b/lib/internal/bootstrap_node.js @@ -188,7 +188,7 @@ const fs = NativeModule.require('fs'); // read the source const filename = Module._resolveFilename(process.argv[1]); - var source = fs.readFileSync(filename, 'utf-8'); + const source = fs.readFileSync(filename, 'utf-8'); checkScriptSyntax(source, filename); process.exit(0); } @@ -439,7 +439,7 @@ const versionTypes = icu.getVersion().split(','); for (var n = 0; n < versionTypes.length; n++) { - var name = versionTypes[n]; + const name = versionTypes[n]; const version = icu.getVersion(name); Object.defineProperty(process.versions, name, { writable: false, diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 6613c72a5c4650..0738ec4307bf56 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -58,7 +58,7 @@ const handleConversion = { }, got: function(message, handle, emit) { - var server = new net.Server(); + const server = new net.Server(); server.listen(handle, function() { emit(server); }); @@ -75,8 +75,8 @@ const handleConversion = { // the worker should keep track of the socket message.key = socket.server._connectionKey; - var firstTime = !this.channel.sockets.send[message.key]; - var socketList = getSocketList('send', this, message.key); + const firstTime = !this.channel.sockets.send[message.key]; + const socketList = getSocketList('send', this, message.key); // the server should no longer expose a .connection property // and when asked to close it should query the socket status from @@ -88,7 +88,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 @@ -119,14 +119,14 @@ const handleConversion = { }, got: function(message, handle, emit) { - var socket = new net.Socket({ handle: handle }); + const socket = new net.Socket({ handle: handle }); socket.readable = socket.writable = true; // if the socket was created by net.Server we will track the socket if (message.key) { // add socket to connections list - var socketList = getSocketList('got', this, message.key); + const socketList = getSocketList('got', this, message.key); socketList.add({ socket: socket }); @@ -158,7 +158,7 @@ const handleConversion = { }, got: function(message, handle, emit) { - var socket = new dgram.Socket(message.dgramType); + const socket = new dgram.Socket(message.dgramType); socket.bind(handle, function() { emit(socket); @@ -198,7 +198,7 @@ function ChildProcess() { this._handle = null; if (exitCode < 0) { - var syscall = this.spawnfile ? 'spawn ' + this.spawnfile : 'spawn'; + const syscall = this.spawnfile ? 'spawn ' + this.spawnfile : 'spawn'; const err = errnoException(exitCode, syscall); if (this.spawnfile) @@ -239,7 +239,7 @@ function flushStdio(subprocess) { function createSocket(pipe, readable) { - var s = new net.Socket({ handle: pipe }); + const s = new net.Socket({ handle: pipe }); if (readable) { s.writable = false; @@ -313,7 +313,7 @@ ChildProcess.prototype.spawn = function(options) { throw new errors.TypeError('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_EAGAIN || @@ -397,7 +397,7 @@ ChildProcess.prototype.kill = function(sig) { convertToValidSignal(sig === undefined ? 'SIGTERM' : sig); if (this._handle) { - var err = this._handle.kill(signal); + const err = this._handle.kill(signal); if (err === 0) { /* Success. */ this.killed = true; @@ -462,7 +462,7 @@ function setupChannel(target, channel) { const control = new Control(channel); - var decoder = new StringDecoder('utf8'); + const decoder = new StringDecoder('utf8'); var jsonBuffer = ''; var pendingHandle = null; channel.buffering = false; @@ -473,10 +473,10 @@ function setupChannel(target, channel) { pendingHandle = recvHandle; // Linebreak is used as a message end sign - var chunks = decoder.write(pool).split('\n'); - var numCompleteChunks = chunks.length - 1; + const chunks = decoder.write(pool).split('\n'); + const numCompleteChunks = chunks.length - 1; // Last line does not have trailing linebreak - var incompleteChunk = chunks[numCompleteChunks]; + const incompleteChunk = chunks[numCompleteChunks]; if (numCompleteChunks === 0) { jsonBuffer += incompleteChunk; this.buffering = jsonBuffer.length !== 0; @@ -485,7 +485,7 @@ function setupChannel(target, channel) { chunks[0] = jsonBuffer + chunks[0]; for (var i = 0; i < numCompleteChunks; i++) { - var message = JSON.parse(chunks[i]); + const message = JSON.parse(chunks[i]); // There will be at most one NODE_HANDLE message in every chunk we // read because SCM_RIGHTS messages don't get coalesced. Make sure @@ -535,7 +535,7 @@ function setupChannel(target, channel) { } assert(Array.isArray(target._handleQueue)); - var queue = target._handleQueue; + const queue = target._handleQueue; target._handleQueue = null; if (target._pendingMessage) { @@ -546,7 +546,7 @@ function setupChannel(target, channel) { } for (var i = 0; i < queue.length; i++) { - var args = queue[i]; + const args = queue[i]; target._send(args.message, args.handle, args.options, args.callback); } @@ -571,7 +571,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') { @@ -688,11 +688,11 @@ function setupChannel(target, channel) { return this._handleQueue.length === 1; } - var req = new WriteWrap(); + const req = new WriteWrap(); req.async = false; - var string = JSON.stringify(message) + '\n'; - var err = channel.writeUtf8String(req, string, handle); + const string = JSON.stringify(message) + '\n'; + const err = channel.writeUtf8String(req, string, handle); if (err === 0) { if (handle) { @@ -795,7 +795,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); } @@ -857,7 +857,7 @@ function _validateStdio(stdio, sync) { if (stdio === 'ignore') { acc.push({ type: 'ignore' }); } else if (stdio === 'pipe' || typeof stdio === 'number' && stdio < 0) { - var a = { + const a = { type: 'pipe', readable: i === 0, writable: i !== 0 @@ -897,7 +897,7 @@ function _validateStdio(stdio, sync) { }); } else if (getHandleWrapType(stdio) || getHandleWrapType(stdio.handle) || getHandleWrapType(stdio._handle)) { - var handle = getHandleWrapType(stdio) ? + const handle = getHandleWrapType(stdio) ? stdio : getHandleWrapType(stdio.handle) ? stdio.handle : stdio._handle; @@ -927,10 +927,10 @@ 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; + const Construct = type === 'send' ? SocketListSend : SocketListReceive; socketList = sockets[key] = new Construct(worker, key); } return socketList; @@ -946,8 +946,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/cluster/child.js b/lib/internal/cluster/child.js index 98c5e7b5597f74..764f336a567177 100644 --- a/lib/internal/cluster/child.js +++ b/lib/internal/cluster/child.js @@ -192,7 +192,7 @@ function _disconnect(masterInitiated) { } } - for (var key in handles) { + for (const key in handles) { const handle = handles[key]; delete handles[key]; waitingCount++; diff --git a/lib/internal/cluster/master.js b/lib/internal/cluster/master.js index 4ccf0393223a23..1764e1bdb07e69 100644 --- a/lib/internal/cluster/master.js +++ b/lib/internal/cluster/master.js @@ -43,7 +43,7 @@ if (schedulingPolicy === undefined) { cluster.schedulingPolicy = schedulingPolicy; cluster.setupMaster = function(options) { - var settings = { + const settings = { args: process.argv.slice(2), exec: process.argv[1], execArgv: process.execArgv, @@ -147,7 +147,7 @@ function removeWorker(worker) { function removeHandlesForWorker(worker) { assert(worker); - for (var key in handles) { + for (const key in handles) { const handle = handles[key]; if (handle.remove(worker)) diff --git a/lib/internal/encoding.js b/lib/internal/encoding.js index de4ebcf196284b..58a3c425d577fe 100644 --- a/lib/internal/encoding.js +++ b/lib/internal/encoding.js @@ -312,8 +312,8 @@ class TextEncoder { throw new errors.TypeError('ERR_INVALID_THIS', 'TextEncoder'); 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; @@ -537,8 +537,8 @@ function makeTextDecoderJS() { throw new errors.TypeError('ERR_INVALID_THIS', 'TextDecoder'); 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/errors.js b/lib/internal/errors.js index 78f2da19a47772..216c8331cc1f6a 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -306,7 +306,7 @@ function invalidArgType(name, expected, actual) { let msg; if (Array.isArray(name)) { - var names = name.map((val) => `"${val}"`).join(', '); + const names = name.map((val) => `"${val}"`).join(', '); msg = `The ${names} arguments ${determiner} ${oneOf(expected, 'type')}`; } else if (name.includes(' argument')) { // for the case like 'first argument' diff --git a/lib/internal/http2/util.js b/lib/internal/http2/util.js index 267ea4fe4fb6a4..34d4680096de7c 100644 --- a/lib/internal/http2/util.js +++ b/lib/internal/http2/util.js @@ -469,11 +469,11 @@ function assertWithinRange(name, value, min = 0, max = Infinity) { function toHeaderObject(headers) { const obj = Object.create(null); for (var n = 0; n < headers.length; n = n + 2) { - var name = headers[n]; + const name = headers[n]; var value = headers[n + 1]; if (name === HTTP2_HEADER_STATUS) value |= 0; - var existing = obj[name]; + const existing = obj[name]; if (existing === undefined) { obj[name] = value; } else if (!kSingleValueHeaders.has(name)) { diff --git a/lib/internal/module.js b/lib/internal/module.js index a6da58a8d73663..020257e8af7dad 100644 --- a/lib/internal/module.js +++ b/lib/internal/module.js @@ -47,7 +47,7 @@ function stripBOM(content) { */ function stripShebang(content) { // Remove shebang - var contLen = content.length; + const contLen = content.length; if (contLen >= 2) { if (content.charCodeAt(0) === 35/*#*/ && content.charCodeAt(1) === 33/*!*/) { @@ -58,7 +58,7 @@ function stripShebang(content) { // Find end of shebang line and slice it off var i = 2; for (; i < contLen; ++i) { - var code = content.charCodeAt(i); + const code = content.charCodeAt(i); if (code === 10/*\n*/ || code === 13/*\r*/) break; } diff --git a/lib/internal/process/next_tick.js b/lib/internal/process/next_tick.js index 00698aee23020b..dc30a0bbb0b745 100644 --- a/lib/internal/process/next_tick.js +++ b/lib/internal/process/next_tick.js @@ -60,15 +60,15 @@ function setupNextTick() { // Grab the constants necessary for working with internal arrays. const { kInit, kDestroy, kAsyncUidCntr } = async_wrap.constants; const { async_id_symbol, trigger_id_symbol } = async_wrap; - var nextTickQueue = new NextTickQueue(); + const nextTickQueue = new NextTickQueue(); var microtasksScheduled = false; // Used to run V8's micro task queue. var _runMicrotasks = {}; // *Must* match Environment::TickInfo::Fields in src/env.h. - var kIndex = 0; - var kLength = 1; + const kIndex = 0; + const kLength = 1; process.nextTick = nextTick; // Needs to be accessible from beyond this scope. diff --git a/lib/internal/streams/legacy.js b/lib/internal/streams/legacy.js index 3242b15eabdb0d..e335339edef7cb 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) { diff --git a/lib/internal/tls.js b/lib/internal/tls.js index 6d367dbf285ff7..4e468a2dd72a74 100644 --- a/lib/internal/tls.js +++ b/lib/internal/tls.js @@ -3,13 +3,13 @@ // Example: // C=US\nST=CA\nL=SF\nO=Joyent\nOU=Node.js\nCN=ca1\nemailAddress=ry@clouds.org function parseCertString(s) { - var out = Object.create(null); - var parts = s.split('\n'); + const out = Object.create(null); + const parts = s.split('\n'); for (var i = 0, len = parts.length; i < len; i++) { - var sepIndex = parts[i].indexOf('='); + const sepIndex = parts[i].indexOf('='); if (sepIndex > 0) { - var key = parts[i].slice(0, sepIndex); - var value = parts[i].slice(sepIndex + 1); + const key = parts[i].slice(0, sepIndex); + const value = parts[i].slice(sepIndex + 1); if (key in out) { if (!Array.isArray(out[key])) { out[key] = [out[key]]; diff --git a/lib/internal/url.js b/lib/internal/url.js index cf0271691a5cd0..a378581cb48b2f 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -169,20 +169,20 @@ class URLSearchParams { if (typeof recurseTimes === 'number' && recurseTimes < 0) return ctx.stylize('[Object]', 'special'); - var separator = ', '; - var innerOpts = Object.assign({}, ctx); + const separator = ', '; + const innerOpts = Object.assign({}, ctx); if (recurseTimes !== null) { innerOpts.depth = recurseTimes - 1; } - var innerInspect = (v) => util.inspect(v, innerOpts); + const innerInspect = (v) => util.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 colorRe = /\u001b\[\d\d?m/g; - var length = output.reduce( + const colorRe = /\u001b\[\d\d?m/g; + const length = output.reduce( (prev, cur) => prev + cur.replace(colorRe, '').length + separator.length, -separator.length ); @@ -198,7 +198,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 : ''; @@ -336,9 +336,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 }); @@ -1084,8 +1084,8 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { // Simple stable in-place insertion sort // Derived from v8/src/js/array.js for (var i = 2; i < len; i += 2) { - var curKey = a[i]; - var curVal = a[i + 1]; + const curKey = a[i]; + const curVal = a[i + 1]; var j; for (j = i - 2; j >= 0; j -= 2) { if (a[j] > curKey) { @@ -1104,7 +1104,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { const rBuffer = new Array(len); for (var step = 2; step < len; step *= 2) { for (var start = 0; start < len - 2; start += 2 * step) { - var mid = start + step; + const mid = start + step; var end = mid + step; end = end < len ? end : len; if (mid > end) @@ -1296,7 +1296,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: url.hostname, hash: url.hash, @@ -1315,11 +1315,11 @@ function urlToOptions(url) { } 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] === '%') { - var third = pathname.codePointAt(n + 2) | 0x20; + const third = pathname.codePointAt(n + 2) | 0x20; if ((pathname[n + 1] === '2' && third === 102) || // 2f 2F / (pathname[n + 1] === '5' && third === 99)) { // 5c 5C \ return new errors.TypeError( @@ -1339,8 +1339,8 @@ function getPathFromURLWin32(url) { return `//${domainToUnicode(hostname)}${pathname}`; } else { // Otherwise, it's a local path that requires a drive letter - var letter = pathname.codePointAt(1) | 0x20; - var sep = pathname[2]; + const letter = pathname.codePointAt(1) | 0x20; + const sep = pathname[2]; if (letter < 97 || letter > 122 || // a..z A..Z (sep !== ':')) { return new errors.TypeError('ERR_INVALID_FILE_URL_PATH', @@ -1354,10 +1354,10 @@ function getPathFromURLPosix(url) { if (url.hostname !== '') { return new errors.TypeError('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; + const third = pathname.codePointAt(n + 2) | 0x20; if (pathname[n + 1] === '2' && third === 102) { return new errors.TypeError('ERR_INVALID_FILE_URL_PATH', 'must not include encoded / characters'); @@ -1390,7 +1390,7 @@ NativeURL.prototype = URL.prototype; 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 e7b9b958c7a198..5acb52425a58d0 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -164,7 +164,7 @@ function getSignalsToNamesMapping() { return signalsToNamesMapping; signalsToNamesMapping = Object.create(null); - for (var key in signals) { + for (const key in signals) { signalsToNamesMapping[signals[key]] = key; } @@ -185,7 +185,7 @@ function convertToValidSignal(signal) { function getConstructorOf(obj) { while (obj) { - var descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor'); + const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor'); if (descriptor !== undefined && typeof descriptor.value === 'function' && descriptor.value.name !== '') { diff --git a/lib/module.js b/lib/module.js index 0b87cf7480e4d9..8e8b3ad74b82d1 100644 --- a/lib/module.js +++ b/lib/module.js @@ -56,7 +56,7 @@ function stat(filename) { stat.cache = null; function updateChildren(parent, child, scan) { - var children = parent && parent.children; + const children = parent && parent.children; if (children && !(scan && children.includes(child))) children.push(child); } @@ -123,11 +123,11 @@ function readPackage(requestPath) { } function tryPackage(requestPath, exts, isMain) { - var pkg = readPackage(requestPath); + const pkg = readPackage(requestPath); if (!pkg) return false; - var filename = path.resolve(requestPath, pkg); + const filename = path.resolve(requestPath, pkg); return tryFile(filename, isMain) || tryExtensions(filename, exts, isMain) || tryExtensions(path.resolve(filename, 'index'), exts, isMain); @@ -175,14 +175,14 @@ 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; var exts; - var trailingSlash = request.length > 0 && + const trailingSlash = request.length > 0 && request.charCodeAt(request.length - 1) === 47/*/*/; // For each path @@ -190,10 +190,10 @@ Module._findPath = function(request, paths, isMain) { // Don't search further if path doesn't exist const curPath = paths[i]; if (curPath && stat(curPath) < 1) continue; - var basePath = path.resolve(curPath, request); + const basePath = path.resolve(curPath, request); var filename; - var rc = stat(basePath); + const rc = stat(basePath); if (!trailingSlash) { if (rc === 0) { // File. if (preserveSymlinks && !isMain) { @@ -237,8 +237,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 (process.platform === 'win32') { // 'from' is the __dirname of the module. Module._nodeModulePaths = function(from) { @@ -322,8 +322,8 @@ if (process.platform === 'win32') { // '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.nonInternalExists(request)) { debug('looking for %j in []', request); @@ -350,7 +350,7 @@ Module._resolveLookupPaths = function(request, parent, newReturn) { if (!parent || !parent.id || !parent.filename) { // make require('./path/to/foo') work - normally the path is taken // from realpath(__filename) but with eval there is no filename - var mainPaths = ['.'].concat(Module._nodeModulePaths('.'), modulePaths); + const mainPaths = ['.'].concat(Module._nodeModulePaths('.'), modulePaths); debug('looking for %j in %j', request, mainPaths); return (newReturn ? mainPaths : [request, mainPaths]); @@ -403,7 +403,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]); }; @@ -452,7 +452,7 @@ Module._load = function(request, parent, isMain) { 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; @@ -464,7 +464,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; @@ -495,12 +495,12 @@ Module._resolveFilename = function(request, parent, isMain) { return request; } - var paths = Module._resolveLookupPaths(request, parent, true); + const paths = Module._resolveLookupPaths(request, parent, true); // 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) { - var err = new Error(`Cannot find module '${request}'`); + const err = new Error(`Cannot find module '${request}'`); err.code = 'MODULE_NOT_FOUND'; throw err; } @@ -559,9 +559,9 @@ Module.prototype._compile = function(content, filename) { content = internalModule.stripShebang(content); // create wrapper function - var wrapper = Module.wrap(content); + const wrapper = Module.wrap(content); - var compiledWrapper = vm.runInThisContext(wrapper, { + const compiledWrapper = vm.runInThisContext(wrapper, { filename: filename, lineOffset: 0, displayErrors: true @@ -588,9 +588,9 @@ Module.prototype._compile = function(content, filename) { } } } - var dirname = path.dirname(filename); - var require = internalModule.makeRequireFunction(this); - var depth = internalModule.requireDepth; + const dirname = path.dirname(filename); + const require = internalModule.makeRequireFunction(this); + const depth = internalModule.requireDepth; if (depth === 0) stat.cache = new Map(); var result; if (inspectorWrapper) { @@ -607,14 +607,14 @@ 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(internalModule.stripBOM(content), filename); }; // Native extension for .json Module._extensions['.json'] = function(module, filename) { - var content = fs.readFileSync(filename, 'utf8'); + const content = fs.readFileSync(filename, 'utf8'); try { module.exports = JSON.parse(internalModule.stripBOM(content)); } catch (err) { @@ -669,7 +669,7 @@ Module._initPaths = function() { paths.unshift(path.resolve(homeDir, '.node_modules')); } - var nodePath = process.env['NODE_PATH']; + const nodePath = process.env['NODE_PATH']; if (nodePath) { paths = nodePath.split(path.delimiter).filter(function(path) { return !!path; @@ -689,7 +689,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/net.js b/lib/net.js index d693b25d46f54b..840d7519072168 100644 --- a/lib/net.js +++ b/lib/net.js @@ -61,7 +61,7 @@ const normalizedArgsSymbol = internalNet.normalizedArgsSymbol; function noop() {} function createHandle(fd) { - var type = TTYWrap.guessHandleType(fd); + const type = TTYWrap.guessHandleType(fd); if (type === 'PIPE') return new Pipe(); if (type === 'TCP') return new TCP(); throw new TypeError('Unsupported fd type: ' + type); @@ -98,10 +98,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); @@ -146,7 +146,7 @@ function normalizeArgs(args) { } } - var cb = args[args.length - 1]; + const cb = args[args.length - 1]; if (typeof cb !== 'function') arr = [options, null]; else @@ -214,7 +214,7 @@ function Socket(options) { (this._handle instanceof Pipe) && process.platform === 'win32') { // Make stdout and stderr blocking on Windows - var err = this._handle.setBlocking(true); + const err = this._handle.setBlocking(true); if (err) throw errnoException(err, 'setBlocking'); } @@ -288,14 +288,14 @@ function onSocketFinish() { if (!this._handle || !this._handle.shutdown) return this.destroy(); - var req = new ShutdownWrap(); + const req = new ShutdownWrap(); req.oncomplete = afterShutdown; req.handle = this._handle; // node::ShutdownWrap isn't instantiated and attached to the JS instance of // ShutdownWrap above until shutdown() is called. So don't set the init // trigger id until now. setInitTriggerId(this[async_id_symbol]); - var err = this._handle.shutdown(req); + const err = this._handle.shutdown(req); if (err) return this.destroy(errnoException(err, 'shutdown')); @@ -303,7 +303,7 @@ function onSocketFinish() { function afterShutdown(status, handle, req) { - var self = handle.owner; + const self = handle.owner; debug('afterShutdown destroyed=%j', self.destroyed, self._readableState); @@ -355,7 +355,7 @@ function writeAfterFIN(chunk, encoding, cb) { encoding = null; } - 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); @@ -482,7 +482,7 @@ Socket.prototype._read = function(n) { // not already reading, start the flow debug('Socket._read readStart'); this._handle.reading = true; - var err = this._handle.readStart(); + const err = this._handle.readStart(); if (err) this.destroy(errnoException(err, 'read')); } @@ -542,7 +542,7 @@ Socket.prototype._destroy = function(exception, cb) { if (this._handle) { if (this !== process.stderr) debug('close handle'); - var isException = exception ? true : false; + const isException = exception ? true : false; // `bytesRead` should be accessible after `.destroy()` this[BYTES_READ] = this._handle.bytesRead; @@ -571,8 +571,8 @@ Socket.prototype._destroy = function(exception, cb) { // This function is called whenever the handle gets a // buffer, or when there's an error reading. function onread(nread, buffer) { - var handle = this; - var self = handle.owner; + const handle = this; + const self = handle.owner; assert(handle === self._handle, 'handle != self._handle'); self._unrefTimer(); @@ -588,12 +588,12 @@ function onread(nread, buffer) { // called again. // Optimization: emit the original buffer with end points - var ret = self.push(buffer); + const ret = self.push(buffer); if (handle.reading && !ret) { handle.reading = false; debug('readStop'); - var err = handle.readStop(); + const err = handle.readStop(); if (err) self.destroy(errnoException(err, 'read')); } @@ -636,8 +636,8 @@ Socket.prototype._getpeername = function() { if (!this._handle || !this._handle.getpeername) { return {}; } - var out = {}; - var err = this._handle.getpeername(out); + const out = {}; + const err = this._handle.getpeername(out); if (err) return {}; // FIXME(bnoordhuis) Throw? this._peername = out; } @@ -674,8 +674,8 @@ Socket.prototype._getsockname = function() { return {}; } if (!this._sockname) { - var out = {}; - var err = this._handle.getsockname(out); + const out = {}; + const err = this._handle.getsockname(out); if (err) return {}; // FIXME(bnoordhuis) Throw? this._sockname = out; } @@ -724,14 +724,14 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { return false; } - var req = new WriteWrap(); + const req = new WriteWrap(); req.handle = this._handle; req.oncomplete = afterWrite; req.async = false; var err; if (writev) { - var allBuffers = data.allBuffers; + const allBuffers = data.allBuffers; var chunks; var i; if (allBuffers) { @@ -741,7 +741,7 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { } else { chunks = new Array(data.length << 1); for (i = 0; i < data.length; i++) { - var entry = data[i]; + const entry = data[i]; chunks[i * 2] = entry.chunk; chunks[i * 2 + 1] = entry.encoding; } @@ -850,7 +850,7 @@ protoGetter('bytesWritten', function bytesWritten() { function afterWrite(status, handle, req, err) { - var self = handle.owner; + const self = handle.owner; if (self !== process.stderr && self !== process.stdout) debug('afterWrite', status); @@ -861,7 +861,7 @@ function afterWrite(status, handle, req, err) { } if (status < 0) { - var ex = errnoException(status, 'write', req.error); + const ex = errnoException(status, 'write', req.error); debug('write failure', ex); self.destroy(ex, req.cb); return; @@ -887,7 +887,7 @@ function checkBindError(err, port, handle) { // getsockname() method. Non-issue for now, the cluster module doesn't // really support pipes anyway. if (err === 0 && port > 0 && handle.getsockname) { - var out = {}; + const out = {}; err = handle.getsockname(out); if (err === 0 && port !== out.port) { debug(`checkBindError, bound to ${out.port} instead of ${port}`); @@ -958,7 +958,7 @@ function internalConnect( } if (err) { - var sockname = self._getsockname(); + const sockname = self._getsockname(); var details; if (sockname) { @@ -982,8 +982,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; @@ -996,7 +996,7 @@ Socket.prototype.connect = function(...args) { } const path = options.path; - var pipe = !!path; + const pipe = !!path; debug('pipe', pipe, path); if (!this._handle) { @@ -1029,10 +1029,10 @@ Socket.prototype.connect = function(...args) { function lookupAndConnect(self, options) { - var host = options.host || 'localhost'; + const host = options.host || 'localhost'; var port = options.port; - var localAddress = options.localAddress; - var localPort = options.localPort; + const localAddress = options.localAddress; + const localPort = options.localPort; if (localAddress && !cares.isIP(localAddress)) { throw new TypeError('"localAddress" option must be a valid IP: ' + @@ -1055,7 +1055,7 @@ function lookupAndConnect(self, options) { port |= 0; // If host is an IP, skip performing a lookup - var addressType = cares.isIP(host); + const addressType = cares.isIP(host); if (addressType) { nextTick(self[async_id_symbol], function() { if (self.connecting) @@ -1067,7 +1067,7 @@ function lookupAndConnect(self, options) { if (options.lookup && typeof options.lookup !== 'function') throw new TypeError('"lookup" option should be a function'); - var dnsopts = { + const dnsopts = { family: options.family, hints: options.hints || 0 }; @@ -1079,7 +1079,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; setInitTriggerId(self[async_id_symbol]); lookup(host, dnsopts, function emitLookup(err, ip, addressType) { self.emit('lookup', err, ip, addressType, host); @@ -1141,7 +1141,7 @@ Socket.prototype.unref = function() { function afterConnect(status, handle, req, readable, writable) { - var self = handle.owner; + const self = handle.owner; // callback may come after call to destroy if (self.destroyed) { @@ -1176,11 +1176,11 @@ function afterConnect(status, handle, req, readable, writable) { if (req.localAddress && req.localPort) { details = req.localAddress + ':' + req.localPort; } - var ex = exceptionWithHostPort(status, - 'connect', - req.address, - req.port, - details); + const ex = exceptionWithHostPort(status, + 'connect', + req.address, + req.port, + details); if (details) { ex.localAddress = req.localAddress; ex.localPort = req.localPort; @@ -1263,7 +1263,7 @@ function createServerHandle(address, port, addressType, fd) { } else if (port === -1 && addressType === -1) { handle = new Pipe(); if (process.platform === 'win32') { - var instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES); + const instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES); if (!isNaN(instances)) { handle.setPendingInstances(instances); } @@ -1328,7 +1328,7 @@ function setupListenHandle(address, port, addressType, backlog, fd) { rval = createServerHandle(address, port, addressType, fd); if (typeof rval === 'number') { - var error = exceptionWithHostPort(rval, 'listen', address, port); + const error = exceptionWithHostPort(rval, 'listen', address, port); process.nextTick(emitErrorNT, this, error); return; } @@ -1342,10 +1342,10 @@ function setupListenHandle(address, port, addressType, backlog, fd) { // 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 = exceptionWithHostPort(err, 'listen', address, port); + const ex = exceptionWithHostPort(err, 'listen', address, port); this._handle.close(); this._handle = null; nextTick(this[async_id_symbol], emitErrorNT, this, ex); @@ -1405,7 +1405,7 @@ function listenInCluster(server, address, port, addressType, err = checkBindError(err, port, handle); if (err) { - var ex = exceptionWithHostPort(err, 'bind', address, port); + const ex = exceptionWithHostPort(err, 'bind', address, port); return server.emit('error', ex); } @@ -1419,19 +1419,19 @@ 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 errors.Error('ERR_SERVER_ALREADY_LISTEN'); } - var hasCallback = (cb !== null); + const hasCallback = (cb !== null); if (hasCallback) { 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) @@ -1482,7 +1482,7 @@ Server.prototype.listen = function(...args) { // (path[, backlog][, cb]) or (options[, cb]) // where path or options.path is a UNIX domain socket or Windows pipe if (options.path && isPipeName(options.path)) { - var pipeName = this._pipeName = options.path; + const pipeName = this._pipeName = options.path; backlog = options.backlog || backlogFromArgs; listenInCluster(this, pipeName, -1, -1, backlog, undefined, options.exclusive); @@ -1514,8 +1514,8 @@ Object.defineProperty(Server.prototype, 'listening', { Server.prototype.address = function() { if (this._handle && this._handle.getsockname) { - var out = {}; - var err = this._handle.getsockname(out); + const out = {}; + const err = this._handle.getsockname(out); if (err) { throw errnoException(err, 'address'); } @@ -1528,8 +1528,8 @@ Server.prototype.address = function() { }; function onconnection(err, clientHandle) { - var handle = this; - var self = handle.owner; + const handle = this; + const self = handle.owner; debug('onconnection'); @@ -1543,7 +1543,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 24f6ed617f870b..2d8a7282618b07 100644 --- a/lib/path.js +++ b/lib/path.js @@ -221,7 +221,7 @@ const win32 = { continue; } - var len = path.length; + const len = path.length; var rootEnd = 0; var code = path.charCodeAt(0); var device = ''; @@ -430,7 +430,7 @@ const win32 = { } code = path.charCodeAt(len - 1); - var trailingSeparator = (code === 47/*/*/ || code === 92/*\*/); + const trailingSeparator = (code === 47/*/*/ || code === 92/*\*/); var tail; if (rootEnd < len) tail = normalizeStringWin32(path.slice(rootEnd), !isAbsolute); @@ -495,7 +495,7 @@ const win32 = { var joined; var firstPart; for (var i = 0; i < arguments.length; ++i) { - var arg = arguments[i]; + const arg = arguments[i]; assertPath(arg); if (arg.length > 0) { if (joined === undefined) @@ -572,8 +572,8 @@ const win32 = { if (from === to) return ''; - var fromOrig = win32.resolve(from); - var toOrig = win32.resolve(to); + const fromOrig = win32.resolve(from); + const toOrig = win32.resolve(to); if (fromOrig === toOrig) return ''; @@ -596,7 +596,7 @@ const win32 = { if (from.charCodeAt(fromEnd - 1) !== 92/*\*/) break; } - var fromLen = (fromEnd - fromStart); + const fromLen = (fromEnd - fromStart); // Trim any leading backslashes var toStart = 0; @@ -610,10 +610,10 @@ const win32 = { if (to.charCodeAt(toEnd - 1) !== 92/*\*/) break; } - var toLen = (toEnd - toStart); + const toLen = (toEnd - toStart); // Compare paths to find the longest common path from root - var length = (fromLen < toLen ? fromLen : toLen); + const length = (fromLen < toLen ? fromLen : toLen); var lastCommonSep = -1; var i = 0; for (; i <= length; ++i) { @@ -642,8 +642,8 @@ const win32 = { } break; } - var fromCode = from.charCodeAt(fromStart + i); - var toCode = to.charCodeAt(toStart + i); + const fromCode = from.charCodeAt(fromStart + i); + const toCode = to.charCodeAt(toStart + i); if (fromCode !== toCode) break; else if (fromCode === 92/*\*/) @@ -995,11 +995,11 @@ const win32 = { parse: function parse(path) { assertPath(path); - var ret = { root: '', dir: '', base: '', ext: '', name: '' }; + const ret = { root: '', dir: '', base: '', ext: '', name: '' }; if (path.length === 0) return ret; - var len = path.length; + const len = path.length; var rootEnd = 0; var code = path.charCodeAt(0); @@ -1244,7 +1244,7 @@ const posix = { return '.'; var joined; for (var i = 0; i < arguments.length; ++i) { - var arg = arguments[i]; + const arg = arguments[i]; assertPath(arg); if (arg.length > 0) { if (joined === undefined) @@ -1278,8 +1278,8 @@ const posix = { if (from.charCodeAt(fromStart) !== 47/*/*/) break; } - var fromEnd = from.length; - var fromLen = (fromEnd - fromStart); + const fromEnd = from.length; + const fromLen = (fromEnd - fromStart); // Trim any leading backslashes var toStart = 1; @@ -1287,11 +1287,11 @@ const posix = { if (to.charCodeAt(toStart) !== 47/*/*/) break; } - var toEnd = to.length; - var toLen = (toEnd - toStart); + const toEnd = to.length; + const toLen = (toEnd - toStart); // Compare paths to find the longest common path from root - var length = (fromLen < toLen ? fromLen : toLen); + const length = (fromLen < toLen ? fromLen : toLen); var lastCommonSep = -1; var i = 0; for (; i <= length; ++i) { @@ -1319,8 +1319,8 @@ const posix = { } break; } - var fromCode = from.charCodeAt(fromStart + i); - var toCode = to.charCodeAt(toStart + i); + const fromCode = from.charCodeAt(fromStart + i); + const toCode = to.charCodeAt(toStart + i); if (fromCode !== toCode) break; else if (fromCode === 47/*/*/) @@ -1362,7 +1362,7 @@ const posix = { if (path.length === 0) return '.'; var code = path.charCodeAt(0); - var hasRoot = (code === 47/*/*/); + const hasRoot = (code === 47/*/*/); var end = -1; var matchedSlash = true; for (var i = path.length - 1; i >= 1; --i) { @@ -1529,11 +1529,11 @@ const posix = { parse: function parse(path) { assertPath(path); - var ret = { root: '', dir: '', base: '', ext: '', name: '' }; + const ret = { root: '', dir: '', base: '', ext: '', name: '' }; if (path.length === 0) return ret; var code = path.charCodeAt(0); - var isAbsolute = (code === 47/*/*/); + const isAbsolute = (code === 47/*/*/); var start; if (isAbsolute) { ret.root = '/'; diff --git a/lib/querystring.js b/lib/querystring.js index b4851f57c3e4e0..ea7880cd71dd74 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -63,14 +63,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,18 +214,18 @@ function stringify(obj, sep, eq, options) { } if (obj !== null && typeof obj === 'object') { - var keys = Object.keys(obj); - var len = keys.length; - var flast = len - 1; + const keys = Object.keys(obj); + const len = keys.length; + const flast = len - 1; var fields = ''; for (var i = 0; i < len; ++i) { - var k = keys[i]; - var v = obj[k]; - var ks = encode(stringifyPrimitive(k)) + eq; + const k = keys[i]; + const v = obj[k]; + const ks = encode(stringifyPrimitive(k)) + eq; if (Array.isArray(v)) { - var vlen = v.length; - var vlast = vlen - 1; + const vlen = v.length; + const vlast = vlen - 1; for (var j = 0; j < vlen; ++j) { fields += ks + encode(stringifyPrimitive(v[j])); if (j < vlast) @@ -263,8 +263,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 5e96a04b1c5e98..8204c0297f514d 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -120,7 +120,7 @@ function Interface(input, output, completer, terminal) { terminal = !!output.isTTY; } - var self = this; + const self = this; this.output = output; this.input = input; @@ -279,7 +279,7 @@ Interface.prototype.question = function(query, cb) { Interface.prototype._onLine = function(line) { if (this._questionCallback) { - var cb = this._questionCallback; + const cb = this._questionCallback; this._questionCallback = null; this.setPrompt(this._oldPrompt); cb(line); @@ -332,16 +332,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); } @@ -362,7 +362,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); } @@ -417,7 +417,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; @@ -427,7 +427,7 @@ Interface.prototype._normalWrite = function(b) { this._sawReturnAt = string.endsWith('\r') ? now() : 0; // got one or more newlines; process into "line" events - var lines = string.split(lineEnding); + const lines = string.split(lineEnding); // either '' or (conceivably) the unfinished portion of the next line string = lines.pop(); this._line_buffer = string; @@ -441,8 +441,8 @@ Interface.prototype._normalWrite = function(b) { Interface.prototype._insertString = function(c) { if (this.cursor < this.line.length) { - var beg = this.line.slice(0, this.cursor); - var end = this.line.slice(this.cursor, this.line.length); + const beg = this.line.slice(0, this.cursor); + const end = this.line.slice(this.cursor, this.line.length); this.line = beg + c + end; this.cursor += c.length; this._refreshLine(); @@ -462,7 +462,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) { @@ -479,7 +479,7 @@ Interface.prototype._tabComplete = function(lastKeypressWasTab) { // Apply/show completions. if (lastKeypressWasTab) { self._writeToOutput('\r\n'); - var width = completions.reduce(function completionReducer(a, b) { + const width = completions.reduce(function completionReducer(a, b) { return a.length > b.length ? a : b; }).length + 2; // 2 space padding var maxColumns = Math.floor(self.columns / width); @@ -488,7 +488,7 @@ Interface.prototype._tabComplete = function(lastKeypressWasTab) { } var group = []; for (var i = 0; i < completions.length; i++) { - var c = completions[i]; + const c = completions[i]; if (c === '') { handleGroup(self, group, width, maxColumns); group = []; @@ -500,10 +500,10 @@ Interface.prototype._tabComplete = function(lastKeypressWasTab) { } // If there is a common prefix to all matches, then apply that portion. - var f = completions.filter(function completionFilter(e) { + const f = completions.filter(function completionFilter(e) { if (e) return e; }); - var prefix = commonPrefix(f); + const prefix = commonPrefix(f); if (prefix.length > completeOn.length) { self._insertString(prefix.slice(completeOn.length)); } @@ -518,14 +518,14 @@ 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; + const idx = row * maxColumns + col; if (idx >= group.length) { break; } - var item = group[idx]; + const item = group[idx]; self._writeToOutput(item); if (col < maxColumns - 1) { for (var s = 0; s < width - item.length; s++) { @@ -543,9 +543,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); @@ -557,8 +557,8 @@ function commonPrefix(strings) { Interface.prototype._wordLeft = function() { if (this.cursor > 0) { - var leading = this.line.slice(0, this.cursor); - var match = leading.match(/(?:[^\w\s]+|\w+|)\s*$/); + const leading = this.line.slice(0, this.cursor); + const match = leading.match(/(?:[^\w\s]+|\w+|)\s*$/); this._moveCursor(-match[0].length); } }; @@ -566,8 +566,8 @@ Interface.prototype._wordLeft = function() { Interface.prototype._wordRight = function() { if (this.cursor < this.line.length) { - var trailing = this.line.slice(this.cursor); - var match = trailing.match(/^(?:\s+|\W+|\w+)\s*/); + const trailing = this.line.slice(this.cursor); + const match = trailing.match(/^(?:\s+|\W+|\w+)\s*/); this._moveCursor(match[0].length); } }; @@ -594,7 +594,7 @@ Interface.prototype._deleteRight = function() { Interface.prototype._deleteWordLeft = function() { if (this.cursor > 0) { var leading = this.line.slice(0, this.cursor); - var match = leading.match(/(?:[^\w\s]+|\w+|)\s*$/); + const match = leading.match(/(?:[^\w\s]+|\w+|)\s*$/); leading = leading.slice(0, leading.length - match[0].length); this.line = leading + this.line.slice(this.cursor, this.line.length); this.cursor = leading.length; @@ -605,8 +605,8 @@ Interface.prototype._deleteWordLeft = function() { Interface.prototype._deleteWordRight = function() { if (this.cursor < this.line.length) { - var trailing = this.line.slice(this.cursor); - var match = trailing.match(/^(?:\s+|\W+|\w+)\s*/); + const trailing = this.line.slice(this.cursor); + const match = trailing.match(/^(?:\s+|\W+|\w+)\s*/); this.line = this.line.slice(0, this.cursor) + trailing.slice(match[0].length); this._refreshLine(); @@ -637,7 +637,7 @@ Interface.prototype.clearLine = function() { Interface.prototype._line = function() { - var line = this._addHistory(); + const line = this._addHistory(); this.clearLine(); this._onLine(line); }; @@ -673,7 +673,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); @@ -697,17 +697,17 @@ 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, @@ -725,19 +725,19 @@ 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) { - var diffCursor = this.cursor - oldcursor; + const diffCursor = this.cursor - oldcursor; var diffWidth; if (diffCursor < 0) { diffWidth = -getStringWidth( @@ -977,7 +977,7 @@ Interface.prototype._ttyWrite = function(s, key) { s = s.toString('utf-8'); if (s) { - var lines = s.split(/\r\n|\n|\r/); + const lines = s.split(/\r\n|\n|\r/); for (var i = 0, len = lines.length; i < len; i++) { if (i > 0) { this._line(); @@ -1005,7 +1005,7 @@ function emitKeypressEvents(stream, iface) { function onData(b) { if (stream.listenerCount('keypress') > 0) { - var r = stream[KEYPRESS_DECODER].write(b); + const r = stream[KEYPRESS_DECODER].write(b); if (r) { clearTimeout(timeoutId); diff --git a/lib/repl.js b/lib/repl.js index 0d1aca6aa546c9..c6289b2ed1bb96 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -143,7 +143,7 @@ function REPLServer(prompt, throw new errors.Error('ERR_INVALID_REPL_EVAL_CONFIG'); } - var self = this; + const self = this; self._domain = dom || domain.create(); @@ -169,7 +169,7 @@ function REPLServer(prompt, function defaultEval(code, context, file, cb) { var err, result, script, wrappedErr; var wrappedCmd = false; - var input = code; + const input = code; if (/^\s*\{/.test(code) && /\}\s*$/.test(code)) { // It's confusing for `{ a : 1 }` to be interpreted as a block @@ -375,7 +375,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; @@ -395,7 +395,7 @@ function REPLServer(prompt, var sawSIGINT = false; var sawCtrlD = false; self.on('SIGINT', function onSigInt() { - var empty = self.line.length === 0; + const empty = self.line.length === 0; self.clearLine(); self.turnOffEditorMode(); @@ -582,12 +582,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; @@ -625,9 +625,9 @@ REPLServer.prototype.createContext = function() { get: () => _console }); - var names = Object.getOwnPropertyNames(global); + const names = Object.getOwnPropertyNames(global); for (var n = 0; n < names.length; n++) { - var name = names[n]; + const name = names[n]; if (name === 'console' || name === 'global') continue; if (GLOBAL_OBJECT_PROPERTY_MAP[name] === undefined) { @@ -637,10 +637,10 @@ REPLServer.prototype.createContext = function() { } } - var module = new Module(''); + const module = new Module(''); module.paths = Module._resolveLookupPaths('', parentModule, true) || []; - var require = internalModule.makeRequireFunction(module); + const require = internalModule.makeRequireFunction(module); context.module = module; context.require = require; @@ -771,16 +771,16 @@ function complete(line, callback) { if (this[kBufferedCommandSymbol] !== undefined && this[kBufferedCommandSymbol].length) { // Get a new array of inputted lines - var tmp = this.lines.slice(); + const tmp = this.lines.slice(); // Kill off all function declarations to push all local variables into // global scope for (var n = 0; n < this.lines.level.length; n++) { - var kill = this.lines.level[n]; + const kill = this.lines.level[n]; if (kill.isFunction) tmp[kill.line] = ''; } - var flat = new ArrayStream(); // make a new "input" stream - var magic = new REPLServer('', flat); // make a nested REPL + const flat = new ArrayStream(); // make a new "input" stream + const magic = new REPLServer('', flat); // make a nested REPL replMap.set(magic, replMap.get(this)); magic.resetContext(); flat.run(tmp); // eval the flattened code @@ -813,12 +813,12 @@ function complete(line, callback) { } else if (match = line.match(requireRE)) { // require('...') const exts = Object.keys(this.context.require.extensions); - var indexRe = new RegExp('^index(?:' + exts.map(regexpEscape).join('|') + + const indexRe = new RegExp('^index(?:' + exts.map(regexpEscape).join('|') + ')$'); - var versionedFileNamesRe = /-\d+\.\d+/; + const versionedFileNamesRe = /-\d+\.\d+/; completeOn = match[1]; - var subdir = match[2] || ''; + const subdir = match[2] || ''; filter = match[1]; var dir, files, f, name, base, ext, abs, subfiles, s, isDirectory; group = []; @@ -904,13 +904,13 @@ function complete(line, callback) { filter = ''; expr = match[0].slice(0, match[0].length - 1); } else { - var bits = match[0].split('.'); + const bits = match[0].split('.'); filter = bits.pop(); expr = bits.join('.'); } // Resolve expr and get its completions. - var memberGroups = []; + const memberGroups = []; if (!expr) { // If context is instance of vm.ScriptContext // Get global vars synchronously @@ -1006,7 +1006,7 @@ function complete(line, callback) { // Filter, sort (within each group), uniq and merge the completion groups. if (completionGroups.length && filter) { - var newCompletionGroups = []; + const newCompletionGroups = []; for (i = 0; i < completionGroups.length; i++) { group = completionGroups[i].filter(function(elem) { return elem.indexOf(filter) === 0; @@ -1019,7 +1019,7 @@ function complete(line, callback) { } if (completionGroups.length) { - var uniq = {}; // unique completions across all groups + const uniq = {}; // unique completions across all groups completions = []; // Completion group 0 is the "closest" // (least far up the inheritance chain) @@ -1092,7 +1092,7 @@ REPLServer.prototype.defineCommand = function(keyword, cmd) { }; REPLServer.prototype.memory = function memory(cmd) { - var self = this; + const self = this; self.lines = self.lines || []; self.lines.level = self.lines.level || []; @@ -1136,9 +1136,9 @@ REPLServer.prototype.memory = function memory(cmd) { }); } else if (depth < 0) { // going... up. - var curr = self.lines.level.pop(); + const curr = self.lines.level.pop(); if (curr) { - var tmp = curr.depth + depth; + const tmp = curr.depth + depth; if (tmp < 0) { //more to go, recurse depth += curr.depth; @@ -1225,10 +1225,10 @@ function defineDefaultCommands(repl) { 0 ); for (var n = 0; n < names.length; n++) { - var name = names[n]; - var cmd = this.commands[name]; - var spaces = ' '.repeat(longestNameLength - name.length + 3); - var line = `.${name}${cmd.help ? spaces + cmd.help : ''}\n`; + const name = names[n]; + const cmd = this.commands[name]; + const spaces = ' '.repeat(longestNameLength - name.length + 3); + const line = `.${name}${cmd.help ? spaces + cmd.help : ''}\n`; this.outputStream.write(line); } this.displayPrompt(); @@ -1252,12 +1252,12 @@ function defineDefaultCommands(repl) { help: 'Load JS from a file into the REPL session', action: function(file) { try { - var stats = fs.statSync(file); + const stats = fs.statSync(file); if (stats && stats.isFile()) { this.editorMode = true; REPLServer.super_.prototype.setPrompt.call(this, ''); - var data = fs.readFileSync(file, 'utf8'); - var lines = data.split('\n'); + const data = fs.readFileSync(file, 'utf8'); + const lines = data.split('\n'); for (var n = 0; n < lines.length; n++) { if (lines[n]) this.write(`${lines[n]}\n`); @@ -1295,7 +1295,7 @@ function regexpEscape(s) { // then let the user try to recover by adding more input. function isRecoverableError(e, code) { if (e && e.name === 'SyntaxError') { - var message = e.message; + const message = e.message; if (message === 'Unterminated template literal' || message === 'Missing } in template expression') { return true; @@ -1318,7 +1318,7 @@ function isCodeRecoverable(code) { var isBlockComment = false; var isSingleComment = false; var isRegExpLiteral = false; - var lastChar = code.charAt(code.length - 2); + const lastChar = code.charAt(code.length - 2); var prevTokenChar = null; for (var i = 0; i < code.length; i++) { diff --git a/lib/string_decoder.js b/lib/string_decoder.js index f0bca5705098a8..7336a61ae3707e 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -182,7 +182,7 @@ function utf8CheckExtraBytes(self, buf, p) { // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { const p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); + const r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { diff --git a/lib/timers.js b/lib/timers.js index 5f3982fa4a9620..8dc3e50b193867 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -204,8 +204,8 @@ function TimersList(msecs, unrefed) { } function listOnTimeout() { - var list = this._list; - var msecs = list.msecs; + const list = this._list; + const msecs = list.msecs; if (list.nextTick) { list.nextTick = false; @@ -215,7 +215,7 @@ function listOnTimeout() { debug('timeout callback %d', msecs); - var now = TimerWrap.now(); + const now = TimerWrap.now(); debug('now: %d', now); var diff, timer; @@ -248,7 +248,7 @@ function listOnTimeout() { continue; } - var domain = timer.domain; + const domain = timer.domain; if (domain) { // If the timer callback throws and the @@ -320,7 +320,7 @@ function tryOnTimeout(timer, list) { // Postpone all later list events to next tick. We need to do this // so that the events are called in the order they were created. const lists = list._unrefed === true ? unrefedLists : refedLists; - for (var key in lists) { + for (const key in lists) { if (key > list.msecs) { lists[key].nextTick = true; } @@ -351,7 +351,7 @@ function listOnTimeoutNT(list) { function reuse(item) { L.remove(item); - var list = refedLists[item._idleTimeout]; + const list = refedLists[item._idleTimeout]; // if empty - reuse the watcher if (list && L.isEmpty(list)) { debug('reuse hit'); @@ -375,7 +375,7 @@ const unenroll = exports.unenroll = function(item) { item._destroyed = true; } - var handle = reuse(item); + const handle = reuse(item); if (handle) { debug('unenroll: list empty'); handle.close(); @@ -423,7 +423,7 @@ function setTimeout(callback, after, arg1, arg2, arg3) { throw new errors.TypeError('ERR_INVALID_CALLBACK'); } - var len = arguments.length; + const len = arguments.length; var args; if (len === 3) { args = [arg1]; @@ -452,7 +452,7 @@ function createSingleTimeout(callback, after, args) { if (!(after >= 1 && after <= TIMEOUT_MAX)) after = 1; // schedule on next tick, follows browser behavior - var timer = new Timeout(after, callback, args); + const timer = new Timeout(after, callback, args); if (process.domain) timer.domain = process.domain; @@ -463,8 +463,8 @@ function createSingleTimeout(callback, after, args) { function ontimeout(timer) { - var args = timer._timerArgs; - var callback = timer._onTimeout; + const args = timer._timerArgs; + const callback = timer._onTimeout; if (typeof callback !== 'function') return promiseResolve(callback, args[0]); if (!args) @@ -520,7 +520,7 @@ exports.setInterval = function(callback, repeat, arg1, arg2, arg3) { throw new errors.TypeError('ERR_INVALID_CALLBACK'); } - var len = arguments.length; + const len = arguments.length; var args; if (len === 3) { args = [arg1]; @@ -541,7 +541,7 @@ function createRepeatTimeout(callback, repeat, args) { if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) repeat = 1; // schedule on next tick, follows browser behavior - var timer = new Timeout(repeat, callback, args); + const timer = new Timeout(repeat, callback, args); timer._repeat = repeat; if (process.domain) timer.domain = process.domain; @@ -595,7 +595,7 @@ Timeout.prototype.unref = function() { if (this._handle) { this._handle.unref(); } else if (typeof this._onTimeout === 'function') { - var now = TimerWrap.now(); + const now = TimerWrap.now(); if (!this._idleStart) this._idleStart = now; var delay = this._idleStart + this._idleTimeout - now; if (delay < 0) delay = 0; @@ -606,7 +606,7 @@ Timeout.prototype.unref = function() { return; } - var handle = reuse(this); + const handle = reuse(this); this._handle = handle || new TimerWrap(); this._handle.owner = this; @@ -685,12 +685,12 @@ ImmediateList.prototype.remove = function(item) { }; // Create a single linked list instance only once at startup -var immediateQueue = new ImmediateList(); +const immediateQueue = new ImmediateList(); function processImmediate() { var immediate = immediateQueue.head; - var tail = immediateQueue.tail; + const tail = immediateQueue.tail; var domain; // Clear the linked list early in case new `setImmediate()` calls occur while @@ -711,7 +711,7 @@ function processImmediate() { immediate._callback = immediate._onImmediate; // Save next in case `clearImmediate(immediate)` is called from callback - var next = immediate._idleNext; + const next = immediate._idleNext; tryOnImmediate(immediate, tail); @@ -847,7 +847,7 @@ exports.setImmediate = setImmediate; function createImmediate(args, callback) { // declaring it `const immediate` causes v6.0.0 to deoptimize this function - var immediate = new Immediate(); + const immediate = new Immediate(); immediate._callback = callback; immediate._argv = args; immediate._onImmediate = callback; diff --git a/lib/tls.js b/lib/tls.js index 91a543cb552397..925ded18baa6c9 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -55,7 +55,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); lens[i] = len; return p + 1 + len; }, 0)); diff --git a/lib/tty.js b/lib/tty.js index 81647fa684bd09..2c71a2286219aa 100644 --- a/lib/tty.js +++ b/lib/tty.js @@ -82,8 +82,8 @@ function WriteStream(fd) { // Ref: https://github.com/nodejs/node/pull/1771#issuecomment-119351671 this._handle.setBlocking(true); - var winSize = new Array(2); - var err = this._handle.getWindowSize(winSize); + const winSize = new Array(2); + const err = this._handle.getWindowSize(winSize); if (!err) { this.columns = winSize[0]; this.rows = winSize[1]; @@ -97,16 +97,16 @@ WriteStream.prototype.isTTY = true; WriteStream.prototype._refreshSize = function() { - var oldCols = this.columns; - var oldRows = this.rows; - var winSize = new Array(2); - var err = this._handle.getWindowSize(winSize); + const oldCols = this.columns; + const oldRows = this.rows; + const winSize = new Array(2); + const err = this._handle.getWindowSize(winSize); if (err) { this.emit('error', errnoException(err, 'getWindowSize')); return; } - var newCols = winSize[0]; - var newRows = winSize[1]; + const newCols = winSize[0]; + const newRows = winSize[1]; if (oldCols !== newCols || oldRows !== newRows) { this.columns = newCols; this.rows = newRows; diff --git a/lib/url.js b/lib/url.js index 887f5c29ce5a68..54853c35c0215a 100644 --- a/lib/url.js +++ b/lib/url.js @@ -94,7 +94,7 @@ const querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url instanceof Url) return url; - var u = new Url(); + const u = new Url(); u.parse(url, parseQueryString, slashesDenoteHost); return u; } @@ -308,11 +308,11 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { if (typeof this.hostname !== 'string') this.hostname = ''; - var hostname = this.hostname; + const hostname = this.hostname; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. - var ipv6Hostname = hostname.charCodeAt(0) === 91/*[*/ && + const ipv6Hostname = hostname.charCodeAt(0) === 91/*[*/ && hostname.charCodeAt(hostname.length - 1) === 93/*]*/; // validate a little. @@ -340,8 +340,8 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { this.hostname = toASCII(this.hostname, true); } - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; + const p = this.port ? ':' + this.port : ''; + const h = this.hostname || ''; this.host = h + p; // strip [ and ] from the hostname @@ -558,7 +558,7 @@ function urlFormat(urlObject, options) { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'urlObject', ['object', 'string'], urlObject); } else if (!(urlObject instanceof Url)) { - var format = urlObject[formatSymbol]; + const format = urlObject[formatSymbol]; return format ? format.call(urlObject, options) : Url.prototype.format.call(urlObject); @@ -664,15 +664,15 @@ function urlResolveObject(source, relative) { Url.prototype.resolveObject = function resolveObject(relative) { if (typeof relative === 'string') { - var rel = new Url(); + const rel = new Url(); rel.parse(relative, false, true); 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]; + const tkey = tkeys[tk]; result[tkey] = this[tkey]; } @@ -689,9 +689,9 @@ Url.prototype.resolveObject = function resolveObject(relative) { // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative - var rkeys = Object.keys(relative); + const rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; + const rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } @@ -716,9 +716,9 @@ Url.prototype.resolveObject = function resolveObject(relative) { // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { - var keys = Object.keys(relative); + const keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { - var k = keys[v]; + const k = keys[v]; result[k] = relative[k]; } result.href = result.format(); @@ -747,8 +747,8 @@ Url.prototype.resolveObject = function resolveObject(relative) { result.port = relative.port; // to support http.request if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; + const p = result.pathname || ''; + const s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; @@ -756,16 +756,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 && !slashedProtocol[result.protocol]; + const relPath = relative.pathname && relative.pathname.split('/') || []; + const noLeadingSlashes = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able @@ -861,7 +861,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 === ''); @@ -897,7 +897,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/util.js b/lib/util.js index 61b7a9d87ea268..258960df709214 100644 --- a/lib/util.js +++ b/lib/util.js @@ -165,7 +165,7 @@ function format(f) { } -var debugs = {}; +const debugs = {}; var debugEnviron; function debuglog(set) { @@ -176,9 +176,9 @@ function debuglog(set) { set = set.toUpperCase(); if (!debugs[set]) { if (debugEnviron.has(set)) { - var pid = process.pid; + const pid = process.pid; debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); + const msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { @@ -267,7 +267,7 @@ inspect.styles = Object.assign(Object.create(null), { }); function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + const style = inspect.styles[styleType]; if (style) { return `\u001b[${inspect.colors[style][0]}m${str}` + @@ -284,10 +284,10 @@ function stylizeNoColor(str, styleType) { function arrayToHash(array) { - var hash = Object.create(null); + const hash = Object.create(null); for (var i = 0; i < array.length; i++) { - var val = array[i]; + const val = array[i]; hash[val] = true; } @@ -368,14 +368,14 @@ function formatValue(ctx, value, recurseTimes) { } // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); + const primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + const visibleKeys = arrayToHash(keys); const symbolKeys = Object.getOwnPropertySymbols(value); const enumSymbolKeys = symbolKeys .filter((key) => propertyIsEnumerable.call(value, key)); @@ -626,10 +626,10 @@ function formatPrimitive(ctx, value) { if (value === null) return ctx.stylize('null', 'null'); - var type = typeof value; + const type = typeof value; if (type === 'string') { - var simple = JSON.stringify(value) + const simple = JSON.stringify(value) .replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"'); @@ -646,9 +646,9 @@ function formatPrimitive(ctx, value) { function formatPrimitiveNoColor(ctx, value) { - var stylize = ctx.stylize; + const stylize = ctx.stylize; ctx.stylize = stylizeNoColor; - var str = formatPrimitive(ctx, value); + const str = formatPrimitive(ctx, value); ctx.stylize = stylize; return str; } @@ -702,12 +702,12 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { output.push(ctx.stylize(message, 'undefined')); index = value.length; } - var remaining = value.length - index; + const remaining = value.length - index; if (remaining > 0) { output.push(`... ${remaining} more item${remaining > 1 ? 's' : ''}`); } for (var n = 0; n < keys.length; n++) { - var key = keys[n]; + const key = keys[n]; if (typeof key === 'symbol' || !numbersOnlyRE.test(key)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); @@ -720,7 +720,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { function formatTypedArray(ctx, value, recurseTimes, visibleKeys, keys) { const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), value.length); const remaining = value.length - maxLength; - var output = new Array(maxLength); + const output = new Array(maxLength); for (var i = 0; i < maxLength; ++i) output[i] = formatNumber(ctx, value[i]); if (remaining > 0) { @@ -737,10 +737,10 @@ function formatTypedArray(ctx, value, recurseTimes, visibleKeys, keys) { function formatSet(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; + const output = []; value.forEach(function(v) { - var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1; - var str = formatValue(ctx, v, nextRecurseTimes); + const nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1; + const str = formatValue(ctx, v, nextRecurseTimes); output.push(str); }); for (var n = 0; n < keys.length; n++) { @@ -752,9 +752,9 @@ function formatSet(ctx, value, recurseTimes, visibleKeys, keys) { function formatMap(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; + const output = []; value.forEach(function(v, k) { - var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1; + const nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1; var str = formatValue(ctx, k, nextRecurseTimes); str += ' => '; str += formatValue(ctx, v, nextRecurseTimes); @@ -770,9 +770,9 @@ function formatMap(ctx, value, recurseTimes, visibleKeys, keys) { function formatCollectionIterator(ctx, value, recurseTimes, visibleKeys, keys) { ensureDebugIsInitialized(); const mirror = Debug.MakeMirror(value, true); - var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1; - var vals = mirror.preview(); - var output = []; + const nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1; + const vals = mirror.preview(); + const output = []; for (const o of vals) { output.push(formatValue(ctx, o, nextRecurseTimes)); } @@ -786,8 +786,8 @@ function formatPromise(ctx, value, recurseTimes, visibleKeys, keys) { if (state === kPending) { output.push(''); } else { - var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1; - var str = formatValue(ctx, result, nextRecurseTimes); + const nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1; + const str = formatValue(ctx, result, nextRecurseTimes); if (state === kRejected) { output.push(` ${str}`); } else { @@ -859,7 +859,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { function reduceToSingleString(output, base, braces, breakLength) { - var length = output.reduce(function(prev, cur) { + const length = output.reduce(function(prev, cur) { return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); @@ -934,10 +934,10 @@ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', // 26 Feb 16:19:34 function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); + const d = new Date(); + const time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } @@ -983,7 +983,7 @@ function _extend(target, source) { // Don't do anything if source isn't an object if (source === null || typeof source !== 'object') return target; - var keys = Object.keys(source); + const keys = Object.keys(source); var i = keys.length; while (i--) { target[keys[i]] = source[keys[i]]; @@ -1046,7 +1046,7 @@ function _exceptionWithHostPort(err, if (additional) { details += ` - Local (${additional})`; } - var ex = exports._errnoException(err, syscall, details); + const ex = exports._errnoException(err, syscall, details); ex.address = address; if (port) { ex.port = port; diff --git a/lib/vm.js b/lib/vm.js index e7fccc97493bcb..4601efc2e1b3b8 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -61,7 +61,7 @@ Script.prototype.runInContext = function(contextifiedSandbox, options) { }; Script.prototype.runInNewContext = function(sandbox, options) { - var context = createContext(sandbox); + const context = createContext(sandbox); return this.runInContext(context, options); }; diff --git a/lib/zlib.js b/lib/zlib.js index 35d998df26af3f..d55ee0df2c6865 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -55,7 +55,7 @@ const codes = { const ckeys = Object.keys(codes); for (var ck = 0; ck < ckeys.length; ck++) { - var ckey = ckeys[ck]; + const ckey = ckeys[ck]; codes[codes[ckey]] = ckey; } @@ -94,7 +94,7 @@ function zlibBufferOnEnd() { if (this.nread >= kMaxLength) { err = new RangeError(kRangeErrorMessage); } else { - var bufs = this.buffers; + const bufs = this.buffers; buf = (bufs.length === 1 ? bufs[0] : Buffer.concat(bufs, this.nread)); } this.close(); @@ -121,13 +121,13 @@ function zlibBufferSync(engine, buffer) { } function zlibOnError(message, errno) { - var self = this.jsref; + const self = this.jsref; // there is no way to cleanly recover. // continuing only obscures problems. _close(self); self._hadError = true; - var error = new Error(message); + const error = new Error(message); error.errno = errno; error.code = codes[errno]; self.emit('error', error); @@ -317,7 +317,7 @@ function maxFlush(a, b) { } Zlib.prototype.flush = function flush(kind, callback) { - var ws = this._writableState; + const ws = this._writableState; if (typeof kind === 'function' || (kind === undefined && !callback)) { callback = kind; @@ -359,7 +359,7 @@ Zlib.prototype._transform = function _transform(chunk, encoding, cb) { // If it's explicitly flushing at some other time, then we use // Z_FULL_FLUSH. Otherwise, use the original opts.flush flag. var flushFlag; - var ws = this._writableState; + const ws = this._writableState; if ((ws.ending || ws.ended) && ws.length === chunk.byteLength) { flushFlag = this._finishFlushFlag; } else { @@ -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(er) { @@ -415,12 +415,12 @@ function processChunkSync(self, chunk, flushFlag) { availOutAfter = state[0]; availInAfter = state[1]; - var inDelta = (availInBefore - availInAfter); + const inDelta = (availInBefore - availInAfter); inputRead += inDelta; - var have = availOutBefore - availOutAfter; + const have = availOutBefore - availOutAfter; if (have > 0) { - var out = buffer.slice(offset, offset + have); + const out = buffer.slice(offset, offset + have); offset += have; if (!buffers) buffers = [out]; @@ -463,7 +463,7 @@ function processChunkSync(self, chunk, flushFlag) { } function processChunk(self, chunk, flushFlag, cb) { - var handle = self._handle; + const handle = self._handle; if (!handle) return cb(new Error('zlib binding closed')); @@ -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.jsref; - var state = self._writeState; + const handle = this; + const self = this.jsref; + const state = self._writeState; if (self._hadError) { this.buffer = null; @@ -501,15 +501,15 @@ function processCallback() { return; } - var availOutAfter = state[0]; - var availInAfter = state[1]; + const availOutAfter = state[0]; + const availInAfter = state[1]; - var inDelta = (handle.availInBefore - availInAfter); + const inDelta = (handle.availInBefore - availInAfter); self.bytesRead += inDelta; - var have = handle.availOutBefore - availOutAfter; + const have = handle.availOutBefore - availOutAfter; if (have > 0) { - var out = self._outBuffer.slice(self._outOffset, self._outOffset + have); + const out = self._outBuffer.slice(self._outOffset, self._outOffset + have); self._outOffset += have; self.push(out); } else if (have < 0) { @@ -690,7 +690,7 @@ Object.defineProperties(module.exports, { // expose all the zlib constants const bkeys = Object.keys(constants); for (var bk = 0; bk < bkeys.length; bk++) { - var bkey = bkeys[bk]; + const bkey = bkeys[bk]; Object.defineProperty(module.exports, bkey, { enumerable: true, value: constants[bkey], writable: false });