From f25c7ceb731e350591b2e8d406bb8f65d1897ea9 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Tue, 12 Jan 2016 12:21:09 +0000 Subject: [PATCH 01/34] win,msi: Added Italian translation As titled. Tested by @piccoloaiutante. PR-URL: https://github.com/nodejs/node/pull/4647 Refs: https://github.com/wixtoolset/wix3/pull/366 Reviewed-By: Rod Vagg Reviewed-By: Frederic Hemberger --- tools/msvs/msi/i18n/it-it.wxl | 38 ++++++++++++++++++++++++++++++++++ tools/msvs/msi/nodemsi.wixproj | 3 +++ 2 files changed, 41 insertions(+) create mode 100644 tools/msvs/msi/i18n/it-it.wxl diff --git a/tools/msvs/msi/i18n/it-it.wxl b/tools/msvs/msi/i18n/it-it.wxl new file mode 100644 index 00000000000000..54a251ea2530b4 --- /dev/null +++ b/tools/msvs/msi/i18n/it-it.wxl @@ -0,0 +1,38 @@ + + + + 1040 + + Installazione di [ProductName] sul tuo computer. + Scegliere una cartella di destinazione o premere Avanti per installare nella cartella predefinita. + + Una versione successiva di [ProductName] è già installata. Il setup terminerà ora. + + + Node.js runtime + Installa [ProductName] runtime (node.exe). + + Performance counters + Installa il supporto per i performance counters specifici di [ProductName]. + + Event tracing (ETW) + Installa il supporto per gli eventi "event tracing" (ETW) generati da [ProductName]. + + npm package manager + Installa npm, il package manager raccomandato per [ProductName]. + + Collegamenti alla documentazione online + Aggiunge i collegamenti al menu start alla documentazione online per [ProductName] [FullVersion] e per il sito web di [ProductName]. + + Aggiunta al PATH + Aggiunge [ProductName], npm, e i moduli installati globalmente da npm alla variable di ambiente PATH. + + Node.js e npm + Aggiunge [ProductName] e npm (se installato) alla variabile di ambiente PATH. + + Moduli npm + Aggiunge i moduli installati globalmente da npm alla variabile di ambiente PATH. Questa opzione avrà effetto solo per l'utente corrente, gli altri utenti dovranno aggiornare la loro variabile PATH manualmente. + + + Node.js è stato installato correttamente. + diff --git a/tools/msvs/msi/nodemsi.wixproj b/tools/msvs/msi/nodemsi.wixproj index 70ffec50bcc8e4..d21a3cf2327432 100644 --- a/tools/msvs/msi/nodemsi.wixproj +++ b/tools/msvs/msi/nodemsi.wixproj @@ -56,6 +56,7 @@ + @@ -78,7 +79,9 @@ From 9db861b650ef7e83172b55f4df45b366e1e466b7 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 10 Jul 2016 14:01:00 -0700 Subject: [PATCH 02/34] tools: increase lint coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extend linting to tools/license2rtf.js and any other JS that gets added to the `tools` directory by default. This incidentally simplifies lint invocation. PR-URL: https://github.com/nodejs/node/pull/7647 Reviewed-By: Michaël Zasso Reviewed-By: Ben Noordhuis Reviewed-By: Roman Reiss Reviewed-By: Сковорода Никита Андреевич --- .eslintignore | 4 +- Makefile | 6 +-- tools/license2rtf.js | 100 +++++++++++++++++++++---------------------- vcbuild.bat | 4 +- 4 files changed, 55 insertions(+), 59 deletions(-) diff --git a/.eslintignore b/.eslintignore index 9b5c5fccb643e4..6791fbf312a08b 100644 --- a/.eslintignore +++ b/.eslintignore @@ -2,7 +2,7 @@ lib/internal/v8_prof_polyfill.js lib/punycode.js test/addons/??_*/ test/fixtures -test/**/node_modules test/disabled test/tmp*/ -tools/doc/node_modules +tools/eslint +node_modules diff --git a/Makefile b/Makefile index ebea5354f0c6fb..fe058a5b7ec890 100644 --- a/Makefile +++ b/Makefile @@ -678,13 +678,11 @@ bench-idle: $(NODE) benchmark/idle_clients.js & jslint: - $(NODE) tools/jslint.js -J benchmark lib src test tools/doc \ - tools/eslint-rules tools/jslint.js + $(NODE) tools/jslint.js -J benchmark lib src test tools jslint-ci: $(NODE) tools/jslint.js $(PARALLEL_ARGS) -f tap -o test-eslint.tap \ - benchmark lib src test tools/doc \ - tools/eslint-rules tools/jslint.js + benchmark lib src test tools CPPLINT_EXCLUDE ?= CPPLINT_EXCLUDE += src/node_root_certs.h diff --git a/tools/license2rtf.js b/tools/license2rtf.js index f5a75a176dd6bb..0b66cc10f322f9 100644 --- a/tools/license2rtf.js +++ b/tools/license2rtf.js @@ -1,15 +1,16 @@ +'use strict'; -var assert = require('assert'), - Stream = require('stream'), - inherits = require('util').inherits; +const assert = require('assert'); +const Stream = require('stream'); +const inherits = require('util').inherits; /* * This filter consumes a stream of characters and emits one string per line. */ function LineSplitter() { - var self = this, - buffer = ""; + const self = this; + var buffer = ''; Stream.call(this); this.writable = true; @@ -38,33 +39,31 @@ inherits(LineSplitter, Stream); * This filter consumes lines and emits paragraph objects. */ function ParagraphParser() { - var self = this, - block_is_license_block = false, - block_has_c_style_comment, - is_first_line_in_paragraph, - paragraph_line_indent, - paragraph; - - Stream.call(this); - this.writable = true; - - resetBlock(false); - - this.write = function(data) { - parseLine(data + ''); - return true; - }; - - this.end = function(data) { - if (data) { - parseLine(data + ''); - } - flushParagraph(); - self.emit('end'); - }; + const self = this; + var block_is_license_block = false; + var block_has_c_style_comment; + var paragraph_line_indent; + var paragraph; + + Stream.call(this); + this.writable = true; + + resetBlock(false); + + this.write = function(data) { + parseLine(data + ''); + return true; + }; + + this.end = function(data) { + if (data) { + parseLine(data + ''); + } + flushParagraph(); + self.emit('end'); + }; function resetParagraph() { - is_first_line_in_paragraph = true; paragraph_line_indent = -1; paragraph = { @@ -165,8 +164,6 @@ function ParagraphParser() { if (line) paragraph.lines.push(line); - - is_first_line_in_paragraph = false; } } inherits(ParagraphParser, Stream); @@ -184,16 +181,16 @@ function Unwrapper() { this.writable = true; this.write = function(paragraph) { - var lines = paragraph.lines, - break_after = [], - i; + var lines = paragraph.lines; + var break_after = []; + var i; for (i = 0; i < lines.length - 1; i++) { var line = lines[i]; // When a line is really short, the line was probably kept separate for a // reason. - if (line.length < 50) { + if (line.length < 50) { // If the first word on the next line really didn't fit after the line, // it probably was just ordinary wrapping after all. var next_first_word_length = lines[i + 1].replace(/\s.*$/, '').length; @@ -203,7 +200,7 @@ function Unwrapper() { } } - for (i = 0; i < lines.length - 1; ) { + for (i = 0; i < lines.length - 1;) { if (!break_after[i]) { lines[i] += ' ' + lines.splice(i + 1, 1)[0]; } else { @@ -233,8 +230,8 @@ inherits(Unwrapper, Stream); * This filter generates an rtf document from a stream of paragraph objects. */ function RtfGenerator() { - var self = this, - did_write_anything = false; + const self = this; + var did_write_anything = false; Stream.call(this); this.writable = true; @@ -245,11 +242,11 @@ function RtfGenerator() { did_write_anything = true; } - var li = paragraph.li, - level = paragraph.level + (li ? 1 : 0), - lic = paragraph.in_license_block; + var li = paragraph.li; + var level = paragraph.level + (li ? 1 : 0); + var lic = paragraph.in_license_block; - var rtf = "\\pard"; + var rtf = '\\pard'; rtf += '\\sa150\\sl300\\slmult1'; if (level > 0) rtf += '\\li' + (level * 240); @@ -290,18 +287,19 @@ function RtfGenerator() { function rtfEscape(string) { return string .replace(/[\\\{\}]/g, function(m) { - return '\\' + m; + return '\\' + m; }) .replace(/\t/g, function() { return '\\tab '; }) + // eslint-disable-next-line no-control-regex .replace(/[\x00-\x1f\x7f-\xff]/g, function(m) { return '\\\'' + toHex(m.charCodeAt(0), 2); }) .replace(/\ufeff/g, '') .replace(/[\u0100-\uffff]/g, function(m) { return '\\u' + toHex(m.charCodeAt(0), 4) + '?'; - }); + }); } function emitHeader() { @@ -317,12 +315,12 @@ function RtfGenerator() { inherits(RtfGenerator, Stream); -var stdin = process.stdin, - stdout = process.stdout, - line_splitter = new LineSplitter(), - paragraph_parser = new ParagraphParser(), - unwrapper = new Unwrapper(), - rtf_generator = new RtfGenerator(); +const stdin = process.stdin; +const stdout = process.stdout; +const line_splitter = new LineSplitter(); +const paragraph_parser = new ParagraphParser(); +const unwrapper = new Unwrapper(); +const rtf_generator = new RtfGenerator(); stdin.setEncoding('utf-8'); stdin.resume(); diff --git a/vcbuild.bat b/vcbuild.bat index ee5b4c8a17df08..f95cfca8b390a9 100644 --- a/vcbuild.bat +++ b/vcbuild.bat @@ -348,12 +348,12 @@ if defined jslint_ci goto jslint-ci if not defined jslint goto exit if not exist tools\eslint\bin\eslint.js goto no-lint echo running jslint -%config%\node tools\jslint.js -J benchmark lib src test tools\doc tools\eslint-rules tools\jslint.js +%config%\node tools\jslint.js -J benchmark lib src test tools goto exit :jslint-ci echo running jslint-ci -%config%\node tools\jslint.js -J -f tap -o test-eslint.tap benchmark lib src test tools\doc tools\eslint-rules tools\jslint.js +%config%\node tools\jslint.js -J -f tap -o test-eslint.tap benchmark lib src test tools goto exit :no-lint From 25b3ff402d50fe12d9088973d3f6fd0fa56ce6f6 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 8 Jul 2016 12:59:26 +0200 Subject: [PATCH 03/34] test,doc: clarify `buf.indexOf(num)` input range Hopefully clarify the behaviour of `buffer.indexOf()` and `buffer.includes()` for numbers in that they will be truncated to uint8s. Add tests for that behaviour. Fixes: https://github.com/nodejs/node/issues/7591 PR-URL: https://github.com/nodejs/node/pull/7611 Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott --- doc/api/buffer.md | 6 ++++-- test/parallel/test-buffer-includes.js | 16 ++++++++++++++++ test/parallel/test-buffer-indexof.js | 16 ++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index fd527a02d170ff..fb8065a645fdab 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -973,7 +973,8 @@ Operates similar to [`Array#indexOf()`][] in that it returns either the starting index position of `value` in Buffer or `-1` if the Buffer does not contain `value`. The `value` can be a String, Buffer or Number. Strings are by default interpreted as UTF8. Buffers will use the entire Buffer (to compare a -partial Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255. +partial Buffer use [`buf.slice()`][]). Numbers will be interpreted as unsigned 8-bit +integer values between `0` and `255`. ```js const buf = Buffer.from('this is a buffer'); @@ -1012,7 +1013,8 @@ added: v5.3.0 Operates similar to [`Array#includes()`][]. The `value` can be a String, Buffer or Number. Strings are interpreted as UTF8 unless overridden with the `encoding` argument. Buffers will use the entire Buffer (to compare a partial -Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255. +Buffer use [`buf.slice()`][]). Numbers will be interpreted as unsigned 8-bit +integer values between `0` and `255`. The `byteOffset` indicates the index in `buf` where searching begins. diff --git a/test/parallel/test-buffer-includes.js b/test/parallel/test-buffer-includes.js index 7962d1cef850f4..5859399b507f86 100644 --- a/test/parallel/test-buffer-includes.js +++ b/test/parallel/test-buffer-includes.js @@ -256,3 +256,19 @@ assert.throws(function() { assert.throws(function() { b.includes([]); }); + +// test truncation of Number arguments to uint8 +{ + const buf = Buffer.from('this is a test'); + assert.ok(buf.includes(0x6973)); + assert.ok(buf.includes(0x697320)); + assert.ok(buf.includes(0x69732069)); + assert.ok(buf.includes(0x697374657374)); + assert.ok(buf.includes(0x69737374)); + assert.ok(buf.includes(0x69737465)); + assert.ok(buf.includes(0x69737465)); + assert.ok(buf.includes(-140)); + assert.ok(buf.includes(-152)); + assert.ok(!buf.includes(0xff)); + assert.ok(!buf.includes(0xffff)); +} diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 647f1e9a623248..d699e1cd5909ea 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -448,3 +448,19 @@ pattern = reallyLong.slice(0, 1000000); // First 1/5th. assert.equal(3932160, reallyLong.lastIndexOf(pattern)); pattern = reallyLong.slice(0, 2000000); // first 2/5ths. assert.equal(0, reallyLong.lastIndexOf(pattern)); + +// test truncation of Number arguments to uint8 +{ + const buf = Buffer.from('this is a test'); + assert.strictEqual(buf.indexOf(0x6973), 3); + assert.strictEqual(buf.indexOf(0x697320), 4); + assert.strictEqual(buf.indexOf(0x69732069), 2); + assert.strictEqual(buf.indexOf(0x697374657374), 0); + assert.strictEqual(buf.indexOf(0x69737374), 0); + assert.strictEqual(buf.indexOf(0x69737465), 11); + assert.strictEqual(buf.indexOf(0x69737465), 11); + assert.strictEqual(buf.indexOf(-140), 0); + assert.strictEqual(buf.indexOf(-152), 1); + assert.strictEqual(buf.indexOf(0xff), -1); + assert.strictEqual(buf.indexOf(0xffff), -1); +} From 45a8fce5a465f78163fd8961c11345716b638f46 Mon Sep 17 00:00:00 2001 From: vsemozhetbyt Date: Wed, 6 Jul 2016 21:50:58 +0300 Subject: [PATCH 04/34] doc: fix typo in the CHANGELOG_V6 compliment -> complement PR-URL: https://github.com/nodejs/node/pull/7568 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- doc/changelogs/CHANGELOG_V6.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/changelogs/CHANGELOG_V6.md b/doc/changelogs/CHANGELOG_V6.md index 06462967547187..0a6f372a5acaa2 100644 --- a/doc/changelogs/CHANGELOG_V6.md +++ b/doc/changelogs/CHANGELOG_V6.md @@ -33,7 +33,7 @@ October 2016. ### Notable changes -* **buffer**: Added `buffer.swap64()` to compliment `swap16()` & `swap32()`. (Zach Bjornson) [#7157](https://github.com/nodejs/node/pull/7157) +* **buffer**: Added `buffer.swap64()` to complement `swap16()` & `swap32()`. (Zach Bjornson) [#7157](https://github.com/nodejs/node/pull/7157) * **build**: New `configure` options have been added for building Node.js as a shared library. (Stefan Budeanu) [#6994](https://github.com/nodejs/node/pull/6994) - The options are: `--shared`, `--without-v8-platform` & `--without-bundled-v8`. * **crypto**: Root certificates have been updated. (Ben Noordhuis) [#7363](https://github.com/nodejs/node/pull/7363) From 8bbb3eb32c4403949faff3cc0a77ae076fc27830 Mon Sep 17 00:00:00 2001 From: silverwind Date: Wed, 13 Jul 2016 00:09:41 +0200 Subject: [PATCH 05/34] tools: consistent .eslintrc formatting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All quotes in .eslintrc were unnecessary and inconsistently placed across the file. Additionally, format the globals to be consistent with the style of whitespace and sorted them alphabetically. PR-URL: https://github.com/nodejs/node/pull/7691 Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott Reviewed-By: Michaël Zasso --- .eslintrc | 66 +++++++++++++++++++++++++------------------------- test/.eslintrc | 2 +- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/.eslintrc b/.eslintrc index dbc12427ca7ed7..120bca8d2f3b4b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -5,7 +5,7 @@ env: rules: # Possible Errors # http://eslint.org/docs/rules/#possible-errors - comma-dangle: [2, "only-multiline"] + comma-dangle: [2, only-multiline] no-control-regex: 2 no-debugger: 2 no-dupe-args: 2 @@ -14,7 +14,7 @@ rules: no-empty-character-class: 2 no-ex-assign: 2 no-extra-boolean-cast: 2 - no-extra-parens: [2, "functions"] + no-extra-parens: [2, functions] no-extra-semi: 2 no-func-assign: 2 no-invalid-regexp: 2 @@ -38,47 +38,47 @@ rules: # Strict Mode # http://eslint.org/docs/rules/#strict-mode - strict: [2, "global"] + strict: [2, global] # Variables # http://eslint.org/docs/rules/#variables no-delete-var: 2 no-undef: 2 - no-unused-vars: [2, {"args": "none"}] + no-unused-vars: [2, {args: none}] # Node.js and CommonJS # http://eslint.org/docs/rules/#nodejs-and-commonjs no-mixed-requires: 2 no-new-require: 2 no-path-concat: 2 - no-restricted-modules: [2, "sys", "_linklist"] + no-restricted-modules: [2, sys, _linklist] # Stylistic Issues # http://eslint.org/docs/rules/#stylistic-issues - brace-style: [2, "1tbs", {allowSingleLine: true}] + brace-style: [2, 1tbs, {allowSingleLine: true}] comma-spacing: 2 eol-last: 2 indent: [2, 2, {SwitchCase: 1}] - key-spacing: [2, {mode: "minimum"}] + key-spacing: [2, {mode: minimum}] keyword-spacing: 2 - linebreak-style: [2, "unix"] + linebreak-style: [2, unix] max-len: [2, 80, 2] new-parens: 2 no-mixed-spaces-and-tabs: 2 no-multiple-empty-lines: [2, {max: 2}] no-trailing-spaces: 2 - quotes: [2, "single", "avoid-escape"] + quotes: [2, single, avoid-escape] semi: 2 - space-before-blocks: [2, "always"] - space-before-function-paren: [2, "never"] - space-in-parens: [2, "never"] + space-before-blocks: [2, always] + space-before-function-paren: [2, never] + space-in-parens: [2, never] space-infix-ops: 2 space-unary-ops: 2 # ECMAScript 6 # http://eslint.org/docs/rules/#ecmascript-6 - arrow-parens: [2, "always"] - arrow-spacing: [2, {"before": true, "after": true}] + arrow-parens: [2, always] + arrow-spacing: [2, {before: true, after: true}] constructor-super: 2 no-class-assign: 2 no-confusing-arrow: 2 @@ -93,27 +93,27 @@ rules: align-function-arguments: 2 align-multiline-assignment: 2 assert-fail-single-argument: 2 - new-with-error: [2, "Error", "RangeError", "TypeError", "SyntaxError", "ReferenceError"] + new-with-error: [2, Error, RangeError, TypeError, SyntaxError, ReferenceError] no-deepEqual: 2 no-definegetter-definesetter: 2 # Global scoped method and vars globals: - DTRACE_HTTP_CLIENT_REQUEST : false - LTTNG_HTTP_CLIENT_REQUEST : false - COUNTER_HTTP_CLIENT_REQUEST : false - DTRACE_HTTP_CLIENT_RESPONSE : false - LTTNG_HTTP_CLIENT_RESPONSE : false - COUNTER_HTTP_CLIENT_RESPONSE : false - DTRACE_HTTP_SERVER_REQUEST : false - LTTNG_HTTP_SERVER_REQUEST : false - COUNTER_HTTP_SERVER_REQUEST : false - DTRACE_HTTP_SERVER_RESPONSE : false - LTTNG_HTTP_SERVER_RESPONSE : false - COUNTER_HTTP_SERVER_RESPONSE : false - DTRACE_NET_STREAM_END : false - LTTNG_NET_STREAM_END : false - COUNTER_NET_SERVER_CONNECTION_CLOSE : false - DTRACE_NET_SERVER_CONNECTION : false - LTTNG_NET_SERVER_CONNECTION : false - COUNTER_NET_SERVER_CONNECTION : false + COUNTER_HTTP_CLIENT_REQUEST: false + COUNTER_HTTP_CLIENT_RESPONSE: false + COUNTER_HTTP_SERVER_REQUEST: false + COUNTER_HTTP_SERVER_RESPONSE: false + COUNTER_NET_SERVER_CONNECTION: false + COUNTER_NET_SERVER_CONNECTION_CLOSE: false + DTRACE_HTTP_CLIENT_REQUEST: false + DTRACE_HTTP_CLIENT_RESPONSE: false + DTRACE_HTTP_SERVER_REQUEST: false + DTRACE_HTTP_SERVER_RESPONSE: false + DTRACE_NET_SERVER_CONNECTION: false + DTRACE_NET_STREAM_END: false + LTTNG_HTTP_CLIENT_REQUEST: false + LTTNG_HTTP_CLIENT_RESPONSE: false + LTTNG_HTTP_SERVER_REQUEST: false + LTTNG_HTTP_SERVER_RESPONSE: false + LTTNG_NET_SERVER_CONNECTION: false + LTTNG_NET_STREAM_END: false diff --git a/test/.eslintrc b/test/.eslintrc index b498b08f4d7d0c..d20e21aa27f2a3 100644 --- a/test/.eslintrc +++ b/test/.eslintrc @@ -2,4 +2,4 @@ rules: ## common module is mandatory in tests - required-modules: [2, "common"] + required-modules: [2, common] From e1e477e2a0b00581a2fb013e3c71232ed7f75922 Mon Sep 17 00:00:00 2001 From: Minqi Pan Date: Thu, 14 Jul 2016 10:59:44 +0800 Subject: [PATCH 06/34] win,msi: add zh-CN translations for the installer PR-URL: https://github.com/nodejs/node/pull/2569 Reviewed-By: Jackson Tian Reviewed-By: Wexpo Lyu Reviewed-By: Yiyu He Reviewed-By: Yorkie Liu --- tools/msvs/msi/i18n/zh-cn.wxl | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 tools/msvs/msi/i18n/zh-cn.wxl diff --git a/tools/msvs/msi/i18n/zh-cn.wxl b/tools/msvs/msi/i18n/zh-cn.wxl new file mode 100644 index 00000000000000..605eea70927c14 --- /dev/null +++ b/tools/msvs/msi/i18n/zh-cn.wxl @@ -0,0 +1,38 @@ + + + + 2052 + + 本安装向导将在您的计算机上安装 [ProductName]。 + 请选择一个自定义的安装位置,或单击下一步开始安装。 + + 已安装 [ProductName] 的一个更高版本。安装程序将立即退出。 + + + Node.js 运行时 + 安装核心 [ProductName] 运行时(node.exe)。 + + 性能计数器 + 为 [ProductName] 安装特定的性能计数器支持。 + + 事件追踪(ETW) + 为 [ProductName] 生成的事件安装事件追踪(ETW)的支持。 + + npm 包管理器 + 安装 npm, [ProductName] 的推荐包管理器。 + + 在线文档的快捷方式 + 在开始菜单内添加 [ProductName] [FullVersion] 的在线文档链接和 [ProductName] 的网站链接。 + + 添加到 PATH 环境变量中 + 把 [ProductName], npm 和以全局方式安装的 npm 模块添加到 PATH 环境变量中。 + + Node.js 和 npm + 把 [ProductName] 和 npm(如果安装了)添加到 PATH 环境变量中。 + + npm 模块 + 把以全局方式安装的 npm 模块添加到 PATH 环境变量中。此选项仅适用于当前用户;其他用户需要手动更新他们的 PATH 环境变量。 + + + Node.js 已成功安装。 + From 43b5bf4616dcb4ab0ae356295a7c8dbb4312c5fd Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Wed, 1 Jun 2016 16:07:23 -0700 Subject: [PATCH 07/34] inspector: Unify event queues Current implementation tracks connected/disconnected status separately which potentially introduces race condition. This change introduces notion of session IDs and also posts connect/disconnect events into the same queue as the messages. This way Node knows what session given response belongs to and can discard messages if the frontend for that session had disconnected. This also fixes an issue when frontend was unable to attach to V8 instance that was running infinite loop. PR-URL: https://github.com/nodejs/node/pull/7271 Reviewed-By: bnoordhuis - Ben Noordhuis --- src/inspector_agent.cc | 213 +++++++++++++++++++++-------------------- 1 file changed, 110 insertions(+), 103 deletions(-) diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index 8ef95305a6f3c0..d8233f41dc2de9 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -17,6 +17,7 @@ #include "libplatform/libplatform.h" #include +#include #include // We need pid to use as ID with Chrome @@ -31,6 +32,9 @@ namespace node { namespace { +const char TAG_CONNECT[] = "#connect"; +const char TAG_DISCONNECT[] = "#disconnect"; + const char DEVTOOLS_PATH[] = "/node"; const char DEVTOOLS_HASH[] = "521e5b7e2b7cc66b4006a8a54cb9c4e57494a5ef"; @@ -154,7 +158,6 @@ bool RespondToGet(inspector_socket_t* socket, const char* path, int port) { namespace inspector { using blink::protocol::DictionaryValue; -using blink::protocol::String16; class AgentImpl { public: @@ -171,24 +174,27 @@ class AgentImpl { void WaitForDisconnect(); private: + using MessageQueue = std::vector>; + static void ThreadCbIO(void* agent); static void OnSocketConnectionIO(uv_stream_t* server, int status); static bool OnInspectorHandshakeIO(inspector_socket_t* socket, enum inspector_handshake_event state, const char* path); - static void OnRemoteDataIO(uv_stream_t* stream, ssize_t read, - const uv_buf_t* b); static void WriteCbIO(uv_async_t* async); void WorkerRunIO(); void OnInspectorConnectionIO(inspector_socket_t* socket); - void PushPendingMessage(std::vector* queue, - const std::string& message); - void SwapBehindLock(std::vector AgentImpl::*queue, - std::vector* output); + void OnRemoteDataIO(inspector_socket_t* stream, ssize_t read, + const uv_buf_t* b); void PostMessages(); void SetConnected(bool connected); - void Write(const std::string& message); + void DispatchMessages(); + void Write(int session_id, const String16& message); + void AppendMessage(MessageQueue* vector, int session_id, + const String16& message); + void SwapBehindLock(MessageQueue* vector1, MessageQueue* vector2); + void PostIncomingMessage(const String16& message); uv_sem_t start_sem_; ConditionVariable pause_cond_; @@ -208,19 +214,28 @@ class AgentImpl { inspector_socket_t* client_socket_; blink::V8Inspector* inspector_; v8::Platform* platform_; - std::vector message_queue_; - std::vector outgoing_message_queue_; + MessageQueue incoming_message_queue_; + MessageQueue outgoing_message_queue_; bool dispatching_messages_; + int frontend_session_id_; + int backend_session_id_; friend class ChannelImpl; friend class DispatchOnInspectorBackendTask; friend class SetConnectedTask; friend class V8NodeInspector; friend void InterruptCallback(v8::Isolate*, void* agent); + friend void DataCallback(uv_stream_t* stream, ssize_t read, + const uv_buf_t* buf); }; void InterruptCallback(v8::Isolate*, void* agent) { - static_cast(agent)->PostMessages(); + static_cast(agent)->DispatchMessages(); +} + +void DataCallback(uv_stream_t* stream, ssize_t read, const uv_buf_t* buf) { + inspector_socket_t* socket = static_cast(stream->data); + static_cast(socket->data)->OnRemoteDataIO(socket, read, buf); } class DispatchOnInspectorBackendTask : public v8::Task { @@ -228,7 +243,7 @@ class DispatchOnInspectorBackendTask : public v8::Task { explicit DispatchOnInspectorBackendTask(AgentImpl* agent) : agent_(agent) {} void Run() override { - agent_->PostMessages(); + agent_->DispatchMessages(); } private: @@ -251,27 +266,12 @@ class ChannelImpl final : public blink::protocol::FrontendChannel { void flushProtocolNotifications() override { } void sendMessageToFrontend(const String16& message) { - agent_->Write(message.utf8()); + agent_->Write(agent_->frontend_session_id_, message); } AgentImpl* const agent_; }; -class SetConnectedTask : public v8::Task { - public: - SetConnectedTask(AgentImpl* agent, bool connected) - : agent_(agent), - connected_(connected) {} - - void Run() override { - agent_->SetConnected(connected_); - } - - private: - AgentImpl* agent_; - bool connected_; -}; - class V8NodeInspector : public blink::V8Inspector { public: V8NodeInspector(AgentImpl* agent, node::Environment* env, @@ -320,7 +320,9 @@ AgentImpl::AgentImpl(Environment* env) : port_(0), client_socket_(nullptr), inspector_(nullptr), platform_(nullptr), - dispatching_messages_(false) { + dispatching_messages_(false), + frontend_session_id_(0), + backend_session_id_(0) { CHECK_EQ(0, uv_sem_init(&start_sem_, 0)); memset(&data_written_, 0, sizeof(data_written_)); memset(&io_thread_req_, 0, sizeof(io_thread_req_)); @@ -355,10 +357,7 @@ void AgentImpl::Start(v8::Platform* platform, int port, bool wait) { uv_sem_wait(&start_sem_); if (wait) { - // Flush messages in case of wait to connect, see OnRemoteDataIO on how it - // should be fixed. - SetConnected(true); - PostMessages(); + DispatchMessages(); } } @@ -424,55 +423,39 @@ bool AgentImpl::OnInspectorHandshakeIO(inspector_socket_t* socket, } } -// static -void AgentImpl::OnRemoteDataIO(uv_stream_t* stream, - ssize_t read, - const uv_buf_t* b) { - inspector_socket_t* socket = static_cast(stream->data); - AgentImpl* agent = static_cast(socket->data); - Mutex::ScopedLock scoped_lock(agent->pause_lock_); +void AgentImpl::OnRemoteDataIO(inspector_socket_t* socket, + ssize_t read, + const uv_buf_t* buf) { + Mutex::ScopedLock scoped_lock(pause_lock_); if (read > 0) { - std::string str(b->base, read); - agent->PushPendingMessage(&agent->message_queue_, str); - free(b->base); - + String16 str = String16::fromUTF8(buf->base, read); + PostIncomingMessage(str); // TODO(pfeldman): Instead of blocking execution while debugger // engages, node should wait for the run callback from the remote client // and initiate its startup. This is a change to node.cc that should be // upstreamed separately. - if (agent->wait_ && str.find("\"Runtime.run\"") != std::string::npos) { - agent->wait_ = false; - uv_sem_post(&agent->start_sem_); + if (wait_ && str.find("\"Runtime.run\"") != std::string::npos) { + wait_ = false; + uv_sem_post(&start_sem_); } - agent->platform_->CallOnForegroundThread(agent->parent_env_->isolate(), - new DispatchOnInspectorBackendTask(agent)); - agent->parent_env_->isolate() - ->RequestInterrupt(InterruptCallback, agent); - uv_async_send(&agent->data_written_); + platform_->CallOnForegroundThread(parent_env_->isolate(), + new DispatchOnInspectorBackendTask(this)); + parent_env_->isolate()->RequestInterrupt(InterruptCallback, this); + uv_async_send(&data_written_); } else if (read <= 0) { // EOF - if (agent->client_socket_ == socket) { - agent->client_socket_ = nullptr; - agent->platform_->CallOnForegroundThread(agent->parent_env_->isolate(), - new SetConnectedTask(agent, false)); - uv_async_send(&agent->data_written_); + if (client_socket_ == socket) { + String16 message(TAG_DISCONNECT, sizeof(TAG_DISCONNECT) - 1); + client_socket_ = nullptr; + PostIncomingMessage(message); } DisconnectAndDisposeIO(socket); } - agent->pause_cond_.Broadcast(scoped_lock); -} - -void AgentImpl::PushPendingMessage(std::vector* queue, - const std::string& message) { - Mutex::ScopedLock scoped_lock(queue_lock_); - queue->push_back(message); -} - -void AgentImpl::SwapBehindLock(std::vector AgentImpl::*queue, - std::vector* output) { - Mutex::ScopedLock scoped_lock(queue_lock_); - (this->*queue).swap(*output); + if (buf) { + free(buf->base); + } + pause_cond_.Broadcast(scoped_lock); } // static @@ -480,11 +463,14 @@ void AgentImpl::WriteCbIO(uv_async_t* async) { AgentImpl* agent = static_cast(async->data); inspector_socket_t* socket = agent->client_socket_; if (socket) { - std::vector outgoing_messages; - agent->SwapBehindLock(&AgentImpl::outgoing_message_queue_, - &outgoing_messages); - for (auto const& message : outgoing_messages) - inspector_write(socket, message.c_str(), message.length()); + MessageQueue outgoing_messages; + agent->SwapBehindLock(&agent->outgoing_message_queue_, &outgoing_messages); + for (const MessageQueue::value_type& outgoing : outgoing_messages) { + if (outgoing.first == agent->frontend_session_id_) { + std::string message = outgoing.second.utf8(); + inspector_write(socket, message.c_str(), message.length()); + } + } } } @@ -518,49 +504,70 @@ void AgentImpl::WorkerRunIO() { uv_run(&child_loop_, UV_RUN_DEFAULT); } +void AgentImpl::AppendMessage(MessageQueue* queue, int session_id, + const String16& message) { + Mutex::ScopedLock scoped_lock(queue_lock_); + queue->push_back(std::make_pair(session_id, message)); +} + +void AgentImpl::SwapBehindLock(MessageQueue* vector1, MessageQueue* vector2) { + Mutex::ScopedLock scoped_lock(queue_lock_); + vector1->swap(*vector2); +} + +void AgentImpl::PostIncomingMessage(const String16& message) { + AppendMessage(&incoming_message_queue_, frontend_session_id_, message); + v8::Isolate* isolate = parent_env_->isolate(); + platform_->CallOnForegroundThread(isolate, + new DispatchOnInspectorBackendTask(this)); + isolate->RequestInterrupt(InterruptCallback, this); + uv_async_send(&data_written_); +} + void AgentImpl::OnInspectorConnectionIO(inspector_socket_t* socket) { if (client_socket_) { DisconnectAndDisposeIO(socket); return; } client_socket_ = socket; - inspector_read_start(socket, OnBufferAlloc, AgentImpl::OnRemoteDataIO); - platform_->CallOnForegroundThread(parent_env_->isolate(), - new SetConnectedTask(this, true)); + inspector_read_start(socket, OnBufferAlloc, DataCallback); + frontend_session_id_++; + PostIncomingMessage(String16(TAG_CONNECT, sizeof(TAG_CONNECT) - 1)); } -void AgentImpl::PostMessages() { +void AgentImpl::DispatchMessages() { if (dispatching_messages_) return; dispatching_messages_ = true; - std::vector messages; - SwapBehindLock(&AgentImpl::message_queue_, &messages); - for (auto const& message : messages) - inspector_->dispatchMessageFromFrontend( - String16::fromUTF8(message.c_str(), message.length())); + MessageQueue tasks; + SwapBehindLock(&incoming_message_queue_, &tasks); + for (const MessageQueue::value_type& pair : tasks) { + const String16& message = pair.second; + if (message == TAG_CONNECT) { + CHECK_EQ(false, connected_); + backend_session_id_++; + connected_ = true; + fprintf(stderr, "Debugger attached.\n"); + inspector_->connectFrontend(new ChannelImpl(this)); + } else if (message == TAG_DISCONNECT) { + CHECK(connected_); + connected_ = false; + if (!shutting_down_) + PrintDebuggerReadyMessage(port_); + inspector_->quitMessageLoopOnPause(); + inspector_->disconnectFrontend(); + } else { + inspector_->dispatchMessageFromFrontend(message); + } + } uv_async_send(&data_written_); dispatching_messages_ = false; } -void AgentImpl::SetConnected(bool connected) { - if (connected_ == connected) - return; - - connected_ = connected; - if (connected) { - fprintf(stderr, "Debugger attached.\n"); - inspector_->connectFrontend(new ChannelImpl(this)); - } else { - if (!shutting_down_) - PrintDebuggerReadyMessage(port_); - inspector_->quitMessageLoopOnPause(); - inspector_->disconnectFrontend(); - } -} - -void AgentImpl::Write(const std::string& message) { - PushPendingMessage(&outgoing_message_queue_, message); - ASSERT_EQ(0, uv_async_send(&io_thread_req_)); +void AgentImpl::Write(int session_id, const String16& message) { + AppendMessage(&outgoing_message_queue_, session_id, message); + int err = uv_async_send(&io_thread_req_); + CHECK_EQ(0, err); } // Exported class Agent From ccd498359b608a9c3b86da099e983fd6d3f84588 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 12 Jul 2016 12:17:28 -0400 Subject: [PATCH 08/34] test: add common.rootDir A few of the child process tests can be simplified by computing the OS specific root directory in common and then accessing that value. PR-URL: https://github.com/nodejs/node/pull/7685 Reviewed-By: Roman Reiss --- test/common.js | 1 + test/parallel/test-child-process-cwd.js | 3 +-- test/parallel/test-child-process-spawnsync.js | 2 +- test/sequential/test-child-process-execsync.js | 17 +++++------------ 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/test/common.js b/test/common.js index 5aefdc3bcee5f1..f9d80ff1490e42 100644 --- a/test/common.js +++ b/test/common.js @@ -27,6 +27,7 @@ exports.isSunOS = process.platform === 'sunos'; exports.isFreeBSD = process.platform === 'freebsd'; exports.enoughTestMem = os.totalmem() > 0x20000000; /* 512MB */ +exports.rootDir = exports.isWindows ? 'c:\\' : '/'; function rimrafSync(p) { try { diff --git a/test/parallel/test-child-process-cwd.js b/test/parallel/test-child-process-cwd.js index f13da684fbdfe4..108538629e7060 100644 --- a/test/parallel/test-child-process-cwd.js +++ b/test/parallel/test-child-process-cwd.js @@ -36,12 +36,11 @@ function testCwd(options, forCode, forData) { } // Assume these exist, and 'pwd' gives us the right directory back +testCwd({cwd: common.rootDir}, 0, common.rootDir); if (common.isWindows) { testCwd({cwd: process.env.windir}, 0, process.env.windir); - testCwd({cwd: 'c:\\'}, 0, 'c:\\'); } else { testCwd({cwd: '/dev'}, 0, '/dev'); - testCwd({cwd: '/'}, 0, '/'); } // Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT diff --git a/test/parallel/test-child-process-spawnsync.js b/test/parallel/test-child-process-spawnsync.js index d45cc1e0dcea7a..77d205f79a414e 100644 --- a/test/parallel/test-child-process-spawnsync.js +++ b/test/parallel/test-child-process-spawnsync.js @@ -20,7 +20,7 @@ assert.deepStrictEqual(ret_err.spawnargs, ['bar']); { // Test the cwd option - const cwd = common.isWindows ? 'c:\\' : '/'; + const cwd = common.rootDir; const response = common.spawnSyncPwd({cwd}); assert.strictEqual(response.stdout.toString().trim(), cwd); diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index fcb923a38fcfd0..2fad4ba8c205b7 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -61,20 +61,13 @@ assert.strictEqual(ret, msg + '\n', 'execFileSync encoding result should match'); // Verify that the cwd option works - GH #7824 -(function() { - var response; - var cwd; - - if (common.isWindows) { - cwd = 'c:\\'; - response = execSync('echo %cd%', {cwd: cwd}); - } else { - cwd = '/'; - response = execSync('pwd', {cwd: cwd}); - } +{ + const cwd = common.rootDir; + const cmd = common.isWindows ? 'echo %cd%' : 'pwd'; + const response = execSync(cmd, {cwd}); assert.strictEqual(response.toString().trim(), cwd); -})(); +} // Verify that stderr is not accessed when stdio = 'ignore' - GH #7966 (function() { From f00346500a82244dc02ec51a145bd93893f52900 Mon Sep 17 00:00:00 2001 From: Claudio Rodriguez Date: Fri, 1 Jul 2016 09:33:20 +0100 Subject: [PATCH 09/34] fs: rename event to eventType in fs.watch listener The name 'event' for the argument of the listener in fs.watch was confusing considering FSWatcher also had events. This changes the name of the argument to eventType. Fixes: https://github.com/nodejs/node/issues/7504 PR-URL: https://github.com/nodejs/node/pull/7506 Reviewed-By: Rich Trott Reviewed-By: Sakthipriyan Vairamani --- doc/api/fs.md | 21 +++++++++++++++------ lib/fs.js | 4 ++-- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/doc/api/fs.md b/doc/api/fs.md index bd975732c67987..74da659dbf6625 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -109,14 +109,19 @@ non-UTF-8 encoded Buffers to `fs` functions will not work as expected. added: v0.5.8 --> -Objects returned from `fs.watch()` are of this type. +Objects returned from [`fs.watch()`][] are of this type. + +The `listener` callback provided to `fs.watch()` receives the returned FSWatcher's +`change` events. + +The object itself emits these events: ### Event: 'change' -* `event` {String} The type of fs change +* `eventType` {String} The type of fs change * `filename` {String | Buffer} The filename that changed (if relevant/available) Emitted when something changes in a watched directory or file. @@ -128,7 +133,8 @@ support. If `filename` is provided, it will be provided as a `Buffer` if `filename` will be a string. ```js -fs.watch('./tmp', {encoding: 'buffer'}, (event, filename) => { +// Example when handled through fs.watch listener +fs.watch('./tmp', {encoding: 'buffer'}, (eventType, filename) => { if (filename) console.log(filename); // Prints: @@ -1443,10 +1449,13 @@ directory. The returned object is a [`fs.FSWatcher`][]. The second argument is optional. If `options` is provided as a string, it specifies the `encoding`. Otherwise `options` should be passed as an object. -The listener callback gets two arguments `(event, filename)`. `event` is either +The listener callback gets two arguments `(eventType, filename)`. `eventType` is either `'rename'` or `'change'`, and `filename` is the name of the file which triggered the event. +Please note the listener callback is attached to the `'change'` event +fired by [`fs.FSWatcher`][], but they are not the same thing. + ### Caveats @@ -1499,8 +1508,8 @@ be provided. Therefore, don't assume that `filename` argument is always provided in the callback, and have some fallback logic if it is null. ```js -fs.watch('somedir', (event, filename) => { - console.log(`event is: ${event}`); +fs.watch('somedir', (eventType, filename) => { + console.log(`event type is: ${eventType}`); if (filename) { console.log(`filename provided: ${filename}`); } else { diff --git a/lib/fs.js b/lib/fs.js index 39bb3777bf9035..e3bfdabe885734 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1399,7 +1399,7 @@ function FSWatcher() { this._handle = new FSEvent(); this._handle.owner = this; - this._handle.onchange = function(status, event, filename) { + this._handle.onchange = function(status, eventType, filename) { if (status < 0) { self._handle.close(); const error = !filename ? @@ -1409,7 +1409,7 @@ function FSWatcher() { error.filename = filename; self.emit('error', error); } else { - self.emit('change', event, filename); + self.emit('change', eventType, filename); } }; } From 1af8c03c99de9e441d6289bee20e6acc918d6988 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 12 Jul 2016 19:47:32 -0400 Subject: [PATCH 10/34] test: cleanup IIFE tests A number of test files use IIFEs to separate distinct tests from each other in the same file. The project has been moving toward using block scopes and let/const in favor of IIFEs. This commit moves IIFE tests to block scopes. Some additional cleanup such as use of strictEqual() and common.mustCall() is also included. PR-URL: https://github.com/nodejs/node/pull/7694 Reviewed-By: Santiago Gimeno --- test/gc/test-net-timeout.js | 22 +- test/parallel/test-buffer-alloc.js | 84 ++--- test/parallel/test-buffer.js | 88 ++--- test/parallel/test-child-process-cwd.js | 15 +- test/parallel/test-crypto-authenticated.js | 78 ++-- test/parallel/test-crypto-binary-default.js | 36 +- test/parallel/test-crypto-cipher-decipher.js | 30 +- test/parallel/test-crypto-dh.js | 12 +- test/parallel/test-crypto-from-binary.js | 20 +- test/parallel/test-crypto-rsa-dsa.js | 60 ++-- test/parallel/test-fs-mkdir.js | 40 +-- test/parallel/test-fs-truncate-GH-6233.js | 18 +- test/parallel/test-fs-write-stream-end.js | 20 +- test/parallel/test-fs-write-stream.js | 13 +- test/parallel/test-http-1.0.js | 90 ++--- test/parallel/test-http-parser.js | 340 +++++++++--------- test/parallel/test-querystring.js | 8 +- test/parallel/test-require-cache.js | 18 +- .../test-stream-pipe-error-handling.js | 88 ++--- test/parallel/test-stream-readable-event.js | 78 +--- .../test-stream-writable-decoded-encoding.js | 22 +- .../test-stream2-pipe-error-handling.js | 36 +- test/parallel/test-stringbytes-external.js | 70 ++-- test/parallel/test-timers-unref.js | 6 +- test/parallel/test-timers-zero-timeout.js | 39 +- test/parallel/test-tls-connect.js | 25 +- test/parallel/test-util-format.js | 6 +- test/parallel/test-vm-debug-context.js | 12 +- test/parallel/test-zlib-dictionary-fail.js | 12 +- test/pummel/test-https-ci-reneg-attack.js | 6 +- test/pummel/test-net-connect-memleak.js | 7 +- test/pummel/test-tls-ci-reneg-attack.js | 6 +- test/pummel/test-tls-connect-memleak.js | 10 +- .../sequential/test-child-process-execsync.js | 4 +- 34 files changed, 667 insertions(+), 752 deletions(-) diff --git a/test/gc/test-net-timeout.js b/test/gc/test-net-timeout.js index ff1d5656ce9bcf..2645ccc5038d91 100644 --- a/test/gc/test-net-timeout.js +++ b/test/gc/test-net-timeout.js @@ -35,19 +35,16 @@ function getall() { if (count >= todo) return; - (function() { - var req = net.connect(server.address().port, server.address().address); - req.resume(); - req.setTimeout(10, function() { - //console.log('timeout (expected)') - req.destroy(); - done++; - global.gc(); - }); + const req = net.connect(server.address().port, server.address().address); + req.resume(); + req.setTimeout(10, function() { + req.destroy(); + done++; + global.gc(); + }); - count++; - weak(req, afterGC); - })(); + count++; + weak(req, afterGC); setImmediate(getall); } @@ -76,4 +73,3 @@ function status() { }, 200); } } - diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index 0f06393d6a5aaa..c06c1107039cb2 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -1029,28 +1029,28 @@ Buffer.from(Buffer.allocUnsafe(0), 0, 0); // GH-5110 -(function() { +{ const buffer = Buffer.from('test'); const string = JSON.stringify(buffer); - assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); + assert.strictEqual(string, '{"type":"Buffer","data":[116,101,115,116]}'); assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) { return value && value.type === 'Buffer' ? Buffer.from(value.data) : value; })); -})(); +} // issue GH-7849 -(function() { - var buf = Buffer.from('test'); - var json = JSON.stringify(buf); - var obj = JSON.parse(json); - var copy = Buffer.from(obj); +{ + const buf = Buffer.from('test'); + const json = JSON.stringify(buf); + const obj = JSON.parse(json); + const copy = Buffer.from(obj); assert(buf.equals(copy)); -})(); +} // issue GH-4331 assert.throws(function() { @@ -1156,30 +1156,30 @@ assert.throws(function() { }); // test for common read(U)IntLE/BE -(function() { +{ var buf = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); - assert.equal(buf.readUIntLE(0, 1), 0x01); - assert.equal(buf.readUIntBE(0, 1), 0x01); - assert.equal(buf.readUIntLE(0, 3), 0x030201); - assert.equal(buf.readUIntBE(0, 3), 0x010203); - assert.equal(buf.readUIntLE(0, 5), 0x0504030201); - assert.equal(buf.readUIntBE(0, 5), 0x0102030405); - assert.equal(buf.readUIntLE(0, 6), 0x060504030201); - assert.equal(buf.readUIntBE(0, 6), 0x010203040506); - assert.equal(buf.readIntLE(0, 1), 0x01); - assert.equal(buf.readIntBE(0, 1), 0x01); - assert.equal(buf.readIntLE(0, 3), 0x030201); - assert.equal(buf.readIntBE(0, 3), 0x010203); - assert.equal(buf.readIntLE(0, 5), 0x0504030201); - assert.equal(buf.readIntBE(0, 5), 0x0102030405); - assert.equal(buf.readIntLE(0, 6), 0x060504030201); - assert.equal(buf.readIntBE(0, 6), 0x010203040506); -})(); + assert.strictEqual(buf.readUIntLE(0, 1), 0x01); + assert.strictEqual(buf.readUIntBE(0, 1), 0x01); + assert.strictEqual(buf.readUIntLE(0, 3), 0x030201); + assert.strictEqual(buf.readUIntBE(0, 3), 0x010203); + assert.strictEqual(buf.readUIntLE(0, 5), 0x0504030201); + assert.strictEqual(buf.readUIntBE(0, 5), 0x0102030405); + assert.strictEqual(buf.readUIntLE(0, 6), 0x060504030201); + assert.strictEqual(buf.readUIntBE(0, 6), 0x010203040506); + assert.strictEqual(buf.readIntLE(0, 1), 0x01); + assert.strictEqual(buf.readIntBE(0, 1), 0x01); + assert.strictEqual(buf.readIntLE(0, 3), 0x030201); + assert.strictEqual(buf.readIntBE(0, 3), 0x010203); + assert.strictEqual(buf.readIntLE(0, 5), 0x0504030201); + assert.strictEqual(buf.readIntBE(0, 5), 0x0102030405); + assert.strictEqual(buf.readIntLE(0, 6), 0x060504030201); + assert.strictEqual(buf.readIntBE(0, 6), 0x010203040506); +} // test for common write(U)IntLE/BE -(function() { - var buf = Buffer.allocUnsafe(3); +{ + let buf = Buffer.allocUnsafe(3); buf.writeUIntLE(0x123456, 0, 3); assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.equal(buf.readUIntLE(0, 3), 0x123456); @@ -1268,11 +1268,11 @@ assert.throws(function() { buf.writeIntBE(-0x0012000000, 0, 5); assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]); assert.equal(buf.readIntBE(0, 5), -0x0012000000); -})(); +} // test Buffer slice -(function() { - var buf = Buffer.from('0123456789'); +{ + const buf = Buffer.from('0123456789'); assert.equal(buf.slice(-10, 10), '0123456789'); assert.equal(buf.slice(-20, 10), '0123456789'); assert.equal(buf.slice(-20, -10), ''); @@ -1305,7 +1305,7 @@ assert.throws(function() { assert.equal(buf.slice(0, -i), s.slice(0, -i)); } - var utf16Buf = Buffer.from('0123456789', 'utf16le'); + const utf16Buf = Buffer.from('0123456789', 'utf16le'); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le')); assert.equal(buf.slice('0', '1'), '0'); @@ -1319,7 +1319,7 @@ assert.throws(function() { // try to slice a zero length Buffer // see https://github.com/joyent/node/issues/5881 Buffer.alloc(0).slice(0, 1); -})(); +} // Regression test for #5482: should throw but not assert in C++ land. assert.throws(function() { @@ -1328,20 +1328,20 @@ assert.throws(function() { // Regression test for #6111. Constructing a buffer from another buffer // should a) work, and b) not corrupt the source buffer. -(function() { - var a = [0]; +{ + let a = [0]; for (let i = 0; i < 7; ++i) a = a.concat(a); a = a.map(function(_, i) { return i; }); const b = Buffer.from(a); const c = Buffer.from(b); - assert.equal(b.length, a.length); - assert.equal(c.length, a.length); + assert.strictEqual(b.length, a.length); + assert.strictEqual(c.length, a.length); for (let i = 0, k = a.length; i < k; ++i) { - assert.equal(a[i], i); - assert.equal(b[i], i); - assert.equal(c[i], i); + assert.strictEqual(a[i], i); + assert.strictEqual(b[i], i); + assert.strictEqual(c[i], i); } -})(); +} assert.throws(function() { diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index 02f94436968c30..a007a1088b3e70 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -1031,28 +1031,28 @@ Buffer(Buffer(0), 0, 0); // GH-5110 -(function() { +{ const buffer = new Buffer('test'); const string = JSON.stringify(buffer); - assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); + assert.strictEqual(string, '{"type":"Buffer","data":[116,101,115,116]}'); assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) { return value && value.type === 'Buffer' ? new Buffer(value.data) : value; })); -})(); +} // issue GH-7849 -(function() { - var buf = new Buffer('test'); - var json = JSON.stringify(buf); - var obj = JSON.parse(json); - var copy = new Buffer(obj); +{ + const buf = new Buffer('test'); + const json = JSON.stringify(buf); + const obj = JSON.parse(json); + const copy = new Buffer(obj); assert(buf.equals(copy)); -})(); +} // issue GH-4331 assert.throws(function() { @@ -1168,30 +1168,30 @@ assert.throws(function() { }); // test for common read(U)IntLE/BE -(function() { - var buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); - - assert.equal(buf.readUIntLE(0, 1), 0x01); - assert.equal(buf.readUIntBE(0, 1), 0x01); - assert.equal(buf.readUIntLE(0, 3), 0x030201); - assert.equal(buf.readUIntBE(0, 3), 0x010203); - assert.equal(buf.readUIntLE(0, 5), 0x0504030201); - assert.equal(buf.readUIntBE(0, 5), 0x0102030405); - assert.equal(buf.readUIntLE(0, 6), 0x060504030201); - assert.equal(buf.readUIntBE(0, 6), 0x010203040506); - assert.equal(buf.readIntLE(0, 1), 0x01); - assert.equal(buf.readIntBE(0, 1), 0x01); - assert.equal(buf.readIntLE(0, 3), 0x030201); - assert.equal(buf.readIntBE(0, 3), 0x010203); - assert.equal(buf.readIntLE(0, 5), 0x0504030201); - assert.equal(buf.readIntBE(0, 5), 0x0102030405); - assert.equal(buf.readIntLE(0, 6), 0x060504030201); - assert.equal(buf.readIntBE(0, 6), 0x010203040506); -})(); +{ + const buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); + + assert.strictEqual(buf.readUIntLE(0, 1), 0x01); + assert.strictEqual(buf.readUIntBE(0, 1), 0x01); + assert.strictEqual(buf.readUIntLE(0, 3), 0x030201); + assert.strictEqual(buf.readUIntBE(0, 3), 0x010203); + assert.strictEqual(buf.readUIntLE(0, 5), 0x0504030201); + assert.strictEqual(buf.readUIntBE(0, 5), 0x0102030405); + assert.strictEqual(buf.readUIntLE(0, 6), 0x060504030201); + assert.strictEqual(buf.readUIntBE(0, 6), 0x010203040506); + assert.strictEqual(buf.readIntLE(0, 1), 0x01); + assert.strictEqual(buf.readIntBE(0, 1), 0x01); + assert.strictEqual(buf.readIntLE(0, 3), 0x030201); + assert.strictEqual(buf.readIntBE(0, 3), 0x010203); + assert.strictEqual(buf.readIntLE(0, 5), 0x0504030201); + assert.strictEqual(buf.readIntBE(0, 5), 0x0102030405); + assert.strictEqual(buf.readIntLE(0, 6), 0x060504030201); + assert.strictEqual(buf.readIntBE(0, 6), 0x010203040506); +} // test for common write(U)IntLE/BE -(function() { - var buf = Buffer(3); +{ + let buf = Buffer(3); buf.writeUIntLE(0x123456, 0, 3); assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.equal(buf.readUIntLE(0, 3), 0x123456); @@ -1280,11 +1280,11 @@ assert.throws(function() { buf.writeIntBE(-0x0012000000, 0, 5); assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]); assert.equal(buf.readIntBE(0, 5), -0x0012000000); -})(); +} // test Buffer slice -(function() { - var buf = new Buffer('0123456789'); +{ + const buf = new Buffer('0123456789'); assert.equal(buf.slice(-10, 10), '0123456789'); assert.equal(buf.slice(-20, 10), '0123456789'); assert.equal(buf.slice(-20, -10), ''); @@ -1317,7 +1317,7 @@ assert.throws(function() { assert.equal(buf.slice(0, -i), s.slice(0, -i)); } - var utf16Buf = new Buffer('0123456789', 'utf16le'); + const utf16Buf = new Buffer('0123456789', 'utf16le'); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer('012', 'utf16le')); assert.equal(buf.slice('0', '1'), '0'); @@ -1331,7 +1331,7 @@ assert.throws(function() { // try to slice a zero length Buffer // see https://github.com/joyent/node/issues/5881 SlowBuffer(0).slice(0, 1); -})(); +} // Regression test for #5482: should throw but not assert in C++ land. assert.throws(function() { @@ -1340,20 +1340,20 @@ assert.throws(function() { // Regression test for #6111. Constructing a buffer from another buffer // should a) work, and b) not corrupt the source buffer. -(function() { - var a = [0]; +{ + let a = [0]; for (let i = 0; i < 7; ++i) a = a.concat(a); a = a.map(function(_, i) { return i; }); const b = Buffer(a); const c = Buffer(b); - assert.equal(b.length, a.length); - assert.equal(c.length, a.length); + assert.strictEqual(b.length, a.length); + assert.strictEqual(c.length, a.length); for (let i = 0, k = a.length; i < k; ++i) { - assert.equal(a[i], i); - assert.equal(b[i], i); - assert.equal(c[i], i); + assert.strictEqual(a[i], i); + assert.strictEqual(b[i], i); + assert.strictEqual(c[i], i); } -})(); +} assert.throws(function() { diff --git a/test/parallel/test-child-process-cwd.js b/test/parallel/test-child-process-cwd.js index 108538629e7060..acba57939f0afe 100644 --- a/test/parallel/test-child-process-cwd.js +++ b/test/parallel/test-child-process-cwd.js @@ -44,18 +44,11 @@ if (common.isWindows) { } // Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT -(function() { - var errors = 0; - - testCwd({cwd: 'does-not-exist'}, -1).on('error', function(e) { +{ + testCwd({cwd: 'does-not-exist'}, -1).on('error', common.mustCall(function(e) { assert.equal(e.code, 'ENOENT'); - errors++; - }); - - process.on('exit', function() { - assert.equal(errors, 1); - }); -})(); + })); +} // Spawn() shouldn't try to chdir() so this should just work testCwd(undefined, 0); diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index f1b92f8a19dafc..331c2d20e0a441 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -322,34 +322,34 @@ for (var i in TEST_CASES) { continue; } - (function() { - var encrypt = crypto.createCipheriv(test.algo, + { + const encrypt = crypto.createCipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); if (test.aad) encrypt.setAAD(Buffer.from(test.aad, 'hex')); - var inputEncoding = test.plainIsHex ? 'hex' : 'ascii'; - var hex = encrypt.update(test.plain, inputEncoding, 'hex'); + const inputEncoding = test.plainIsHex ? 'hex' : 'ascii'; + let hex = encrypt.update(test.plain, inputEncoding, 'hex'); hex += encrypt.final('hex'); - var auth_tag = encrypt.getAuthTag(); + const auth_tag = encrypt.getAuthTag(); // only test basic encryption run if output is marked as tampered. if (!test.tampered) { - assert.equal(hex, test.ct); - assert.equal(auth_tag.toString('hex'), test.tag); + assert.strictEqual(hex, test.ct); + assert.strictEqual(auth_tag.toString('hex'), test.tag); } - })(); + } - (function() { - var decrypt = crypto.createDecipheriv(test.algo, + { + const decrypt = crypto.createDecipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); if (test.aad) decrypt.setAAD(Buffer.from(test.aad, 'hex')); - var outputEncoding = test.plainIsHex ? 'hex' : 'ascii'; + const outputEncoding = test.plainIsHex ? 'hex' : 'ascii'; - var msg = decrypt.update(test.ct, 'hex', outputEncoding); + let msg = decrypt.update(test.ct, 'hex', outputEncoding); if (!test.tampered) { msg += decrypt.final(outputEncoding); assert.equal(msg, test.plain); @@ -357,48 +357,48 @@ for (var i in TEST_CASES) { // assert that final throws if input data could not be verified! assert.throws(function() { decrypt.final('ascii'); }, / auth/); } - })(); + } - (function() { + { if (!test.password) return; if (common.hasFipsCrypto) { assert.throws(() => { crypto.createCipher(test.algo, test.password); }, /not supported in FIPS mode/); } else { - var encrypt = crypto.createCipher(test.algo, test.password); + const encrypt = crypto.createCipher(test.algo, test.password); if (test.aad) encrypt.setAAD(Buffer.from(test.aad, 'hex')); - var hex = encrypt.update(test.plain, 'ascii', 'hex'); + let hex = encrypt.update(test.plain, 'ascii', 'hex'); hex += encrypt.final('hex'); - var auth_tag = encrypt.getAuthTag(); + const auth_tag = encrypt.getAuthTag(); // only test basic encryption run if output is marked as tampered. if (!test.tampered) { - assert.equal(hex, test.ct); - assert.equal(auth_tag.toString('hex'), test.tag); + assert.strictEqual(hex, test.ct); + assert.strictEqual(auth_tag.toString('hex'), test.tag); } } - })(); + } - (function() { + { if (!test.password) return; if (common.hasFipsCrypto) { assert.throws(() => { crypto.createDecipher(test.algo, test.password); }, /not supported in FIPS mode/); } else { - var decrypt = crypto.createDecipher(test.algo, test.password); + const decrypt = crypto.createDecipher(test.algo, test.password); decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); if (test.aad) decrypt.setAAD(Buffer.from(test.aad, 'hex')); - var msg = decrypt.update(test.ct, 'hex', 'ascii'); + let msg = decrypt.update(test.ct, 'hex', 'ascii'); if (!test.tampered) { msg += decrypt.final('ascii'); - assert.equal(msg, test.plain); + assert.strictEqual(msg, test.plain); } else { // assert that final throws if input data could not be verified! assert.throws(function() { decrypt.final('ascii'); }, / auth/); } } - })(); + } // after normal operation, test some incorrect ways of calling the API: // it's most certainly enough to run these tests with one algorithm only. @@ -407,41 +407,41 @@ for (var i in TEST_CASES) { continue; } - (function() { + { // non-authenticating mode: - var encrypt = crypto.createCipheriv('aes-128-cbc', + const encrypt = crypto.createCipheriv('aes-128-cbc', 'ipxp9a6i1Mb4USb4', '6fKjEjR3Vl30EUYC'); encrypt.update('blah', 'ascii'); encrypt.final(); assert.throws(() => { encrypt.getAuthTag(); }, / state/); assert.throws(() => { encrypt.setAAD(Buffer.from('123', 'ascii')); }, / state/); - })(); + } - (function() { + { // trying to get tag before inputting all data: - var encrypt = crypto.createCipheriv(test.algo, + const encrypt = crypto.createCipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); encrypt.update('blah', 'ascii'); assert.throws(function() { encrypt.getAuthTag(); }, / state/); - })(); + } - (function() { + { // trying to set tag on encryption object: - var encrypt = crypto.createCipheriv(test.algo, + const encrypt = crypto.createCipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, / state/); - })(); + } - (function() { + { // trying to read tag from decryption object: - var decrypt = crypto.createDecipheriv(test.algo, + const decrypt = crypto.createDecipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); assert.throws(function() { decrypt.getAuthTag(); }, / state/); - })(); + } - (function() { + { // trying to create cipher with incorrect IV length assert.throws(function() { crypto.createCipheriv( @@ -450,5 +450,5 @@ for (var i in TEST_CASES) { Buffer.alloc(0) ); }, /Invalid IV length/); - })(); + } } diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index 74447ce69d2ee9..2386ff1c24b5b4 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -580,58 +580,58 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); // // Test RSA signing and verification // -(function() { - var privateKey = fs.readFileSync( +{ + const privateKey = fs.readFileSync( common.fixturesDir + '/test_rsa_privkey_2.pem'); - var publicKey = fs.readFileSync( + const publicKey = fs.readFileSync( common.fixturesDir + '/test_rsa_pubkey_2.pem'); - var input = 'I AM THE WALRUS'; + const input = 'I AM THE WALRUS'; - var signature = + const signature = '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '0ddfb299bedeb1ad'; - var sign = crypto.createSign('RSA-SHA256'); + const sign = crypto.createSign('RSA-SHA256'); sign.update(input); - var output = sign.sign(privateKey, 'hex'); - assert.equal(output, signature); + const output = sign.sign(privateKey, 'hex'); + assert.strictEqual(output, signature); - var verify = crypto.createVerify('RSA-SHA256'); + const verify = crypto.createVerify('RSA-SHA256'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); -})(); +} // // Test DSA signing and verification // -(function() { - var privateKey = fs.readFileSync( +{ + const privateKey = fs.readFileSync( common.fixturesDir + '/test_dsa_privkey.pem'); - var publicKey = fs.readFileSync( + const publicKey = fs.readFileSync( common.fixturesDir + '/test_dsa_pubkey.pem'); - var input = 'I AM THE WALRUS'; + const input = 'I AM THE WALRUS'; // DSA signatures vary across runs so there is no static string to verify // against - var sign = crypto.createSign('DSS1'); + const sign = crypto.createSign('DSS1'); sign.update(input); - var signature = sign.sign(privateKey, 'hex'); + const signature = sign.sign(privateKey, 'hex'); - var verify = crypto.createVerify('DSS1'); + const verify = crypto.createVerify('DSS1'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); -})(); +} // diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js index eef329b5f35384..8c9daa16e875f3 100644 --- a/test/parallel/test-crypto-cipher-decipher.js +++ b/test/parallel/test-crypto-cipher-decipher.js @@ -73,35 +73,35 @@ testCipher2('0123456789abcdef'); testCipher2(Buffer.from('0123456789abcdef')); // Base64 padding regression test, see #4837. -(function() { - var c = crypto.createCipher('aes-256-cbc', 'secret'); - var s = c.update('test', 'utf8', 'base64') + c.final('base64'); - assert.equal(s, '375oxUQCIocvxmC5At+rvA=='); -})(); +{ + const c = crypto.createCipher('aes-256-cbc', 'secret'); + const s = c.update('test', 'utf8', 'base64') + c.final('base64'); + assert.strictEqual(s, '375oxUQCIocvxmC5At+rvA=='); +} // Calling Cipher.final() or Decipher.final() twice should error but // not assert. See #4886. -(function() { - var c = crypto.createCipher('aes-256-cbc', 'secret'); +{ + const c = crypto.createCipher('aes-256-cbc', 'secret'); try { c.final('xxx'); } catch (e) { /* Ignore. */ } try { c.final('xxx'); } catch (e) { /* Ignore. */ } try { c.final('xxx'); } catch (e) { /* Ignore. */ } - var d = crypto.createDecipher('aes-256-cbc', 'secret'); + const d = crypto.createDecipher('aes-256-cbc', 'secret'); try { d.final('xxx'); } catch (e) { /* Ignore. */ } try { d.final('xxx'); } catch (e) { /* Ignore. */ } try { d.final('xxx'); } catch (e) { /* Ignore. */ } -})(); +} // Regression test for #5482: string to Cipher#update() should not assert. -(function() { - var c = crypto.createCipher('aes192', '0123456789abcdef'); +{ + const c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update'); c.final(); -})(); +} // #5655 regression tests, 'utf-8' and 'utf8' are identical. -(function() { - var c = crypto.createCipher('aes192', '0123456789abcdef'); +{ + let c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update', ''); // Defaults to "utf8". c.final('utf-8'); // Should not throw. @@ -112,4 +112,4 @@ testCipher2(Buffer.from('0123456789abcdef')); c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update', 'utf-8'); c.final('utf8'); // Should not throw. -})(); +} diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index e9fbd30a2effc8..17ee6134c6124b 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -57,19 +57,19 @@ var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); assert.equal(secret1, secret3); // Run this one twice to make sure that the dh3 clears its error properly -(function() { - var c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); +{ + const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); assert.throws(function() { c.final('utf8'); }, /wrong final block length/); -})(); +} assert.throws(function() { dh3.computeSecret(''); }, /key is too small/i); -(function() { - var c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); +{ + const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); assert.throws(function() { c.final('utf8'); }, /wrong final block length/); -})(); +} // Create a shared using a DH group. var alice = crypto.createDiffieHellmanGroup('modp5'); diff --git a/test/parallel/test-crypto-from-binary.js b/test/parallel/test-crypto-from-binary.js index 5c7e75a72104c5..0889541ef6e144 100644 --- a/test/parallel/test-crypto-from-binary.js +++ b/test/parallel/test-crypto-from-binary.js @@ -29,18 +29,18 @@ var b = Buffer.from(ucs2_control + ucs2_control, 'ucs2'); // // Test updating from birant data // -(function() { - var datum1 = b.slice(700000); - var hash1_converted = crypto.createHash('sha1') +{ + const datum1 = b.slice(700000); + const hash1_converted = crypto.createHash('sha1') .update(datum1.toString('base64'), 'base64') .digest('hex'); - var hash1_direct = crypto.createHash('sha1').update(datum1).digest('hex'); - assert.equal(hash1_direct, hash1_converted, 'should hash the same.'); + const hash1_direct = crypto.createHash('sha1').update(datum1).digest('hex'); + assert.strictEqual(hash1_direct, hash1_converted, 'should hash the same.'); - var datum2 = b; - var hash2_converted = crypto.createHash('sha1') + const datum2 = b; + const hash2_converted = crypto.createHash('sha1') .update(datum2.toString('base64'), 'base64') .digest('hex'); - var hash2_direct = crypto.createHash('sha1').update(datum2).digest('hex'); - assert.equal(hash2_direct, hash2_converted, 'should hash the same.'); -})(); + const hash2_direct = crypto.createHash('sha1').update(datum2).digest('hex'); + assert.strictEqual(hash2_direct, hash2_converted, 'should hash the same.'); +} diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 2e29cd723d2677..a05102320caa7c 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -27,20 +27,20 @@ var dsaKeyPemEncrypted = fs.readFileSync( common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii'); // Test RSA encryption/decryption -(function() { - var input = 'I AM THE WALRUS'; - var bufferToEncrypt = Buffer.from(input); +{ + const input = 'I AM THE WALRUS'; + const bufferToEncrypt = Buffer.from(input); - var encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); + let encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); - var decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); + let decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer); + assert.strictEqual(input, decryptedBuffer.toString()); - var decryptedBufferWithPassword = crypto.privateDecrypt({ + let decryptedBufferWithPassword = crypto.privateDecrypt({ key: rsaKeyPemEncrypted, passphrase: 'password' }, encryptedBuffer); - assert.equal(input, decryptedBufferWithPassword.toString()); + assert.strictEqual(input, decryptedBufferWithPassword.toString()); encryptedBuffer = crypto.publicEncrypt({ key: rsaKeyPemEncrypted, @@ -51,7 +51,7 @@ var dsaKeyPemEncrypted = fs.readFileSync( key: rsaKeyPemEncrypted, passphrase: 'password' }, encryptedBuffer); - assert.equal(input, decryptedBufferWithPassword.toString()); + assert.strictEqual(input, decryptedBufferWithPassword.toString()); encryptedBuffer = crypto.privateEncrypt({ key: rsaKeyPemEncrypted, @@ -62,22 +62,22 @@ var dsaKeyPemEncrypted = fs.readFileSync( key: rsaKeyPemEncrypted, passphrase: Buffer.from('password') }, encryptedBuffer); - assert.equal(input, decryptedBufferWithPassword.toString()); + assert.strictEqual(input, decryptedBufferWithPassword.toString()); encryptedBuffer = crypto.publicEncrypt(certPem, bufferToEncrypt); decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); + assert.strictEqual(input, decryptedBuffer.toString()); encryptedBuffer = crypto.publicEncrypt(keyPem, bufferToEncrypt); decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); + assert.strictEqual(input, decryptedBuffer.toString()); encryptedBuffer = crypto.privateEncrypt(keyPem, bufferToEncrypt); decryptedBuffer = crypto.publicDecrypt(keyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); + assert.strictEqual(input, decryptedBuffer.toString()); assert.throws(function() { crypto.privateDecrypt({ @@ -104,7 +104,7 @@ var dsaKeyPemEncrypted = fs.readFileSync( passphrase: [].concat.apply([], Buffer.from('password')) }, encryptedBuffer); }); -})(); +} function test_rsa(padding) { var input = Buffer.allocUnsafe(padding === 'RSA_NO_PADDING' ? 1024 / 8 : 32); @@ -176,52 +176,52 @@ assert.throws(function() { // // Test RSA signing and verification // -(function() { - var privateKey = fs.readFileSync( +{ + const privateKey = fs.readFileSync( common.fixturesDir + '/test_rsa_privkey_2.pem'); - var publicKey = fs.readFileSync( + const publicKey = fs.readFileSync( common.fixturesDir + '/test_rsa_pubkey_2.pem'); - var input = 'I AM THE WALRUS'; + const input = 'I AM THE WALRUS'; - var signature = + const signature = '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '0ddfb299bedeb1ad'; - var sign = crypto.createSign('RSA-SHA256'); + const sign = crypto.createSign('RSA-SHA256'); sign.update(input); - var output = sign.sign(privateKey, 'hex'); - assert.equal(output, signature); + const output = sign.sign(privateKey, 'hex'); + assert.strictEqual(output, signature); - var verify = crypto.createVerify('RSA-SHA256'); + const verify = crypto.createVerify('RSA-SHA256'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); -})(); +} // // Test DSA signing and verification // -(function() { - var input = 'I AM THE WALRUS'; +{ + const input = 'I AM THE WALRUS'; // DSA signatures vary across runs so there is no static string to verify // against - var sign = crypto.createSign('DSS1'); + const sign = crypto.createSign('DSS1'); sign.update(input); - var signature = sign.sign(dsaKeyPem, 'hex'); + const signature = sign.sign(dsaKeyPem, 'hex'); - var verify = crypto.createVerify('DSS1'); + const verify = crypto.createVerify('DSS1'); verify.update(input); assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); -})(); +} // diff --git a/test/parallel/test-fs-mkdir.js b/test/parallel/test-fs-mkdir.js index ae13b9bc7a071d..2b8e8b8f026637 100644 --- a/test/parallel/test-fs-mkdir.js +++ b/test/parallel/test-fs-mkdir.js @@ -12,53 +12,47 @@ function unlink(pathname) { common.refreshTmpDir(); -(function() { - var ncalls = 0; - var pathname = common.tmpDir + '/test1'; +{ + const pathname = common.tmpDir + '/test1'; unlink(pathname); - fs.mkdir(pathname, function(err) { - assert.equal(err, null); - assert.equal(common.fileExists(pathname), true); - ncalls++; - }); + fs.mkdir(pathname, common.mustCall(function(err) { + assert.strictEqual(err, null); + assert.strictEqual(common.fileExists(pathname), true); + })); process.on('exit', function() { unlink(pathname); - assert.equal(ncalls, 1); }); -})(); +} -(function() { - var ncalls = 0; - var pathname = common.tmpDir + '/test2'; +{ + const pathname = common.tmpDir + '/test2'; unlink(pathname); - fs.mkdir(pathname, 0o777, function(err) { + fs.mkdir(pathname, 0o777, common.mustCall(function(err) { assert.equal(err, null); assert.equal(common.fileExists(pathname), true); - ncalls++; - }); + })); process.on('exit', function() { unlink(pathname); - assert.equal(ncalls, 1); }); -})(); +} -(function() { - var pathname = common.tmpDir + '/test3'; +{ + const pathname = common.tmpDir + '/test3'; unlink(pathname); fs.mkdirSync(pathname); - var exists = common.fileExists(pathname); + const exists = common.fileExists(pathname); unlink(pathname); - assert.equal(exists, true); -})(); + assert.strictEqual(exists, true); +} // Keep the event loop alive so the async mkdir() requests // have a chance to run (since they don't ref the event loop). diff --git a/test/parallel/test-fs-truncate-GH-6233.js b/test/parallel/test-fs-truncate-GH-6233.js index 023d08b15101d7..acfdd1ccae1259 100644 --- a/test/parallel/test-fs-truncate-GH-6233.js +++ b/test/parallel/test-fs-truncate-GH-6233.js @@ -8,19 +8,19 @@ var filename = common.tmpDir + '/truncate-file.txt'; common.refreshTmpDir(); // Synchronous test. -(function() { +{ fs.writeFileSync(filename, '0123456789'); - assert.equal(fs.readFileSync(filename).toString(), '0123456789'); + assert.strictEqual(fs.readFileSync(filename).toString(), '0123456789'); fs.truncateSync(filename, 5); - assert.equal(fs.readFileSync(filename).toString(), '01234'); -})(); + assert.strictEqual(fs.readFileSync(filename).toString(), '01234'); +} // Asynchronous test. -(function() { +{ fs.writeFileSync(filename, '0123456789'); - assert.equal(fs.readFileSync(filename).toString(), '0123456789'); + assert.strictEqual(fs.readFileSync(filename).toString(), '0123456789'); fs.truncate(filename, 5, common.mustCall(function(err) { - if (err) throw err; - assert.equal(fs.readFileSync(filename).toString(), '01234'); + assert.ifError(err); + assert.strictEqual(fs.readFileSync(filename).toString(), '01234'); })); -})(); +} diff --git a/test/parallel/test-fs-write-stream-end.js b/test/parallel/test-fs-write-stream-end.js index a8af29d1327672..ade6777d5f68ac 100644 --- a/test/parallel/test-fs-write-stream-end.js +++ b/test/parallel/test-fs-write-stream-end.js @@ -6,19 +6,19 @@ var fs = require('fs'); common.refreshTmpDir(); -(function() { - var file = path.join(common.tmpDir, 'write-end-test0.txt'); - var stream = fs.createWriteStream(file); +{ + const file = path.join(common.tmpDir, 'write-end-test0.txt'); + const stream = fs.createWriteStream(file); stream.end(); stream.on('close', common.mustCall(function() { })); -})(); +} -(function() { - var file = path.join(common.tmpDir, 'write-end-test1.txt'); - var stream = fs.createWriteStream(file); +{ + const file = path.join(common.tmpDir, 'write-end-test1.txt'); + const stream = fs.createWriteStream(file); stream.end('a\n', 'utf8'); stream.on('close', common.mustCall(function() { - var content = fs.readFileSync(file, 'utf8'); - assert.equal(content, 'a\n'); + const content = fs.readFileSync(file, 'utf8'); + assert.strictEqual(content, 'a\n'); })); -})(); +} diff --git a/test/parallel/test-fs-write-stream.js b/test/parallel/test-fs-write-stream.js index 5d29e60545f434..71aaaa75dd5845 100644 --- a/test/parallel/test-fs-write-stream.js +++ b/test/parallel/test-fs-write-stream.js @@ -8,7 +8,7 @@ var file = path.join(common.tmpDir, 'write.txt'); common.refreshTmpDir(); -(function() { +{ const stream = fs.WriteStream(file); const _fs_close = fs.close; @@ -17,15 +17,14 @@ common.refreshTmpDir(); fs.close = _fs_close; }; stream.destroy(); -})(); +} -(function() { - var stream = fs.createWriteStream(file); +{ + const stream = fs.createWriteStream(file); stream.on('drain', function() { - assert.fail(null, null, '\'drain\' event must not be emitted before ' + + common.fail('\'drain\' event must not be emitted before ' + 'stream.write() has been called at least once.'); }); stream.destroy(); -})(); - +} diff --git a/test/parallel/test-http-1.0.js b/test/parallel/test-http-1.0.js index 622dd4a16f1516..d01613de45452d 100644 --- a/test/parallel/test-http-1.0.js +++ b/test/parallel/test-http-1.0.js @@ -35,11 +35,11 @@ function test(handler, request_generator, response_validator) { }); } -(function() { +{ function handler(req, res) { - assert.equal('1.0', req.httpVersion); - assert.equal(1, req.httpVersionMajor); - assert.equal(0, req.httpVersionMinor); + assert.strictEqual('1.0', req.httpVersion); + assert.strictEqual(1, req.httpVersionMajor); + assert.strictEqual(0, req.httpVersionMinor); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(body); } @@ -49,25 +49,25 @@ function test(handler, request_generator, response_validator) { } function response_validator(server_response, client_got_eof, timed_out) { - var m = server_response.split('\r\n\r\n'); - assert.equal(m[1], body); - assert.equal(true, client_got_eof); - assert.equal(false, timed_out); + const m = server_response.split('\r\n\r\n'); + assert.strictEqual(m[1], body); + assert.strictEqual(true, client_got_eof); + assert.strictEqual(false, timed_out); } test(handler, request_generator, response_validator); -})(); +} // // Don't send HTTP/1.1 status lines to HTTP/1.0 clients. // // https://github.com/joyent/node/issues/1234 // -(function() { +{ function handler(req, res) { - assert.equal('1.0', req.httpVersion); - assert.equal(1, req.httpVersionMajor); - assert.equal(0, req.httpVersionMinor); + assert.strictEqual('1.0', req.httpVersion); + assert.strictEqual(1, req.httpVersionMajor); + assert.strictEqual(0, req.httpVersionMinor); res.sendDate = false; res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello, '); res._send(''); @@ -85,25 +85,25 @@ function test(handler, request_generator, response_validator) { } function response_validator(server_response, client_got_eof, timed_out) { - var expected_response = 'HTTP/1.1 200 OK\r\n' + - 'Content-Type: text/plain\r\n' + - 'Connection: close\r\n' + - '\r\n' + - 'Hello, world!'; - - assert.equal(expected_response, server_response); - assert.equal(true, client_got_eof); - assert.equal(false, timed_out); + const expected_response = 'HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/plain\r\n' + + 'Connection: close\r\n' + + '\r\n' + + 'Hello, world!'; + + assert.strictEqual(expected_response, server_response); + assert.strictEqual(true, client_got_eof); + assert.strictEqual(false, timed_out); } test(handler, request_generator, response_validator); -})(); +} -(function() { +{ function handler(req, res) { - assert.equal('1.1', req.httpVersion); - assert.equal(1, req.httpVersionMajor); - assert.equal(1, req.httpVersionMinor); + assert.strictEqual('1.1', req.httpVersion); + assert.strictEqual(1, req.httpVersionMajor); + assert.strictEqual(1, req.httpVersionMinor); res.sendDate = false; res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello, '); res._send(''); @@ -112,32 +112,32 @@ function test(handler, request_generator, response_validator) { } function request_generator() { - return ('GET / HTTP/1.1\r\n' + + return 'GET / HTTP/1.1\r\n' + 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + 'Connection: close\r\n' + 'Host: 127.0.0.1:1337\r\n' + 'Accept: */*\r\n' + - '\r\n'); + '\r\n'; } function response_validator(server_response, client_got_eof, timed_out) { - var expected_response = 'HTTP/1.1 200 OK\r\n' + - 'Content-Type: text/plain\r\n' + - 'Connection: close\r\n' + - 'Transfer-Encoding: chunked\r\n' + - '\r\n' + - '7\r\n' + - 'Hello, \r\n' + - '6\r\n' + - 'world!\r\n' + - '0\r\n' + - '\r\n'; - - assert.equal(expected_response, server_response); - assert.equal(true, client_got_eof); - assert.equal(false, timed_out); + const expected_response = 'HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/plain\r\n' + + 'Connection: close\r\n' + + 'Transfer-Encoding: chunked\r\n' + + '\r\n' + + '7\r\n' + + 'Hello, \r\n' + + '6\r\n' + + 'world!\r\n' + + '0\r\n' + + '\r\n'; + + assert.strictEqual(expected_response, server_response); + assert.strictEqual(true, client_got_eof); + assert.strictEqual(false, timed_out); } test(handler, request_generator, response_validator); -})(); +} diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index 360dc6ccc982dd..abc1d096dff0d8 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -72,21 +72,21 @@ function expectBody(expected) { // // Simple request test. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'GET /hello HTTP/1.1' + CRLF + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); - assert.equal(method, methods.indexOf('GET')); - assert.equal(url || parser.url, '/hello'); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); + assert.strictEqual(method, methods.indexOf('GET')); + assert.strictEqual(url || parser.url, '/hello'); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser.execute(request, 0, request.length); @@ -104,72 +104,72 @@ function expectBody(expected) { assert.throws(function() { parser.execute(request, 0, request.length); }, Error, 'hello world'); -})(); +} // // Simple response test. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'HTTP/1.1 200 OK' + CRLF + 'Content-Type: text/plain' + CRLF + 'Content-Length: 4' + CRLF + CRLF + 'pong'); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, undefined); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); - assert.equal(statusCode, 200); - assert.equal(statusMessage, 'OK'); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, undefined); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); + assert.strictEqual(statusCode, 200); + assert.strictEqual(statusMessage, 'OK'); }; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, 'pong'); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, 'pong'); }; - var parser = newParser(RESPONSE); + const parser = newParser(RESPONSE); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody); parser.execute(request, 0, request.length); -})(); +} // // Response with no headers. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'HTTP/1.0 200 Connection established' + CRLF + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 0); - assert.equal(method, undefined); - assert.equal(statusCode, 200); - assert.equal(statusMessage, 'Connection established'); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 0); + assert.strictEqual(method, undefined); + assert.strictEqual(statusCode, 200); + assert.strictEqual(statusMessage, 'Connection established'); assert.deepStrictEqual(headers || parser.headers, []); }; - var parser = newParser(RESPONSE); + const parser = newParser(RESPONSE); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser.execute(request, 0, request.length); -})(); +} // // Trailing headers. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Transfer-Encoding: chunked' + CRLF + CRLF + @@ -180,139 +180,139 @@ function expectBody(expected) { 'Content-Type: text/plain' + CRLF + CRLF); - var seen_body = false; + let seen_body = false; - var onHeaders = function(headers, url) { + const onHeaders = function(headers, url) { assert.ok(seen_body); // trailers should come after the body assert.deepStrictEqual(headers, ['Vary', '*', 'Content-Type', 'text/plain']); }; - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); // expect to see trailing headers now parser[kOnHeaders] = mustCall(onHeaders); }; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, 'ping'); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, 'ping'); seen_body = true; }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody); parser.execute(request, 0, request.length); -})(); +} // // Test header ordering. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'GET / HTTP/1.0' + CRLF + 'X-Filler: 1337' + CRLF + 'X-Filler: 42' + CRLF + 'X-Filler2: 42' + CRLF + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('GET')); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 0); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('GET')); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 0); assert.deepStrictEqual( headers || parser.headers, ['X-Filler', '1337', 'X-Filler', '42', 'X-Filler2', '42']); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser.execute(request, 0, request.length); -})(); +} // // Test large number of headers // -(function() { +{ // 256 X-Filler headers - var lots_of_headers = 'X-Filler: 42' + CRLF; + let lots_of_headers = 'X-Filler: 42' + CRLF; lots_of_headers = lots_of_headers.repeat(256); - var request = Buffer.from( + const request = Buffer.from( 'GET /foo/bar/baz?quux=42#1337 HTTP/1.0' + CRLF + lots_of_headers + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('GET')); - assert.equal(url || parser.url, '/foo/bar/baz?quux=42#1337'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 0); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('GET')); + assert.strictEqual(url || parser.url, '/foo/bar/baz?quux=42#1337'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 0); headers = headers || parser.headers; - assert.equal(headers.length, 2 * 256); // 256 key/value pairs - for (var i = 0; i < headers.length; i += 2) { - assert.equal(headers[i], 'X-Filler'); - assert.equal(headers[i + 1], '42'); + assert.strictEqual(headers.length, 2 * 256); // 256 key/value pairs + for (let i = 0; i < headers.length; i += 2) { + assert.strictEqual(headers[i], 'X-Filler'); + assert.strictEqual(headers[i + 1], '42'); } }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser.execute(request, 0, request.length); -})(); +} // // Test request body // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: application/x-www-form-urlencoded' + CRLF + 'Content-Length: 15' + CRLF + CRLF + 'foo=42&bar=1337'); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); }; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, 'foo=42&bar=1337'); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, 'foo=42&bar=1337'); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody); parser.execute(request, 0, request.length); -})(); +} // // Test chunked request body // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -325,35 +325,35 @@ function expectBody(expected) { '1234567890' + CRLF + '0' + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); }; let body_part = 0; const body_parts = ['123', '123456', '1234567890']; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, body_parts[body_part++]); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, body_parts[body_part++]); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody, body_parts.length); parser.execute(request, 0, request.length); -})(); +} // // Test chunked request body spread over multiple buffers (packets) // -(function() { - var request = Buffer.from( +{ + let request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -363,25 +363,25 @@ function expectBody(expected) { '6' + CRLF + '123456' + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); }; let body_part = 0; const body_parts = ['123', '123456', '123456789', '123456789ABC', '123456789ABCDEF']; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, body_parts[body_part++]); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, body_parts[body_part++]); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody, body_parts.length); parser.execute(request, 0, request.length); @@ -396,14 +396,14 @@ function expectBody(expected) { '0' + CRLF); parser.execute(request, 0, request.length); -})(); +} // // Stress test. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /helpme HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -421,30 +421,30 @@ function expectBody(expected) { '0' + CRLF); function test(a, b) { - var onHeadersComplete = function(versionMajor, versionMinor, headers, - method, url, statusCode, statusMessage, - upgrade, shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/helpme'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/helpme'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); }; - var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; + let expected_body = '123123456123456789123456789ABC123456789ABCDEF'; - var onBody = function(buf, start, len) { - var chunk = '' + buf.slice(start, start + len); - assert.equal(expected_body.indexOf(chunk), 0); + const onBody = function(buf, start, len) { + const chunk = '' + buf.slice(start, start + len); + assert.strictEqual(expected_body.indexOf(chunk), 0); expected_body = expected_body.slice(chunk.length); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = onBody; parser.execute(a, 0, a.length); parser.execute(b, 0, b.length); - assert.equal(expected_body, ''); + assert.strictEqual(expected_body, ''); } for (var i = 1; i < request.length - 1; ++i) { @@ -456,14 +456,14 @@ function expectBody(expected) { JSON.stringify(b.toString())); test(a, b); } -})(); +} // // Byte by byte test. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -480,43 +480,43 @@ function expectBody(expected) { '123456789ABCDEF' + CRLF + '0' + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); assert.deepStrictEqual( headers || parser.headers, ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']); }; - var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; + let expected_body = '123123456123456789123456789ABC123456789ABCDEF'; - var onBody = function(buf, start, len) { - var chunk = '' + buf.slice(start, start + len); - assert.equal(expected_body.indexOf(chunk), 0); + const onBody = function(buf, start, len) { + const chunk = '' + buf.slice(start, start + len); + assert.strictEqual(expected_body.indexOf(chunk), 0); expected_body = expected_body.slice(chunk.length); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = onBody; - for (var i = 0; i < request.length; ++i) { + for (let i = 0; i < request.length; ++i) { parser.execute(request, i, 1); } - assert.equal(expected_body, ''); -})(); + assert.strictEqual(expected_body, ''); +} // // Test parser reinit sequence. // -(function() { - var req1 = Buffer.from( +{ + const req1 = Buffer.from( 'PUT /this HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -525,16 +525,16 @@ function expectBody(expected) { 'ping' + CRLF + '0' + CRLF); - var req2 = Buffer.from( + const req2 = Buffer.from( 'POST /that HTTP/1.0' + CRLF + 'Content-Type: text/plain' + CRLF + 'Content-Length: 4' + CRLF + CRLF + 'pong'); - var onHeadersComplete1 = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { + const onHeadersComplete1 = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { assert.equal(method, methods.indexOf('PUT')); assert.equal(url, '/this'); assert.equal(versionMajor, 1); @@ -544,20 +544,20 @@ function expectBody(expected) { ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']); }; - var onHeadersComplete2 = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url, '/that'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 0); + const onHeadersComplete2 = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url, '/that'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 0); assert.deepStrictEqual( headers, ['Content-Type', 'text/plain', 'Content-Length', '4'] ); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = onHeadersComplete1; parser[kOnBody] = expectBody('ping'); parser.execute(req1, 0, req1.length); @@ -566,7 +566,7 @@ function expectBody(expected) { parser[kOnBody] = expectBody('pong'); parser[kOnHeadersComplete] = onHeadersComplete2; parser.execute(req2, 0, req2.length); -})(); +} // Test parser 'this' safety // https://github.com/joyent/node/issues/6690 diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 5d52fe6544a1a8..37cf66705d56d7 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -134,7 +134,7 @@ qsNoMungeTestCases.forEach(function(testCase) { }); // test the nested qs-in-qs case -(function() { +{ const f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); check(f, createWithNoPrototype([ { key: 'a', value: 'b'}, @@ -147,10 +147,10 @@ qsNoMungeTestCases.forEach(function(testCase) { {key: 'y', value: 'z' } ]); check(f.q, expectedInternal); -})(); +} // nested in colon -(function() { +{ const f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); check(f, createWithNoPrototype([ {key: 'a', value: 'b'}, @@ -162,7 +162,7 @@ qsNoMungeTestCases.forEach(function(testCase) { {key: 'y', value: 'z' } ]); check(f.q, expectedInternal); -})(); +} // now test stringifying diff --git a/test/parallel/test-require-cache.js b/test/parallel/test-require-cache.js index 7ea68dd0515799..247590197d6126 100644 --- a/test/parallel/test-require-cache.js +++ b/test/parallel/test-require-cache.js @@ -2,22 +2,22 @@ require('../common'); var assert = require('assert'); -(function testInjectFakeModule() { - var relativePath = '../fixtures/semicolon'; - var absolutePath = require.resolve(relativePath); - var fakeModule = {}; +{ + const relativePath = '../fixtures/semicolon'; + const absolutePath = require.resolve(relativePath); + const fakeModule = {}; require.cache[absolutePath] = {exports: fakeModule}; assert.strictEqual(require(relativePath), fakeModule); -})(); +} -(function testInjectFakeNativeModule() { - var relativePath = 'fs'; - var fakeModule = {}; +{ + const relativePath = 'fs'; + const fakeModule = {}; require.cache[relativePath] = {exports: fakeModule}; assert.strictEqual(require(relativePath), fakeModule); -})(); +} diff --git a/test/parallel/test-stream-pipe-error-handling.js b/test/parallel/test-stream-pipe-error-handling.js index 88a70fb58e2cf1..b2c25cfe8c6e22 100644 --- a/test/parallel/test-stream-pipe-error-handling.js +++ b/test/parallel/test-stream-pipe-error-handling.js @@ -1,33 +1,33 @@ 'use strict'; -require('../common'); -var assert = require('assert'); -var Stream = require('stream').Stream; +const common = require('../common'); +const assert = require('assert'); +const Stream = require('stream').Stream; -(function testErrorListenerCatches() { - var source = new Stream(); - var dest = new Stream(); +{ + const source = new Stream(); + const dest = new Stream(); source.pipe(dest); - var gotErr = null; + let gotErr = null; source.on('error', function(err) { gotErr = err; }); - var err = new Error('This stream turned into bacon.'); + const err = new Error('This stream turned into bacon.'); source.emit('error', err); assert.strictEqual(gotErr, err); -})(); +} -(function testErrorWithoutListenerThrows() { - var source = new Stream(); - var dest = new Stream(); +{ + const source = new Stream(); + const dest = new Stream(); source.pipe(dest); - var err = new Error('This stream turned into bacon.'); + const err = new Error('This stream turned into bacon.'); - var gotErr = null; + let gotErr = null; try { source.emit('error', err); } catch (e) { @@ -35,30 +35,23 @@ var Stream = require('stream').Stream; } assert.strictEqual(gotErr, err); -})(); +} -(function testErrorWithRemovedListenerThrows() { - var R = Stream.Readable; - var W = Stream.Writable; +{ + const R = Stream.Readable; + const W = Stream.Writable; - var r = new R(); - var w = new W(); - var removed = false; - var didTest = false; - - process.on('exit', function() { - assert(didTest); - console.log('ok'); - }); + const r = new R(); + const w = new W(); + let removed = false; r._read = function() { - setTimeout(function() { + setTimeout(common.mustCall(function() { assert(removed); assert.throws(function() { w.emit('error', new Error('fail')); }); - didTest = true; - }); + })); }; w.on('error', myOnError); @@ -69,41 +62,28 @@ var Stream = require('stream').Stream; function myOnError(er) { throw new Error('this should not happen'); } -})(); +} -(function testErrorWithRemovedListenerThrows() { - var R = Stream.Readable; - var W = Stream.Writable; +{ + const R = Stream.Readable; + const W = Stream.Writable; - var r = new R(); - var w = new W(); - var removed = false; - var didTest = false; - var caught = false; - - process.on('exit', function() { - assert(didTest); - console.log('ok'); - }); + const r = new R(); + const w = new W(); + let removed = false; r._read = function() { - setTimeout(function() { + setTimeout(common.mustCall(function() { assert(removed); w.emit('error', new Error('fail')); - didTest = true; - }); + })); }; - w.on('error', myOnError); + w.on('error', common.mustCall(function(er) {})); w._write = function() {}; r.pipe(w); // Removing some OTHER random listener should not do anything w.removeListener('error', function() {}); removed = true; - - function myOnError(er) { - assert(!caught); - caught = true; - } -})(); +} diff --git a/test/parallel/test-stream-readable-event.js b/test/parallel/test-stream-readable-event.js index 957f4097818bfc..a20fc2ee732d0f 100644 --- a/test/parallel/test-stream-readable-event.js +++ b/test/parallel/test-stream-readable-event.js @@ -1,106 +1,64 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var Readable = require('stream').Readable; +const Readable = require('stream').Readable; -(function first() { +{ // First test, not reading when the readable is added. // make sure that on('readable', ...) triggers a readable event. - var r = new Readable({ + const r = new Readable({ highWaterMark: 3 }); - var _readCalled = false; - r._read = function(n) { - _readCalled = true; - }; + r._read = common.fail; // This triggers a 'readable' event, which is lost. r.push(Buffer.from('blerg')); - var caughtReadable = false; setTimeout(function() { // we're testing what we think we are assert(!r._readableState.reading); - r.on('readable', function() { - caughtReadable = true; - }); + r.on('readable', common.mustCall(function() {})); }); +} - process.on('exit', function() { - // we're testing what we think we are - assert(!_readCalled); - - assert(caughtReadable); - console.log('ok 1'); - }); -})(); - -(function second() { +{ // second test, make sure that readable is re-emitted if there's // already a length, while it IS reading. - var r = new Readable({ + const r = new Readable({ highWaterMark: 3 }); - var _readCalled = false; - r._read = function(n) { - _readCalled = true; - }; + r._read = common.mustCall(function(n) {}); // This triggers a 'readable' event, which is lost. r.push(Buffer.from('bl')); - var caughtReadable = false; setTimeout(function() { // assert we're testing what we think we are assert(r._readableState.reading); - r.on('readable', function() { - caughtReadable = true; - }); - }); - - process.on('exit', function() { - // we're testing what we think we are - assert(_readCalled); - - assert(caughtReadable); - console.log('ok 2'); + r.on('readable', common.mustCall(function() {})); }); -})(); +} -(function third() { +{ // Third test, not reading when the stream has not passed // the highWaterMark but *has* reached EOF. - var r = new Readable({ + const r = new Readable({ highWaterMark: 30 }); - var _readCalled = false; - r._read = function(n) { - _readCalled = true; - }; + r._read = common.fail; // This triggers a 'readable' event, which is lost. r.push(Buffer.from('blerg')); r.push(null); - var caughtReadable = false; setTimeout(function() { // assert we're testing what we think we are assert(!r._readableState.reading); - r.on('readable', function() { - caughtReadable = true; - }); - }); - - process.on('exit', function() { - // we're testing what we think we are - assert(!_readCalled); - - assert(caughtReadable); - console.log('ok 3'); + r.on('readable', common.mustCall(function() {})); }); -})(); +} diff --git a/test/parallel/test-stream-writable-decoded-encoding.js b/test/parallel/test-stream-writable-decoded-encoding.js index 75d5d424766323..621e342a3c2d74 100644 --- a/test/parallel/test-stream-writable-decoded-encoding.js +++ b/test/parallel/test-stream-writable-decoded-encoding.js @@ -17,24 +17,22 @@ MyWritable.prototype._write = function(chunk, encoding, callback) { callback(); }; -(function decodeStringsTrue() { - var m = new MyWritable(function(isBuffer, type, enc) { +{ + const m = new MyWritable(function(isBuffer, type, enc) { assert(isBuffer); - assert.equal(type, 'object'); - assert.equal(enc, 'buffer'); - console.log('ok - decoded string is decoded'); + assert.strictEqual(type, 'object'); + assert.strictEqual(enc, 'buffer'); }, { decodeStrings: true }); m.write('some-text', 'utf8'); m.end(); -})(); +} -(function decodeStringsFalse() { - var m = new MyWritable(function(isBuffer, type, enc) { +{ + const m = new MyWritable(function(isBuffer, type, enc) { assert(!isBuffer); - assert.equal(type, 'string'); - assert.equal(enc, 'utf8'); - console.log('ok - un-decoded string is not decoded'); + assert.strictEqual(type, 'string'); + assert.strictEqual(enc, 'utf8'); }, { decodeStrings: false }); m.write('some-text', 'utf8'); m.end(); -})(); +} diff --git a/test/parallel/test-stream2-pipe-error-handling.js b/test/parallel/test-stream2-pipe-error-handling.js index 65397566c23ca2..bdf7a4a9a33a77 100644 --- a/test/parallel/test-stream2-pipe-error-handling.js +++ b/test/parallel/test-stream2-pipe-error-handling.js @@ -3,77 +3,77 @@ require('../common'); var assert = require('assert'); var stream = require('stream'); -(function testErrorListenerCatches() { - var count = 1000; +{ + let count = 1000; - var source = new stream.Readable(); + const source = new stream.Readable(); source._read = function(n) { n = Math.min(count, n); count -= n; source.push(Buffer.allocUnsafe(n)); }; - var unpipedDest; + let unpipedDest; source.unpipe = function(dest) { unpipedDest = dest; stream.Readable.prototype.unpipe.call(this, dest); }; - var dest = new stream.Writable(); + const dest = new stream.Writable(); dest._write = function(chunk, encoding, cb) { cb(); }; source.pipe(dest); - var gotErr = null; + let gotErr = null; dest.on('error', function(err) { gotErr = err; }); - var unpipedSource; + let unpipedSource; dest.on('unpipe', function(src) { unpipedSource = src; }); - var err = new Error('This stream turned into bacon.'); + const err = new Error('This stream turned into bacon.'); dest.emit('error', err); assert.strictEqual(gotErr, err); assert.strictEqual(unpipedSource, source); assert.strictEqual(unpipedDest, dest); -})(); +} -(function testErrorWithoutListenerThrows() { - var count = 1000; +{ + let count = 1000; - var source = new stream.Readable(); + const source = new stream.Readable(); source._read = function(n) { n = Math.min(count, n); count -= n; source.push(Buffer.allocUnsafe(n)); }; - var unpipedDest; + let unpipedDest; source.unpipe = function(dest) { unpipedDest = dest; stream.Readable.prototype.unpipe.call(this, dest); }; - var dest = new stream.Writable(); + const dest = new stream.Writable(); dest._write = function(chunk, encoding, cb) { cb(); }; source.pipe(dest); - var unpipedSource; + let unpipedSource; dest.on('unpipe', function(src) { unpipedSource = src; }); - var err = new Error('This stream turned into bacon.'); + const err = new Error('This stream turned into bacon.'); - var gotErr = null; + let gotErr = null; try { dest.emit('error', err); } catch (e) { @@ -82,4 +82,4 @@ var stream = require('stream'); assert.strictEqual(gotErr, err); assert.strictEqual(unpipedSource, source); assert.strictEqual(unpipedDest, dest); -})(); +} diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js index 68332232171ab4..8372321991dc53 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -53,57 +53,57 @@ var RADIOS = 2; var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; -(function() { - for (var j = 0; j < RADIOS * 2; j += 1) { - var datum = b; - var slice = datum.slice(0, PRE_HALF_APEX + j); - var slice2 = datum.slice(0, PRE_HALF_APEX + j + 2); - var pumped_string = slice.toString('hex'); - var pumped_string2 = slice2.toString('hex'); - var decoded = Buffer.from(pumped_string, 'hex'); +{ + for (let j = 0; j < RADIOS * 2; j += 1) { + const datum = b; + const slice = datum.slice(0, PRE_HALF_APEX + j); + const slice2 = datum.slice(0, PRE_HALF_APEX + j + 2); + const pumped_string = slice.toString('hex'); + const pumped_string2 = slice2.toString('hex'); + const decoded = Buffer.from(pumped_string, 'hex'); // the string are the same? - for (var k = 0; k < pumped_string.length; ++k) { - assert.equal(pumped_string[k], pumped_string2[k]); + for (let k = 0; k < pumped_string.length; ++k) { + assert.strictEqual(pumped_string[k], pumped_string2[k]); } // the recoded buffer is the same? - for (var i = 0; i < decoded.length; ++i) { - assert.equal(datum[i], decoded[i]); + for (let i = 0; i < decoded.length; ++i) { + assert.strictEqual(datum[i], decoded[i]); } } -})(); +} -(function() { - for (var j = 0; j < RADIOS * 2; j += 1) { - var datum = b; - var slice = datum.slice(0, PRE_3OF4_APEX + j); - var slice2 = datum.slice(0, PRE_3OF4_APEX + j + 2); - var pumped_string = slice.toString('base64'); - var pumped_string2 = slice2.toString('base64'); - var decoded = Buffer.from(pumped_string, 'base64'); +{ + for (let j = 0; j < RADIOS * 2; j += 1) { + const datum = b; + const slice = datum.slice(0, PRE_3OF4_APEX + j); + const slice2 = datum.slice(0, PRE_3OF4_APEX + j + 2); + const pumped_string = slice.toString('base64'); + const pumped_string2 = slice2.toString('base64'); + const decoded = Buffer.from(pumped_string, 'base64'); // the string are the same? - for (var k = 0; k < pumped_string.length - 3; ++k) { - assert.equal(pumped_string[k], pumped_string2[k]); + for (let k = 0; k < pumped_string.length - 3; ++k) { + assert.strictEqual(pumped_string[k], pumped_string2[k]); } // the recoded buffer is the same? - for (var i = 0; i < decoded.length; ++i) { - assert.equal(datum[i], decoded[i]); + for (let i = 0; i < decoded.length; ++i) { + assert.strictEqual(datum[i], decoded[i]); } } -})(); +} // https://github.com/nodejs/node/issues/1024 -(function() { - var a = Array(1 << 20).join('x'); - var b = Buffer.from(a, 'ucs2').toString('ucs2'); - var c = Buffer.from(b, 'utf8').toString('utf8'); +{ + const a = Array(1 << 20).join('x'); + const b = Buffer.from(a, 'ucs2').toString('ucs2'); + const c = Buffer.from(b, 'utf8').toString('utf8'); - assert.equal(a.length, b.length); - assert.equal(b.length, c.length); + assert.strictEqual(a.length, b.length); + assert.strictEqual(b.length, c.length); - assert.equal(a, b); - assert.equal(b, c); -})(); + assert.strictEqual(a, b); + assert.strictEqual(b, c); +} diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index 570c51b9ac7a5f..801b34792a1f73 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -55,11 +55,11 @@ setInterval(function() { }, SHORT_TIME); // Should not assert on args.Holder()->InternalFieldCount() > 0. See #4261. -(function() { - var t = setInterval(function() {}, 1); +{ + const t = setInterval(function() {}, 1); process.nextTick(t.unref.bind({})); process.nextTick(t.unref.bind(t)); -})(); +} process.on('exit', function() { assert.strictEqual(interval_fired, false, diff --git a/test/parallel/test-timers-zero-timeout.js b/test/parallel/test-timers-zero-timeout.js index ab0c38f6084277..00e75b7ea8fa24 100644 --- a/test/parallel/test-timers-zero-timeout.js +++ b/test/parallel/test-timers-zero-timeout.js @@ -1,39 +1,32 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); // https://github.com/joyent/node/issues/2079 - zero timeout drops extra args -(function() { - var ncalled = 0; - - setTimeout(f, 0, 'foo', 'bar', 'baz'); +{ + setTimeout(common.mustCall(f), 0, 'foo', 'bar', 'baz'); setTimeout(function() {}, 0); function f(a, b, c) { - assert.equal(a, 'foo'); - assert.equal(b, 'bar'); - assert.equal(c, 'baz'); - ncalled++; + assert.strictEqual(a, 'foo'); + assert.strictEqual(b, 'bar'); + assert.strictEqual(c, 'baz'); } +} - process.on('exit', function() { - assert.equal(ncalled, 1); - }); -})(); - -(function() { - var ncalled = 0; +{ + let ncalled = 0; - var iv = setInterval(f, 0, 'foo', 'bar', 'baz'); + const iv = setInterval(f, 0, 'foo', 'bar', 'baz'); function f(a, b, c) { - assert.equal(a, 'foo'); - assert.equal(b, 'bar'); - assert.equal(c, 'baz'); + assert.strictEqual(a, 'foo'); + assert.strictEqual(b, 'bar'); + assert.strictEqual(c, 'baz'); if (++ncalled == 3) clearTimeout(iv); } process.on('exit', function() { - assert.equal(ncalled, 3); + assert.strictEqual(ncalled, 3); }); -})(); +} diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js index 3853ea66bc80f4..96de1b0ad6fe42 100644 --- a/test/parallel/test-tls-connect.js +++ b/test/parallel/test-tls-connect.js @@ -13,37 +13,38 @@ var path = require('path'); // https://github.com/joyent/node/issues/1218 // uncatchable exception on TLS connection error -(function() { - var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); - var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); +{ + const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); + const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - var errorEmitted = false; + let errorEmitted = false; process.on('exit', function() { assert.ok(errorEmitted); }); - var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { + const options = {cert: cert, key: key, port: common.PORT}; + const conn = tls.connect(options, function() { assert.ok(false); // callback should never be executed }); conn.on('error', function() { errorEmitted = true; }); -})(); +} // SSL_accept/SSL_connect error handling -(function() { - var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); - var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); +{ + const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); + const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - var errorEmitted = false; + let errorEmitted = false; process.on('exit', function() { assert.ok(errorEmitted); }); - var conn = tls.connect({ + const conn = tls.connect({ cert: cert, key: key, port: common.PORT, @@ -55,4 +56,4 @@ var path = require('path'); conn.on('error', function() { errorEmitted = true; }); -})(); +} diff --git a/test/parallel/test-util-format.js b/test/parallel/test-util-format.js index 92c448578bec1f..f3702ef2f05547 100644 --- a/test/parallel/test-util-format.js +++ b/test/parallel/test-util-format.js @@ -48,11 +48,11 @@ assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz'); assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); -(function() { - var o = {}; +{ + const o = {}; o.o = o; assert.equal(util.format('%j', o), '[Circular]'); -})(); +} // Errors const err = new Error('foo'); diff --git a/test/parallel/test-vm-debug-context.js b/test/parallel/test-vm-debug-context.js index 07335fad56a1f7..9b8da58756c8d3 100644 --- a/test/parallel/test-vm-debug-context.js +++ b/test/parallel/test-vm-debug-context.js @@ -31,9 +31,9 @@ assert.strictEqual(vm.runInDebugContext(undefined), undefined); // See https://github.com/nodejs/node/issues/1190, accessing named interceptors // and accessors inside a debug event listener should not crash. -(function() { - var Debug = vm.runInDebugContext('Debug'); - var breaks = 0; +{ + const Debug = vm.runInDebugContext('Debug'); + let breaks = 0; function ondebugevent(evt, exc) { if (evt !== Debug.DebugEvent.Break) return; @@ -51,10 +51,10 @@ assert.strictEqual(vm.runInDebugContext(undefined), undefined); assert.equal(breaks, 0); breakpoint(); assert.equal(breaks, 1); -})(); +} // Can set listeners and breakpoints on a single line file -(function() { +{ const Debug = vm.runInDebugContext('Debug'); const fn = require(common.fixturesDir + '/exports-function-with-param'); let called = false; @@ -69,7 +69,7 @@ assert.strictEqual(vm.runInDebugContext(undefined), undefined); fn('foo'); assert.strictEqual(Debug.showBreakPoints(fn), '(arg) { [B0]return arg; }'); assert.strictEqual(called, true); -})(); +} // See https://github.com/nodejs/node/issues/1190, fatal errors should not // crash the process. diff --git a/test/parallel/test-zlib-dictionary-fail.js b/test/parallel/test-zlib-dictionary-fail.js index 2c8939c68fac21..21c94b2c41015b 100644 --- a/test/parallel/test-zlib-dictionary-fail.js +++ b/test/parallel/test-zlib-dictionary-fail.js @@ -4,8 +4,8 @@ var assert = require('assert'); var zlib = require('zlib'); // Should raise an error, not trigger an assertion in src/node_zlib.cc -(function() { - var stream = zlib.createInflate(); +{ + const stream = zlib.createInflate(); stream.on('error', common.mustCall(function(err) { assert(/Missing dictionary/.test(err.message)); @@ -13,11 +13,11 @@ var zlib = require('zlib'); // String "test" encoded with dictionary "dict". stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); -})(); +} // Should raise an error, not trigger an assertion in src/node_zlib.cc -(function() { - var stream = zlib.createInflate({ dictionary: Buffer.from('fail') }); +{ + const stream = zlib.createInflate({ dictionary: Buffer.from('fail') }); stream.on('error', common.mustCall(function(err) { assert(/Bad dictionary/.test(err.message)); @@ -25,4 +25,4 @@ var zlib = require('zlib'); // String "test" encoded with dictionary "dict". stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); -})(); +} diff --git a/test/pummel/test-https-ci-reneg-attack.js b/test/pummel/test-https-ci-reneg-attack.js index 701963606e6d80..8bda7cc10286e9 100644 --- a/test/pummel/test-https-ci-reneg-attack.js +++ b/test/pummel/test-https-ci-reneg-attack.js @@ -20,15 +20,15 @@ if (!common.opensslCli) { // renegotiation limits to test var LIMITS = [0, 1, 2, 3, 5, 10, 16]; -(function() { - var n = 0; +{ + let n = 0; function next() { if (n >= LIMITS.length) return; tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; test(next); } next(); -})(); +} function test(next) { var options = { diff --git a/test/pummel/test-net-connect-memleak.js b/test/pummel/test-net-connect-memleak.js index e30ca2e6b0b72a..7c74011755403c 100644 --- a/test/pummel/test-net-connect-memleak.js +++ b/test/pummel/test-net-connect-memleak.js @@ -9,10 +9,11 @@ assert(typeof global.gc === 'function', 'Run this test with --expose-gc'); net.createServer(function() {}).listen(common.PORT); var before = 0; -(function() { +{ // 2**26 == 64M entries global.gc(); - for (var i = 0, junk = [0]; i < 26; ++i) junk = junk.concat(junk); + let junk = [0]; + for (let i = 0; i < 26; ++i) junk = junk.concat(junk); before = process.memoryUsage().rss; net.createConnection(common.PORT, '127.0.0.1', function() { @@ -20,7 +21,7 @@ var before = 0; setTimeout(done, 10); global.gc(); }); -})(); +} function done() { global.gc(); diff --git a/test/pummel/test-tls-ci-reneg-attack.js b/test/pummel/test-tls-ci-reneg-attack.js index b62b8944357ee7..5075806c1085b6 100644 --- a/test/pummel/test-tls-ci-reneg-attack.js +++ b/test/pummel/test-tls-ci-reneg-attack.js @@ -19,15 +19,15 @@ if (!common.opensslCli) { // renegotiation limits to test var LIMITS = [0, 1, 2, 3, 5, 10, 16]; -(function() { - var n = 0; +{ + let n = 0; function next() { if (n >= LIMITS.length) return; tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; test(next); } next(); -})(); +} function test(next) { var options = { diff --git a/test/pummel/test-tls-connect-memleak.js b/test/pummel/test-tls-connect-memleak.js index 2ea61ead6fe5c3..227d9c56f4366e 100644 --- a/test/pummel/test-tls-connect-memleak.js +++ b/test/pummel/test-tls-connect-memleak.js @@ -19,17 +19,19 @@ tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/test_key.pem') }).listen(common.PORT); -(function() { +{ // 2**26 == 64M entries - for (var i = 0, junk = [0]; i < 26; ++i) junk = junk.concat(junk); + let junk = [0]; - var options = { rejectUnauthorized: false }; + for (let i = 0; i < 26; ++i) junk = junk.concat(junk); + + const options = { rejectUnauthorized: false }; tls.connect(common.PORT, '127.0.0.1', options, function() { assert(junk.length != 0); // keep reference alive setTimeout(done, 10); global.gc(); }); -})(); +} function done() { var before = process.memoryUsage().rss; diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 2fad4ba8c205b7..fc3c0494dcbe18 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -70,8 +70,8 @@ assert.strictEqual(ret, msg + '\n', } // Verify that stderr is not accessed when stdio = 'ignore' - GH #7966 -(function() { +{ assert.throws(function() { execSync('exit -1', {stdio: 'ignore'}); }, /Command failed: exit -1/); -})(); +} From d224b47b3a7c41fda7b037584eaaa685969e534d Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 12 Jul 2016 16:31:46 -0700 Subject: [PATCH 11/34] test: improve error message in test-tick-processor Provide additional information about values that indicate test failed. PR-URL: https://github.com/nodejs/node/pull/7693 Reviewed-By: Colin Ihrig Reviewed-By: Brian White --- test/parallel/test-tick-processor.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/parallel/test-tick-processor.js b/test/parallel/test-tick-processor.js index 3abb97579b74ee..550061499a394b 100644 --- a/test/parallel/test-tick-processor.js +++ b/test/parallel/test-tick-processor.js @@ -1,8 +1,8 @@ 'use strict'; -var fs = require('fs'); -var assert = require('assert'); -var cp = require('child_process'); -var common = require('../common'); +const fs = require('fs'); +const assert = require('assert'); +const cp = require('child_process'); +const common = require('../common'); // TODO(mhdawson) Currently the test-tick-processor functionality in V8 // depends on addresses being smaller than a full 64 bits. Aix supports @@ -49,12 +49,12 @@ function runTest(pattern, code) { return /^isolate-/.test(file); }); if (matches.length != 1) { - assert.fail(null, null, 'There should be a single log file.'); + common.fail('There should be a single log file.'); } var log = matches[0]; var out = cp.execSync(process.execPath + ' --prof-process --call-graph-size=10 ' + log, {encoding: 'utf8'}); - assert(pattern.test(out)); + assert(pattern.test(out), `${pattern} not matching ${out}`); fs.unlinkSync(log); } From f0d96103ff3d4a433c3349efc068fc4aff2145e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Hidalgo=20Garc=C3=ADa?= Date: Thu, 7 Jul 2016 20:39:09 +0200 Subject: [PATCH 12/34] doc: removed old git conflict markers from fs.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "doc/api/fs.md" file had some conflict markers like "<<<<<<< HEAD" that are visible at the bottom of https://nodejs.org/api/fs.html PR-URL: https://github.com/nodejs/node/pull/7590 Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Brian White Reviewed-By: Colin Ihrig Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Myles Borins --- doc/api/fs.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/doc/api/fs.md b/doc/api/fs.md index 74da659dbf6625..268b6db9b49b3d 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1963,12 +1963,9 @@ The following constants are meant for use with the [`fs.Stats`][] object's [Writable Stream]: stream.html#stream_class_stream_writable [inode]: http://www.linux.org/threads/intro-to-inodes.4130 [FS Constants]: #fs_fs_constants -<<<<<<< HEAD [`inotify`]: http://man7.org/linux/man-pages/man7/inotify.7.html [`kqueue`]: https://www.freebsd.org/cgi/man.cgi?kqueue [`FSEvents`]: https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005289-CH1-SW1 [`event ports`]: http://illumos.org/man/port_create [`ReadDirectoryChangesW`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465%28v=vs.85%29.aspx [`AHAFS`]: https://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/ -======= ->>>>>>> dcccbfd... src: refactor require('constants') From 3b767b86bded42d7b85e19f39264d1c21fdd3bfe Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Mon, 6 Jun 2016 13:06:56 +0100 Subject: [PATCH 13/34] buffer: fix creating from zero-length ArrayBuffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes regression where creating a new Buffer from an empty ArrayBuffer would fail. Ref: https://github.com/nodejs/node/commit/85ab4a5f1281c4e1dd06450ac7bd3250326267fa PR-URL: https://github.com/nodejs/node/pull/7176 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Ron Korving --- lib/buffer.js | 2 +- test/parallel/test-buffer-alloc.js | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/buffer.js b/lib/buffer.js index 3be54669619567..a5f7ec5ffbb7b1 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -218,7 +218,7 @@ function fromArrayBuffer(obj, byteOffset, length) { const maxLength = obj.byteLength - byteOffset; - if (maxLength <= 0) + if (maxLength < 0) throw new RangeError("'offset' is out of bounds"); if (length === undefined) { diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index c06c1107039cb2..b771054bdd0656 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -1458,3 +1458,8 @@ const ubuf = Buffer.allocUnsafeSlow(10); assert(ubuf); assert(ubuf.buffer); assert.equal(ubuf.buffer.byteLength, 10); + +// Regression test +assert.doesNotThrow(() => { + Buffer.from(new ArrayBuffer()); +}); From c10ade917a0891eaad206c21c6d31eed322d573e Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Sat, 9 Jul 2016 14:51:21 +0200 Subject: [PATCH 14/34] deps: back-port d721121 from v8 upstream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Original commit message: Quit creating array literal boilerplates from Crankshaft. It's such a corner case. BUG= Review URL: https://codereview.chromium.org/1865013002 Cr-Commit-Position: refs/heads/master@{#35346} Fixes: https://github.com/nodejs/node/issues/7454 PR-URL: https://github.com/nodejs/node/pull/7633 Reviewed-By: Fedor Indutny Reviewed-By: Michaël Zasso --- deps/v8/include/v8-version.h | 2 +- deps/v8/src/crankshaft/hydrogen.cc | 53 +++++++------------------ deps/v8/src/runtime/runtime-literals.cc | 9 ++--- deps/v8/src/runtime/runtime.h | 5 --- 4 files changed, 19 insertions(+), 50 deletions(-) diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index 39a537df5720aa..c30ace1e885cf1 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 5 #define V8_MINOR_VERSION 0 #define V8_BUILD_NUMBER 71 -#define V8_PATCH_LEVEL 54 +#define V8_PATCH_LEVEL 55 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/src/crankshaft/hydrogen.cc b/deps/v8/src/crankshaft/hydrogen.cc index 4e34d177254076..ea20a971de961a 100644 --- a/deps/v8/src/crankshaft/hydrogen.cc +++ b/deps/v8/src/crankshaft/hydrogen.cc @@ -6044,60 +6044,34 @@ void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { Handle site; Handle literals(environment()->closure()->literals(), isolate()); - bool uninitialized = false; Handle literals_cell(literals->literal(expr->literal_index()), isolate()); Handle boilerplate_object; - if (literals_cell->IsUndefined()) { - uninitialized = true; - Handle raw_boilerplate; - ASSIGN_RETURN_ON_EXCEPTION_VALUE( - isolate(), raw_boilerplate, - Runtime::CreateArrayLiteralBoilerplate( - isolate(), literals, expr->constant_elements(), - is_strong(function_language_mode())), - Bailout(kArrayBoilerplateCreationFailed)); - - boilerplate_object = Handle::cast(raw_boilerplate); - AllocationSiteCreationContext creation_context(isolate()); - site = creation_context.EnterNewScope(); - if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) { - return Bailout(kArrayBoilerplateCreationFailed); - } - creation_context.ExitScope(site, boilerplate_object); - literals->set_literal(expr->literal_index(), *site); - - if (boilerplate_object->elements()->map() == - isolate()->heap()->fixed_cow_array_map()) { - isolate()->counters()->cow_arrays_created_runtime()->Increment(); - } - } else { + if (!literals_cell->IsUndefined()) { DCHECK(literals_cell->IsAllocationSite()); site = Handle::cast(literals_cell); boilerplate_object = Handle( JSObject::cast(site->transition_info()), isolate()); } - DCHECK(!boilerplate_object.is_null()); - DCHECK(site->SitePointsToLiteral()); - - ElementsKind boilerplate_elements_kind = - boilerplate_object->GetElementsKind(); + ElementsKind boilerplate_elements_kind = expr->constant_elements_kind(); + if (!boilerplate_object.is_null()) { + boilerplate_elements_kind = boilerplate_object->GetElementsKind(); + } // Check whether to use fast or slow deep-copying for boilerplate. int max_properties = kMaxFastLiteralProperties; - if (IsFastLiteral(boilerplate_object, - kMaxFastLiteralDepth, + if (!boilerplate_object.is_null() && + IsFastLiteral(boilerplate_object, kMaxFastLiteralDepth, &max_properties)) { + DCHECK(site->SitePointsToLiteral()); AllocationSiteUsageContext site_context(isolate(), site, false); site_context.EnterNewScope(); literal = BuildFastLiteral(boilerplate_object, &site_context); site_context.ExitScope(site, boilerplate_object); } else { NoObservableSideEffectsScope no_effects(this); - // Boilerplate already exists and constant elements are never accessed, - // pass an empty fixed array to the runtime function instead. - Handle constants = isolate()->factory()->empty_fixed_array(); + Handle constants = expr->constant_elements(); int literal_index = expr->literal_index(); int flags = expr->ComputeFlags(true); @@ -6108,7 +6082,9 @@ void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { literal = Add(Runtime::FunctionForId(function_id), 4); // Register to deopt if the boilerplate ElementsKind changes. - top_info()->dependencies()->AssumeTransitionStable(site); + if (!site.is_null()) { + top_info()->dependencies()->AssumeTransitionStable(site); + } } // The array is expected in the bailout environment during computation @@ -6140,9 +6116,8 @@ void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { case FAST_HOLEY_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: { - HStoreKeyed* instr = Add(elements, key, value, nullptr, - boilerplate_elements_kind); - instr->SetUninitialized(uninitialized); + Add(elements, key, value, nullptr, + boilerplate_elements_kind); break; } default: diff --git a/deps/v8/src/runtime/runtime-literals.cc b/deps/v8/src/runtime/runtime-literals.cc index e73095720eb9cd..d1e4e4670ec86e 100644 --- a/deps/v8/src/runtime/runtime-literals.cc +++ b/deps/v8/src/runtime/runtime-literals.cc @@ -138,7 +138,7 @@ MUST_USE_RESULT static MaybeHandle CreateObjectLiteralBoilerplate( } -MaybeHandle Runtime::CreateArrayLiteralBoilerplate( +static MaybeHandle CreateArrayLiteralBoilerplate( Isolate* isolate, Handle literals, Handle elements, bool is_strong) { // Create the JSArray. @@ -225,8 +225,8 @@ MUST_USE_RESULT static MaybeHandle CreateLiteralBoilerplate( return CreateObjectLiteralBoilerplate(isolate, literals, elements, false, kHasNoFunctionLiteral, is_strong); case CompileTimeValue::ARRAY_LITERAL: - return Runtime::CreateArrayLiteralBoilerplate(isolate, literals, - elements, is_strong); + return CreateArrayLiteralBoilerplate(isolate, literals, + elements, is_strong); default: UNREACHABLE(); return MaybeHandle(); @@ -318,8 +318,7 @@ MUST_USE_RESULT static MaybeHandle GetLiteralAllocationSite( Handle boilerplate; ASSIGN_RETURN_ON_EXCEPTION( isolate, boilerplate, - Runtime::CreateArrayLiteralBoilerplate(isolate, literals, elements, - is_strong), + CreateArrayLiteralBoilerplate(isolate, literals, elements, is_strong), AllocationSite); AllocationSiteCreationContext creation_context(isolate); diff --git a/deps/v8/src/runtime/runtime.h b/deps/v8/src/runtime/runtime.h index 7019c3bf041907..36412d2ffc08f1 100644 --- a/deps/v8/src/runtime/runtime.h +++ b/deps/v8/src/runtime/runtime.h @@ -1148,11 +1148,6 @@ class Runtime : public AllStatic { ElementsKind* fixed_elements_kind, size_t* element_size); - // Used in runtime.cc and hydrogen's VisitArrayLiteral. - MUST_USE_RESULT static MaybeHandle CreateArrayLiteralBoilerplate( - Isolate* isolate, Handle literals, - Handle elements, bool is_strong); - static MaybeHandle GetInternalProperties(Isolate* isolate, Handle); }; From a855b300d5fc25a6a6ac5e352d595ebcc53af583 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Wed, 13 Jul 2016 11:18:31 -0400 Subject: [PATCH 15/34] cluster: remove bind() and self MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit removes the use of self and bind() from the cluster module in favor of arrow functions. PR-URL: https://github.com/nodejs/node/pull/7710 Reviewed-By: Michaël Zasso Reviewed-By: Santiago Gimeno Reviewed-By: Minwoo Jung --- lib/cluster.js | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/lib/cluster.js b/lib/cluster.js index 8462ec34fc9aeb..5396573c3597a4 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -127,12 +127,11 @@ function RoundRobinHandle(key, address, port, addressType, backlog, fd) { else this.server.listen(address); // UNIX socket path. - var self = this; - this.server.once('listening', function() { - self.handle = self.server._handle; - self.handle.onconnection = self.distribute.bind(self); - self.server._handle = null; - self.server = null; + this.server.once('listening', () => { + this.handle = this.server._handle; + this.handle.onconnection = (err, handle) => this.distribute(err, handle); + this.server._handle = null; + this.server = null; }); } @@ -140,18 +139,17 @@ RoundRobinHandle.prototype.add = function(worker, send) { assert(worker.id in this.all === false); this.all[worker.id] = worker; - var self = this; - function done() { - if (self.handle.getsockname) { + const done = () => { + if (this.handle.getsockname) { var out = {}; - self.handle.getsockname(out); + this.handle.getsockname(out); // TODO(bnoordhuis) Check err. send(null, { sockname: out }, null); } else { send(null, null, null); // UNIX socket. } - self.handoff(worker); // In case there are connections pending. - } + this.handoff(worker); // In case there are connections pending. + }; if (this.server === null) return done(); // Still busy binding. @@ -193,13 +191,13 @@ RoundRobinHandle.prototype.handoff = function(worker) { return; } var message = { act: 'newconn', key: this.key }; - var self = this; - sendHelper(worker.process, message, handle, function(reply) { + + sendHelper(worker.process, message, handle, (reply) => { if (reply.accepted) handle.close(); else - self.distribute(0, handle); // Worker is shutting down. Send to another. - self.handoff(worker); + this.distribute(0, handle); // Worker is shutting down. Send to another. + this.handoff(worker); }); }; @@ -414,7 +412,7 @@ function masterInit() { cluster.disconnect = function(cb) { var workers = Object.keys(cluster.workers); if (workers.length === 0) { - process.nextTick(intercom.emit.bind(intercom, 'disconnect')); + process.nextTick(() => intercom.emit('disconnect')); } else { for (var key in workers) { key = workers[key]; @@ -436,7 +434,7 @@ function masterInit() { signo = signo || 'SIGTERM'; var proc = this.process; if (this.isConnected()) { - this.once('disconnect', proc.kill.bind(proc, signo)); + this.once('disconnect', () => proc.kill(signo)); this.disconnect(); return; } From 46b9ef6db22887058f1d4bddfc6a1271e52f712a Mon Sep 17 00:00:00 2001 From: Kevin Donahue Date: Thu, 14 Jul 2016 12:55:31 -0400 Subject: [PATCH 16/34] doc: fix typo in stream doc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix small typo in Buffering section of stream doc. PR-URL: https://github.com/nodejs/node/pull/7738 Reviewed-By: Brian White Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Michaël Zasso Reviewed-By: Anna Henningsen --- doc/api/stream.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index 4be7f3c3f07880..124b1490fd6f29 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -87,7 +87,7 @@ total size of the internal write buffer is below the threshold set by the size of the internal buffer reaches or exceeds the `highWaterMark`, `false` will be returned. -A key goal of the `stream` API, an in particular the [`stream.pipe()`] method, +A key goal of the `stream` API, and in particular the [`stream.pipe()`] method, is to limit the buffering of data to acceptable levels such that sources and destinations of differing speeds will not overwhelm the available memory. From c726ffb29ca7a4a58960ba853f304407a950ef40 Mon Sep 17 00:00:00 2001 From: Lance Ball Date: Mon, 25 Apr 2016 15:48:50 -0400 Subject: [PATCH 17/34] doc: Warn against `uncaughtException` dependency. State in the documentation that `uncaughtException` is not a reliable way to restart a crashed application, and clarify that an application may crash in ways that do not trigger this event. Use a documented synchronous function in example code. Fixes: https://github.com/nodejs/node/issues/6223 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: James M Snell PR-URL: https://github.com/nodejs/node/pull/6378 --- doc/api/process.md | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/doc/api/process.md b/doc/api/process.md index d2f101419d6d48..6472f7cfc84ca1 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -149,10 +149,11 @@ most convenient for scripts). added: v0.1.18 --> -The `'uncaughtException'` event is emitted when an exception bubbles all the -way back to the event loop. By default, Node.js handles such exceptions by -printing the stack trace to `stderr` and exiting. Adding a handler for the -`'uncaughtException'` event overrides this default behavior. +The `'uncaughtException'` event is emitted when an uncaught JavaScript +exception bubbles all the way back to the event loop. By default, Node.js +handles such exceptions by printing the stack trace to `stderr` and exiting. +Adding a handler for the `'uncaughtException'` event overrides this default +behavior. The listener function is called with the `Error` object passed as the only argument. @@ -161,7 +162,7 @@ For example: ```js process.on('uncaughtException', (err) => { - console.log(`Caught exception: ${err}`); + fs.writeSync(1, `Caught exception: ${err}`); }); setTimeout(() => { @@ -192,8 +193,12 @@ times nothing happens - but the 10th time, the system becomes corrupted. The correct use of `'uncaughtException'` is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting -down the process. It is not safe to resume normal operation after -`'uncaughtException'`. +down the process. **It is not safe to resume normal operation after +`'uncaughtException'`.** + +To restart a crashed application in a more reliable way, whether `uncaughtException` +is emitted or not, an external monitor should be employed in a separate process +to detect application failures and recover or restart as needed. ### Event: 'unhandledRejection' The `'unhandledRejection`' event is emitted whenever a `Promise` is rejected and -no error handler is attached to the promise within a turn of the event loop. +no error handler is attached to the promise within a turn of the event loop. When programming with Promises, exceptions are encapsulated as "rejected promises". Rejections can be caught and handled using [`promise.catch()`][] and are propagated through a `Promise` chain. The `'unhandledRejection'` event is -useful for detecting and keeping track of promises that were rejected whose +useful for detecting and keeping track of promises that were rejected whose rejections have not yet been handled. The listener function is called with the following arguments: @@ -637,7 +642,7 @@ An example of this object looks like: SHLVL: '1', HOME: '/Users/maciej', LOGNAME: 'maciej', - _: '/usr/local/bin/node' + _: '/usr/local/bin/node' } ``` @@ -1108,10 +1113,10 @@ console.log(util.inspect(process.memoryUsage())); Will generate: ```js -{ +{ rss: 4935680, heapTotal: 1826816, - heapUsed: 650472 + heapUsed: 650472 } ``` From 9d9bd3cabbab1a2327843e65e0377affadb4dd43 Mon Sep 17 00:00:00 2001 From: Jeremy Whitlock Date: Thu, 23 Jul 2015 18:09:21 -0600 Subject: [PATCH 18/34] timers: fix processing of nested timers Whenever a timer is scheduled within another timer, there are a few known issues that we are fixing: * Whenever the timer being scheduled has the same timeout value as the outer timer, the newly created timer can fire on the same tick of the event loop instead of during the next tick of the event loop * Whenever a timer is added in another timer's callback, its underlying timer handle will be started with a timeout that is actually incorrect This commit consists of https://github.com/nodejs/node-v0.x-archive/pull/17203 and https://github.com/nodejs/node-v0.x-archive/pull/25763. Fixes: https://github.com/nodejs/node-v0.x-archive/issues/9333 Fixes: https://github.com/nodejs/node-v0.x-archive/issues/15447 Fixes: https://github.com/nodejs/node-v0.x-archive/issues/25607 Fixes: https://github.com/nodejs/node/issues/5426 PR-URL: https://github.com/nodejs/node/pull/3063 --- lib/timers.js | 8 +- test/common.js | 7 ++ .../parallel/test-timers-blocking-callback.js | 81 +++++++++++++++++++ test/parallel/test-timers-nested.js | 39 +++++++++ 4 files changed, 133 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-timers-blocking-callback.js create mode 100644 test/parallel/test-timers-nested.js diff --git a/lib/timers.js b/lib/timers.js index 9dbae32405cf6e..7379cfe3591e02 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -160,7 +160,7 @@ function listOnTimeout() { debug('timeout callback %d', msecs); var now = TimerWrap.now(); - debug('now: %s', now); + debug('now: %d', now); var diff, timer; while (timer = L.peek(list)) { @@ -169,7 +169,11 @@ function listOnTimeout() { // Check if this loop iteration is too early for the next timer. // This happens if there are more timers scheduled for later in the list. if (diff < msecs) { - this.start(msecs - diff, 0); + var timeRemaining = msecs - (TimerWrap.now() - timer._idleStart); + if (timeRemaining < 0) { + timeRemaining = 0; + } + this.start(timeRemaining, 0); debug('%d list wait because diff is %d', msecs, diff); return; } diff --git a/test/common.js b/test/common.js index f9d80ff1490e42..308411a13d3427 100644 --- a/test/common.js +++ b/test/common.js @@ -7,6 +7,7 @@ var os = require('os'); var child_process = require('child_process'); const stream = require('stream'); const util = require('util'); +const Timer = process.binding('timer_wrap').Timer; const testRoot = path.resolve(process.env.NODE_TEST_DIR || path.dirname(__filename)); @@ -484,3 +485,9 @@ exports.nodeProcessAborted = function nodeProcessAborted(exitCode, signal) { return expectedExitCodes.indexOf(exitCode) > -1; } }; + +exports.busyLoop = function busyLoop(time) { + var startTime = Timer.now(); + var stopTime = startTime + time; + while (Timer.now() < stopTime) {} +}; diff --git a/test/parallel/test-timers-blocking-callback.js b/test/parallel/test-timers-blocking-callback.js new file mode 100644 index 00000000000000..114c435a6af726 --- /dev/null +++ b/test/parallel/test-timers-blocking-callback.js @@ -0,0 +1,81 @@ +'use strict'; + +/* + * This is a regression test for https://github.com/joyent/node/issues/15447 + * and https://github.com/joyent/node/issues/9333. + * + * When a timer is added in another timer's callback, its underlying timer + * handle was started with a timeout that was actually incorrect. + * + * The reason was that the value that represents the current time was not + * updated between the time the original callback was called and the time + * the added timer was processed by timers.listOnTimeout. That lead the + * logic in timers.listOnTimeout to do an incorrect computation that made + * the added timer fire with a timeout of scheduledTimeout + + * timeSpentInCallback. + * + * This test makes sure that a timer added by another timer's callback + * fire with the expected timeout. + * + * It makes sure that it works when the timers list for a given timeout is + * empty (see testAddingTimerToEmptyTimersList) and when the timers list + * is not empty (see testAddingTimerToNonEmptyTimersList). + */ + +const assert = require('assert'); +const common = require('../common'); +const Timer = process.binding('timer_wrap').Timer; + +const TIMEOUT = 100; + +var nbBlockingCallbackCalls = 0; +var latestDelay = 0; +var timeCallbackScheduled = 0; + +function initTest() { + nbBlockingCallbackCalls = 0; + latestDelay = 0; + timeCallbackScheduled = 0; +} + +function blockingCallback(callback) { + ++nbBlockingCallbackCalls; + + if (nbBlockingCallbackCalls > 1) { + latestDelay = Timer.now() - timeCallbackScheduled; + // Even if timers can fire later than when they've been scheduled + // to fire, they should more than 50% later with a timeout of + // 100ms. Firing later than that would mean that we hit the regression + // highlighted in + // https://github.com/nodejs/node-v0.x-archive/issues/15447 and + // https://github.com/nodejs/node-v0.x-archive/issues/9333.. + assert(latestDelay < TIMEOUT * 1.5); + if (callback) + return callback(); + } else { + // block by busy-looping to trigger the issue + common.busyLoop(TIMEOUT); + + timeCallbackScheduled = Timer.now(); + setTimeout(blockingCallback, TIMEOUT); + } +} + +function testAddingTimerToEmptyTimersList(callback) { + initTest(); + // Call setTimeout just once to make sure the timers list is + // empty when blockingCallback is called. + setTimeout(blockingCallback.bind(null, callback), TIMEOUT); +} + +function testAddingTimerToNonEmptyTimersList() { + initTest(); + // Call setTimeout twice with the same timeout to make + // sure the timers list is not empty when blockingCallback is called. + setTimeout(blockingCallback, TIMEOUT); + setTimeout(blockingCallback, TIMEOUT); +} + +// Run the test for the empty timers list case, and then for the non-empty +// timers list one +testAddingTimerToEmptyTimersList(testAddingTimerToNonEmptyTimersList); diff --git a/test/parallel/test-timers-nested.js b/test/parallel/test-timers-nested.js new file mode 100644 index 00000000000000..17b397d33cd860 --- /dev/null +++ b/test/parallel/test-timers-nested.js @@ -0,0 +1,39 @@ +'use strict'; + +const assert = require('assert'); +const common = require('../common'); + +// Make sure we test 0ms timers, since they would had always wanted to run on +// the current tick, and greater than 0ms timers, for scenarios where the +// outer timer takes longer to complete than the delay of the nested timer. +// Since the process of recreating this is identical regardless of the timer +// delay, these scenarios are in one test. +const scenarios = [0, 100]; + +scenarios.forEach(function(delay) { + var nestedCalled = false; + + setTimeout(function A() { + // Create the nested timer with the same delay as the outer timer so that it + // gets added to the current list of timers being processed by + // listOnTimeout. + setTimeout(function B() { + nestedCalled = true; + }, delay); + + // Busy loop for the same timeout used for the nested timer to ensure that + // we are in fact expiring the nested timer. + common.busyLoop(delay); + + // The purpose of running this assert in nextTick is to make sure it runs + // after A but before the next iteration of the libuv event loop. + process.nextTick(function() { + assert.ok(!nestedCalled); + }); + + // Ensure that the nested callback is indeed called prior to process exit. + process.on('exit', function onExit() { + assert.ok(nestedCalled); + }); + }, delay); +}); From 669af6e6c8a1a58110ea123975ad26e19bde28c4 Mon Sep 17 00:00:00 2001 From: saadq Date: Thu, 14 Jul 2016 22:41:29 -0700 Subject: [PATCH 19/34] doc: fix inconsistencies in code style MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds missing semicolons, removes extra white space, and properly indents various code snippets in the documentation. Reviewed-By: Evan Lucas Reviewed-By: targos - Michaël Zasso PR-URL: https://github.com/nodejs/node/pull/7745 --- doc/api/assert.md | 4 ++-- doc/api/buffer.md | 2 +- doc/api/crypto.md | 2 +- doc/api/fs.md | 4 ++-- doc/api/http.md | 6 +++--- doc/api/https.md | 4 ++-- doc/api/path.md | 2 +- doc/api/readline.md | 6 +++--- doc/api/repl.md | 2 +- doc/api/stream.md | 8 ++++---- doc/api/util.md | 8 ++++---- 11 files changed, 24 insertions(+), 24 deletions(-) diff --git a/doc/api/assert.md b/doc/api/assert.md index e54e81d22e384e..bc5c0b833ae5aa 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -71,7 +71,7 @@ const obj3 = { a : { b : 1 } -} +}; const obj4 = Object.create(obj1); assert.deepEqual(obj1, obj1); @@ -230,7 +230,7 @@ const assert = require('assert'); assert.ifError(0); // OK assert.ifError(1); // Throws 1 -assert.ifError('error') // Throws 'error' +assert.ifError('error'); // Throws 'error' assert.ifError(new Error()); // Throws Error ``` diff --git a/doc/api/buffer.md b/doc/api/buffer.md index fb8065a645fdab..92908fd38b8177 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -247,7 +247,7 @@ Buffers can be iterated over using the ECMAScript 2015 (ES6) `for..of` syntax: const buf = Buffer.from([1, 2, 3]); for (var b of buf) - console.log(b) + console.log(b); // Prints: // 1 diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 2738b395e655a7..283f87ccbc9f09 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -236,7 +236,7 @@ var decrypted = ''; decipher.on('readable', () => { var data = decipher.read(); if (data) - decrypted += data.toString('utf8'); + decrypted += data.toString('utf8'); }); decipher.on('end', () => { console.log(decrypted); diff --git a/doc/api/fs.md b/doc/api/fs.md index 268b6db9b49b3d..e8b158ac5edbcb 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1022,12 +1022,12 @@ will be returned._ // OS X and Linux fs.open('', 'a+', (err, fd) => { // => [Error: EISDIR: illegal operation on a directory, open ] -}) +}); // Windows and FreeBSD fs.open('', 'a+', (err, fd) => { // => null, -}) +}); ``` ## fs.openSync(path, flags[, mode]) diff --git a/doc/api/http.md b/doc/api/http.md index 1a09e96395c7b8..2646d95c06592a 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -90,7 +90,7 @@ http.get({ agent: false // create a new agent just for this one request }, (res) => { // Do stuff with response -}) +}); ``` ### new Agent([options]) @@ -1451,8 +1451,8 @@ var req = http.request(options, (res) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { - console.log('No more data in response.') - }) + console.log('No more data in response.'); + }); }); req.on('error', (e) => { diff --git a/doc/api/https.md b/doc/api/https.md index c76f1ef837c9ab..620b6b36c74906 100644 --- a/doc/api/https.md +++ b/doc/api/https.md @@ -231,7 +231,7 @@ options.agent = new https.Agent(options); var req = https.request(options, (res) => { ... -} +}); ``` Alternatively, opt out of connection pooling by not using an `Agent`. @@ -251,7 +251,7 @@ var options = { var req = https.request(options, (res) => { ... -} +}); ``` [`Agent`]: #https_class_https_agent diff --git a/doc/api/path.md b/doc/api/path.md index f18ed52730623f..fd07cd6802df9a 100644 --- a/doc/api/path.md +++ b/doc/api/path.md @@ -234,7 +234,7 @@ path.format({ base : "file.txt", ext : ".txt", name : "file" -}) +}); // returns 'C:\\path\\dir\\file.txt' ``` diff --git a/doc/api/readline.md b/doc/api/readline.md index 385540908331c2..9025f6fe7da821 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -398,10 +398,10 @@ For instance: `[[substr1, substr2, ...], originalsubstring]`. ```js function completer(line) { - var completions = '.help .error .exit .quit .q'.split(' ') - var hits = completions.filter((c) => { return c.indexOf(line) == 0 }) + var completions = '.help .error .exit .quit .q'.split(' '); + var hits = completions.filter((c) => { return c.indexOf(line) == 0 }); // show all completions if none found - return [hits.length ? hits : completions, line] + return [hits.length ? hits : completions, line]; } ``` diff --git a/doc/api/repl.md b/doc/api/repl.md index 9d44a701fc379d..56efa5df5d79aa 100644 --- a/doc/api/repl.md +++ b/doc/api/repl.md @@ -492,7 +492,7 @@ net.createServer((socket) => { output: socket }).on('exit', () => { socket.end(); - }) + }); }).listen('/tmp/node-repl-sock'); net.createServer((socket) => { diff --git a/doc/api/stream.md b/doc/api/stream.md index 124b1490fd6f29..ad014a2a69b5bb 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -1227,9 +1227,9 @@ const Writable = require('stream').Writable; const myWritable = new Writable({ write(chunk, encoding, callback) { if (chunk.toString().indexOf('a') >= 0) { - callback(new Error('chunk is invalid')) + callback(new Error('chunk is invalid')); } else { - callback() + callback(); } } }); @@ -1252,9 +1252,9 @@ class MyWritable extends Writable { _write(chunk, encoding, callback) { if (chunk.toString().indexOf('a') >= 0) { - callback(new Error('chunk is invalid')) + callback(new Error('chunk is invalid')); } else { - callback() + callback(); } } } diff --git a/doc/api/util.md b/doc/api/util.md index 56ea9a474d8cb8..12849d1be8a917 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -145,14 +145,14 @@ const util = require('util'); const EventEmitter = require('events'); function MyStream() { - EventEmitter.call(this); + EventEmitter.call(this); } util.inherits(MyStream, EventEmitter); MyStream.prototype.write = function(data) { - this.emit('data', data); -} + this.emit('data', data); +}; const stream = new MyStream(); @@ -161,7 +161,7 @@ console.log(MyStream.super_ === EventEmitter); // true stream.on('data', (data) => { console.log(`Received data: "${data}"`); -}) +}); stream.write('It works!'); // Received data: "It works!" ``` From 17591c3964c310f149bdd6c2e2a4687b0dca4b7c Mon Sep 17 00:00:00 2001 From: cjihrig Date: Thu, 14 Jul 2016 11:26:35 -0400 Subject: [PATCH 20/34] test: s/assert.fail/common.fail as appropriate Many tests use assert.fail(null, null, msg) where it would be simpler to use common.fail(msg). This is largely because common.fail() is fairly new. This commit makes the replacement when applicable. PR-URL: https://github.com/nodejs/node/pull/7735 Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Ben Noordhuis Reviewed-By: Jeremiah Senkpiel --- test/internet/test-dgram-send-cb-quelches-error.js | 2 +- .../test-event-emitter-listeners-side-effects.js | 12 ++++++------ test/parallel/test-event-emitter-once.js | 4 ++-- ...http-client-reject-chunked-with-content-length.js | 2 +- test/parallel/test-http-client-reject-cr-no-lf.js | 2 +- test/parallel/test-http-createConnection.js | 2 +- test/parallel/test-http-double-content-length.js | 3 +-- test/parallel/test-http-localaddress-bind-error.js | 4 ++-- .../test-http-response-multi-content-length.js | 2 +- test/parallel/test-http-response-splitting.js | 2 +- ...http-server-reject-chunked-with-content-length.js | 4 ++-- test/parallel/test-http-server-reject-cr-no-lf.js | 4 ++-- test/parallel/test-https-localaddress-bind-error.js | 2 +- test/parallel/test-net-connect-immediate-destroy.js | 5 ++--- test/parallel/test-net-connect-paused-connection.js | 5 ++--- ...t-listen-close-server-callback-is-not-function.js | 8 +++----- test/parallel/test-net-listen-port-option.js | 4 ++-- ...ver-max-connections-close-makes-more-available.js | 4 ++-- test/parallel/test-net-write-slow.js | 5 ++--- test/parallel/test-path-parse-format.js | 4 ++-- test/parallel/test-process-exit-from-before-exit.js | 5 ++--- test/parallel/test-repl-reset-event.js | 2 +- test/parallel/test-repl-tab.js | 6 ++---- test/parallel/test-spawn-cmd-named-pipe.js | 2 +- .../test-stream2-base64-single-char-read-end.js | 4 ++-- test/parallel/test-tls-client-mindhsize.js | 2 +- test/sequential/test-child-process-emfile.js | 3 +-- 27 files changed, 47 insertions(+), 57 deletions(-) diff --git a/test/internet/test-dgram-send-cb-quelches-error.js b/test/internet/test-dgram-send-cb-quelches-error.js index 64b354c3eb3bfc..56612edead4fd2 100644 --- a/test/internet/test-dgram-send-cb-quelches-error.js +++ b/test/internet/test-dgram-send-cb-quelches-error.js @@ -28,7 +28,7 @@ function callbackOnly(err) { } function onEvent(err) { - assert.fail(null, null, 'Error should not be emitted if there is callback'); + common.fail('Error should not be emitted if there is callback'); } function onError(err) { diff --git a/test/parallel/test-event-emitter-listeners-side-effects.js b/test/parallel/test-event-emitter-listeners-side-effects.js index fec5a7a89767f6..1bed99f3641e98 100644 --- a/test/parallel/test-event-emitter-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-listeners-side-effects.js @@ -1,6 +1,6 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var EventEmitter = require('events').EventEmitter; @@ -14,12 +14,12 @@ assert(fl.length === 0); assert(!(e._events instanceof Object)); assert.deepStrictEqual(Object.keys(e._events), []); -e.on('foo', assert.fail); +e.on('foo', common.fail); fl = e.listeners('foo'); -assert(e._events.foo === assert.fail); +assert(e._events.foo === common.fail); assert(Array.isArray(fl)); assert(fl.length === 1); -assert(fl[0] === assert.fail); +assert(fl[0] === common.fail); e.listeners('bar'); @@ -28,12 +28,12 @@ fl = e.listeners('foo'); assert(Array.isArray(e._events.foo)); assert(e._events.foo.length === 2); -assert(e._events.foo[0] === assert.fail); +assert(e._events.foo[0] === common.fail); assert(e._events.foo[1] === assert.ok); assert(Array.isArray(fl)); assert(fl.length === 2); -assert(fl[0] === assert.fail); +assert(fl[0] === common.fail); assert(fl[1] === assert.ok); console.log('ok'); diff --git a/test/parallel/test-event-emitter-once.js b/test/parallel/test-event-emitter-once.js index d007ef663fdede..1df03d6660e145 100644 --- a/test/parallel/test-event-emitter-once.js +++ b/test/parallel/test-event-emitter-once.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -16,7 +16,7 @@ e.emit('hello', 'a', 'b'); e.emit('hello', 'a', 'b'); var remove = function() { - assert.fail(1, 0, 'once->foo should not be emitted', '!'); + common.fail('once->foo should not be emitted'); }; e.once('foo', remove); diff --git a/test/parallel/test-http-client-reject-chunked-with-content-length.js b/test/parallel/test-http-client-reject-chunked-with-content-length.js index 324ba004d58a7d..daa0591cd75506 100644 --- a/test/parallel/test-http-client-reject-chunked-with-content-length.js +++ b/test/parallel/test-http-client-reject-chunked-with-content-length.js @@ -18,7 +18,7 @@ server.listen(0, () => { // both a Content-Length header and a Transfer-Encoding: chunked // header, which is a violation of the HTTP spec. const req = http.get({port: server.address().port}, (res) => { - assert.fail(null, null, 'callback should not be called'); + common.fail('callback should not be called'); }); req.on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); diff --git a/test/parallel/test-http-client-reject-cr-no-lf.js b/test/parallel/test-http-client-reject-cr-no-lf.js index e396637aaa448d..4cabfa0107bbc8 100644 --- a/test/parallel/test-http-client-reject-cr-no-lf.js +++ b/test/parallel/test-http-client-reject-cr-no-lf.js @@ -17,7 +17,7 @@ server.listen(0, () => { // The callback should not be called because the server is sending a // header field that ends only in \r with no following \n const req = http.get({port: server.address().port}, (res) => { - assert.fail(null, null, 'callback should not be called'); + common.fail('callback should not be called'); }); req.on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); diff --git a/test/parallel/test-http-createConnection.js b/test/parallel/test-http-createConnection.js index 04d7f3dc0dc6cb..69592eb09ff487 100644 --- a/test/parallel/test-http-createConnection.js +++ b/test/parallel/test-http-createConnection.js @@ -21,7 +21,7 @@ const server = http.createServer(common.mustCall(function(req, res) { res.resume(); fn = common.mustCall(createConnectionError); http.get({ createConnection: fn }, function(res) { - assert.fail(null, null, 'Unexpected response callback'); + common.fail('Unexpected response callback'); }).on('error', common.mustCall(function(err) { assert.equal(err.message, 'Could not create socket'); server.close(); diff --git a/test/parallel/test-http-double-content-length.js b/test/parallel/test-http-double-content-length.js index ac70168601aaf5..a73cf49854ed35 100644 --- a/test/parallel/test-http-double-content-length.js +++ b/test/parallel/test-http-double-content-length.js @@ -23,8 +23,7 @@ server.listen(0, () => { // Send two content-length header values. headers: {'Content-Length': [1, 2]}}, (res) => { - assert.fail(null, null, 'an error should have occurred'); - server.close(); + common.fail('an error should have occurred'); } ); req.on('error', common.mustCall(() => { diff --git a/test/parallel/test-http-localaddress-bind-error.js b/test/parallel/test-http-localaddress-bind-error.js index 51605fab6aa10e..5b537b00e7ead7 100644 --- a/test/parallel/test-http-localaddress-bind-error.js +++ b/test/parallel/test-http-localaddress-bind-error.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -24,7 +24,7 @@ server.listen(0, '127.0.0.1', function() { method: 'GET', localAddress: invalidLocalAddress }, function(res) { - assert.fail(null, null, 'unexpectedly got response from server'); + common.fail('unexpectedly got response from server'); }).on('error', function(e) { console.log('client got error: ' + e.message); gotError = true; diff --git a/test/parallel/test-http-response-multi-content-length.js b/test/parallel/test-http-response-multi-content-length.js index dd6ad6a1cd4a0c..098061002b003c 100644 --- a/test/parallel/test-http-response-multi-content-length.js +++ b/test/parallel/test-http-response-multi-content-length.js @@ -19,7 +19,7 @@ const server = http.createServer((req, res) => { res.writeHead(200, {'content-length': [1, 2]}); break; default: - assert.fail(null, null, 'should never get here'); + common.fail('should never get here'); } res.end('ok'); }); diff --git a/test/parallel/test-http-response-splitting.js b/test/parallel/test-http-response-splitting.js index 07ced3fd146f9c..e4021e78317759 100644 --- a/test/parallel/test-http-response-splitting.js +++ b/test/parallel/test-http-response-splitting.js @@ -38,7 +38,7 @@ const server = http.createServer((req, res) => { })); break; default: - assert.fail(null, null, 'should not get to here.'); + common.fail('should not get to here.'); } if (count === 3) server.close(); diff --git a/test/parallel/test-http-server-reject-chunked-with-content-length.js b/test/parallel/test-http-server-reject-chunked-with-content-length.js index b3284c368546b5..d8697cd38cde72 100644 --- a/test/parallel/test-http-server-reject-chunked-with-content-length.js +++ b/test/parallel/test-http-server-reject-chunked-with-content-length.js @@ -10,7 +10,7 @@ const reqstr = 'POST / HTTP/1.1\r\n' + 'Transfer-Encoding: chunked\r\n\r\n'; const server = http.createServer((req, res) => { - assert.fail(null, null, 'callback should not be invoked'); + common.fail('callback should not be invoked'); }); server.on('clientError', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); @@ -25,7 +25,7 @@ server.listen(0, () => { client.on('data', (data) => { // Should not get to this point because the server should simply // close the connection without returning any data. - assert.fail(null, null, 'no data should be returned by the server'); + common.fail('no data should be returned by the server'); }); client.on('end', common.mustCall(() => {})); }); diff --git a/test/parallel/test-http-server-reject-cr-no-lf.js b/test/parallel/test-http-server-reject-cr-no-lf.js index 6c55dead96f19f..81a7208d982334 100644 --- a/test/parallel/test-http-server-reject-cr-no-lf.js +++ b/test/parallel/test-http-server-reject-cr-no-lf.js @@ -12,7 +12,7 @@ const str = 'GET / HTTP/1.1\r\n' + const server = http.createServer((req, res) => { - assert.fail(null, null, 'this should not be called'); + common.fail('this should not be called'); }); server.on('clientError', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); @@ -22,7 +22,7 @@ server.on('clientError', common.mustCall((err) => { server.listen(0, () => { const client = net.connect({port: server.address().port}, () => { client.on('data', (chunk) => { - assert.fail(null, null, 'this should not be called'); + common.fail('this should not be called'); }); client.on('end', common.mustCall(() => { server.close(); diff --git a/test/parallel/test-https-localaddress-bind-error.js b/test/parallel/test-https-localaddress-bind-error.js index 5e5f900c7a809b..1ce94a0ac0eaca 100644 --- a/test/parallel/test-https-localaddress-bind-error.js +++ b/test/parallel/test-https-localaddress-bind-error.js @@ -35,7 +35,7 @@ server.listen(0, '127.0.0.1', function() { method: 'GET', localAddress: invalidLocalAddress }, function(res) { - assert.fail(null, null, 'unexpectedly got response from server'); + common.fail('unexpectedly got response from server'); }).on('error', function(e) { console.log('client got error: ' + e.message); gotError = true; diff --git a/test/parallel/test-net-connect-immediate-destroy.js b/test/parallel/test-net-connect-immediate-destroy.js index 37dc4b2d9a2391..f8d22d92d0a985 100644 --- a/test/parallel/test-net-connect-immediate-destroy.js +++ b/test/parallel/test-net-connect-immediate-destroy.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const net = require('net'); -const socket = net.connect(common.PORT, common.localhostIPv4, assert.fail); -socket.on('error', assert.fail); +const socket = net.connect(common.PORT, common.localhostIPv4, common.fail); +socket.on('error', common.fail); socket.destroy(); diff --git a/test/parallel/test-net-connect-paused-connection.js b/test/parallel/test-net-connect-paused-connection.js index 857b287b62174f..8c0e1c93cfb208 100644 --- a/test/parallel/test-net-connect-paused-connection.js +++ b/test/parallel/test-net-connect-paused-connection.js @@ -1,6 +1,5 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var net = require('net'); @@ -10,6 +9,6 @@ net.createServer(function(conn) { net.connect(this.address().port, 'localhost').pause(); setTimeout(function() { - assert.fail(null, null, 'expected to exit'); + common.fail('expected to exit'); }, 1000).unref(); }).unref(); diff --git a/test/parallel/test-net-listen-close-server-callback-is-not-function.js b/test/parallel/test-net-listen-close-server-callback-is-not-function.js index b0fe8c2fe15b71..6fdb61e85dd4e0 100644 --- a/test/parallel/test-net-listen-close-server-callback-is-not-function.js +++ b/test/parallel/test-net-listen-close-server-callback-is-not-function.js @@ -1,18 +1,16 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var server = net.createServer(assert.fail); +var server = net.createServer(common.fail); var closeEvents = 0; server.on('close', function() { ++closeEvents; }); -server.listen(0, function() { - assert(false); -}); +server.listen(0, common.fail); server.close('bad argument'); diff --git a/test/parallel/test-net-listen-port-option.js b/test/parallel/test-net-listen-port-option.js index 18b256c973eaec..77c9cb42f0a930 100644 --- a/test/parallel/test-net-listen-port-option.js +++ b/test/parallel/test-net-listen-port-option.js @@ -17,12 +17,12 @@ net.Server().listen({ port: '' + common.PORT }, close); '-Infinity' ].forEach(function(port) { assert.throws(function() { - net.Server().listen({ port: port }, assert.fail); + net.Server().listen({ port: port }, common.fail); }, /"port" argument must be >= 0 and < 65536/i); }); [null, true, false].forEach(function(port) { assert.throws(function() { - net.Server().listen({ port: port }, assert.fail); + net.Server().listen({ port: port }, common.fail); }, /invalid listen argument/i); }); diff --git a/test/parallel/test-net-server-max-connections-close-makes-more-available.js b/test/parallel/test-net-server-max-connections-close-makes-more-available.js index 08e5bbc2bc74b6..2f8bee1a8d68d9 100644 --- a/test/parallel/test-net-server-max-connections-close-makes-more-available.js +++ b/test/parallel/test-net-server-max-connections-close-makes-more-available.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -86,5 +86,5 @@ process.on('exit', function() { process.on('unhandledRejection', function() { console.error('promise rejected'); - assert.fail(null, null, 'A promise in the chain rejected'); + common.fail('A promise in the chain rejected'); }); diff --git a/test/parallel/test-net-write-slow.js b/test/parallel/test-net-write-slow.js index 9acc1b31c37430..7abee7d0e7dffb 100644 --- a/test/parallel/test-net-write-slow.js +++ b/test/parallel/test-net-write-slow.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -13,8 +13,7 @@ var server = net.createServer(function(socket) { socket.setNoDelay(); socket.setTimeout(9999); socket.on('timeout', function() { - assert.fail(null, null, 'flushed: ' + flushed + - ', received: ' + received + '/' + SIZE * N); + common.fail(`flushed: ${flushed}, received: ${received}/${SIZE * N}`); }); for (var i = 0; i < N; ++i) { diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index a42794790d1459..2db4c27dce072a 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const path = require('path'); @@ -169,7 +169,7 @@ function checkErrors(path) { return; } - assert.fail(null, null, 'should have thrown'); + common.fail('should have thrown'); }); } diff --git a/test/parallel/test-process-exit-from-before-exit.js b/test/parallel/test-process-exit-from-before-exit.js index 30d358cb76da9d..b37df0a5bd340d 100644 --- a/test/parallel/test-process-exit-from-before-exit.js +++ b/test/parallel/test-process-exit-from-before-exit.js @@ -1,9 +1,8 @@ 'use strict'; -var assert = require('assert'); var common = require('../common'); process.on('beforeExit', common.mustCall(function() { - setTimeout(assert.fail, 5); + setTimeout(common.fail, 5); process.exit(0); // Should execute immediately even if we schedule new work. - assert.fail(); + common.fail(); })); diff --git a/test/parallel/test-repl-reset-event.js b/test/parallel/test-repl-reset-event.js index 0bd43dcd6c370e..eee61ac17356f4 100644 --- a/test/parallel/test-repl-reset-event.js +++ b/test/parallel/test-repl-reset-event.js @@ -42,7 +42,7 @@ function testResetGlobal(cb) { } var timeout = setTimeout(function() { - assert.fail(null, null, 'Timeout, REPL did not emit reset events'); + common.fail('Timeout, REPL did not emit reset events'); }, 5000); testReset(function() { diff --git a/test/parallel/test-repl-tab.js b/test/parallel/test-repl-tab.js index 6474d8e4088167..c075b8d4f1125f 100644 --- a/test/parallel/test-repl-tab.js +++ b/test/parallel/test-repl-tab.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var repl = require('repl'); var zlib = require('zlib'); @@ -10,9 +10,7 @@ var testMe = repl.start('', putIn, function(cmd, context, filename, callback) { callback(null, cmd); }); -testMe._domain.on('error', function(e) { - assert.fail(); -}); +testMe._domain.on('error', common.fail); testMe.complete('', function(err, results) { assert.equal(err, null); diff --git a/test/parallel/test-spawn-cmd-named-pipe.js b/test/parallel/test-spawn-cmd-named-pipe.js index fafc5b2167ba59..c463bf6140053f 100644 --- a/test/parallel/test-spawn-cmd-named-pipe.js +++ b/test/parallel/test-spawn-cmd-named-pipe.js @@ -39,7 +39,7 @@ if (!process.argv[2]) { const comspec = process.env['comspec']; if (!comspec || comspec.length === 0) { - assert.fail(null, null, 'Failed to get COMSPEC'); + common.fail('Failed to get COMSPEC'); } const args = ['/c', process.execPath, __filename, 'child', diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js index 07244dc0fbbf78..50bafc3737385d 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var R = require('_stream_readable'); var W = require('_stream_writable'); var assert = require('assert'); @@ -33,5 +33,5 @@ src.on('end', function() { src.pipe(dst); timeout = setTimeout(function() { - assert.fail(null, null, 'timed out waiting for _write'); + common.fail('timed out waiting for _write'); }, 100); diff --git a/test/parallel/test-tls-client-mindhsize.js b/test/parallel/test-tls-client-mindhsize.js index 0012dec4d07d58..9956c971ffbbf3 100644 --- a/test/parallel/test-tls-client-mindhsize.js +++ b/test/parallel/test-tls-client-mindhsize.js @@ -75,7 +75,7 @@ function testDHE2048() { testDHE1024(); -assert.throws(() => test(512, true, assert.fail), +assert.throws(() => test(512, true, common.fail), /DH parameter is less than 1024 bits/); [0, -1, -Infinity, NaN].forEach((minDHSize) => { diff --git a/test/sequential/test-child-process-emfile.js b/test/sequential/test-child-process-emfile.js index f186db54016a40..8f59842f99563b 100644 --- a/test/sequential/test-child-process-emfile.js +++ b/test/sequential/test-child-process-emfile.js @@ -44,8 +44,7 @@ proc.on('error', common.mustCall(function(err) { })); proc.on('exit', function() { - const msg = '"exit" should not be emitted (the process never spawned!)'; - assert.fail(null, null, msg); + common.fail('"exit" should not be emitted (the process never spawned!)'); }); // close one fd for LSan From 3bd40ff5ca069cc0a2e3275c12c3ed948195038f Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Sat, 16 Jul 2016 00:04:07 -0400 Subject: [PATCH 21/34] deps: no /safeseh for ml64.exe `ml64.exe` doesn't support `/safeseh` option. Do not attempt to use it if `target_arch=="x64"`. See: https://msdn.microsoft.com/en-us/library/s0ksfwcf.aspx PR-URL: https://github.com/nodejs/node/pull/7759 Reviewed-By: Ben Noordhuis Reviewed-By: Robert Jefe Lindstaedt Reviewed-By: Minwoo Jung --- deps/openssl/openssl.gyp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/deps/openssl/openssl.gyp b/deps/openssl/openssl.gyp index b25efe60d5e8e6..ae5c980e06a5ab 100644 --- a/deps/openssl/openssl.gyp +++ b/deps/openssl/openssl.gyp @@ -121,15 +121,17 @@ }], # end of conditions of openssl_no_asm ['OS=="win"', { 'defines' : ['<@(openssl_defines_all_win)'], + }, { + 'defines' : ['<@(openssl_defines_all_non_win)'] + }], + ['target_arch=="ia32" and OS=="win"', { 'msvs_settings': { 'MASM': { # Use /safeseh, see commit: 01fa5ee 'UseSafeExceptionHandlers': 'true', }, }, - }, { - 'defines' : ['<@(openssl_defines_all_non_win)'] - }] + }], ], 'include_dirs': ['<@(openssl_include_dirs)'], 'direct_dependent_settings': { From 60c459c90f204e161f8404540c5f30d1df026365 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 9 Jul 2016 22:27:38 +0200 Subject: [PATCH 22/34] util: inspect boxed symbols like other primitives MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inspect boxed symbol objects in the same way other boxed primitives are inspected. Fixes: https://github.com/nodejs/node/issues/7639 PR-URL: https://github.com/nodejs/node/pull/7641 Reviewed-By: Michaël Zasso Reviewed-By: Ben Noordhuis Reviewed-By: Benjamin Gruenbaum Reviewed-By: Colin Ihrig Reviewed-By: Sakthipriyan Vairamani --- lib/util.js | 4 ++++ test/parallel/test-util-inspect.js | 1 + 2 files changed, 5 insertions(+) diff --git a/lib/util.js b/lib/util.js index d4b87eaeb0a58f..bb588cf475e236 100644 --- a/lib/util.js +++ b/lib/util.js @@ -413,6 +413,10 @@ function formatValue(ctx, value, recurseTimes) { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[String: ' + formatted + ']', 'string'); } + if (typeof raw === 'symbol') { + formatted = formatPrimitiveNoColor(ctx, raw); + return ctx.stylize('[Symbol: ' + formatted + ']', 'symbol'); + } if (typeof raw === 'number') { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[Number: ' + formatted + ']', 'number'); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index b25a3190c94d6c..0817f54a9bdc1f 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -474,6 +474,7 @@ test_lines({ // test boxed primitives output the correct values assert.equal(util.inspect(new String('test')), '[String: \'test\']'); +assert.equal(util.inspect(Object(Symbol('test'))), '[Symbol: Symbol(test)]'); assert.equal(util.inspect(new Boolean(false)), '[Boolean: false]'); assert.equal(util.inspect(new Boolean(true)), '[Boolean: true]'); assert.equal(util.inspect(new Number(0)), '[Number: 0]'); From ba6ab7cb3776146e45effdf097bd16744944ed6b Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Wed, 6 Jul 2016 21:57:39 -0700 Subject: [PATCH 23/34] buffer: optimize hex_decode PR-URL: https://github.com/nodejs/node/pull/7602 Reviewed-By: Anna Henningsen --- benchmark/buffers/buffer-hex.js | 26 +++++++++++++++++ src/string_bytes.cc | 37 ++++++++++++++++--------- test/parallel/test-buffer-badhex.js | 43 +++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 13 deletions(-) create mode 100644 benchmark/buffers/buffer-hex.js create mode 100644 test/parallel/test-buffer-badhex.js diff --git a/benchmark/buffers/buffer-hex.js b/benchmark/buffers/buffer-hex.js new file mode 100644 index 00000000000000..d05bb832b3068c --- /dev/null +++ b/benchmark/buffers/buffer-hex.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + len: [0, 1, 64, 1024], + n: [1e7] +}); + +function main(conf) { + const len = conf.len | 0; + const n = conf.n | 0; + const buf = Buffer.alloc(len); + + for (let i = 0; i < buf.length; i++) + buf[i] = i & 0xff; + + const hex = buf.toString('hex'); + + bench.start(); + + for (let i = 0; i < n; i += 1) + Buffer.from(hex, 'hex'); + + bench.end(n); +} diff --git a/src/string_bytes.cc b/src/string_bytes.cc index 882340ae048bf3..935c6f178112c4 100644 --- a/src/string_bytes.cc +++ b/src/string_bytes.cc @@ -143,16 +143,27 @@ const int8_t unbase64_table[256] = }; -template -unsigned hex2bin(TypeName c) { - if (c >= '0' && c <= '9') - return c - '0'; - if (c >= 'A' && c <= 'F') - return 10 + (c - 'A'); - if (c >= 'a' && c <= 'f') - return 10 + (c - 'a'); - return static_cast(-1); -} +static const int8_t unhex_table[256] = + { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }; + +#define unhex(x) \ + static_cast(unhex_table[static_cast(x)]) template @@ -162,11 +173,11 @@ size_t hex_decode(char* buf, const size_t srcLen) { size_t i; for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { - unsigned a = hex2bin(src[i * 2 + 0]); - unsigned b = hex2bin(src[i * 2 + 1]); + unsigned a = unhex(src[i * 2 + 0]); + unsigned b = unhex(src[i * 2 + 1]); if (!~a || !~b) return i; - buf[i] = a * 16 + b; + buf[i] = (a << 4) | b; } return i; diff --git a/test/parallel/test-buffer-badhex.js b/test/parallel/test-buffer-badhex.js new file mode 100644 index 00000000000000..3611ba3a09cdae --- /dev/null +++ b/test/parallel/test-buffer-badhex.js @@ -0,0 +1,43 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const Buffer = require('buffer').Buffer; + +// Test hex strings and bad hex strings +{ + const buf1 = Buffer.alloc(4); + assert.strictEqual(buf1.length, 4); + assert.deepStrictEqual(buf1, new Buffer([0, 0, 0, 0])); + assert.strictEqual(buf1.write('abcdxx', 0, 'hex'), 2); + assert.deepStrictEqual(buf1, new Buffer([0xab, 0xcd, 0x00, 0x00])); + assert.strictEqual(buf1.toString('hex'), 'abcd0000'); + assert.strictEqual(buf1.write('abcdef01', 0, 'hex'), 4); + assert.deepStrictEqual(buf1, new Buffer([0xab, 0xcd, 0xef, 0x01])); + assert.strictEqual(buf1.toString('hex'), 'abcdef01'); + + const buf2 = Buffer.from(buf1.toString('hex'), 'hex'); + assert.strictEqual(buf1.toString('hex'), buf2.toString('hex')); + + const buf3 = Buffer.alloc(5); + assert.strictEqual(buf3.write('abcdxx', 1, 'hex'), 2); + assert.strictEqual(buf3.toString('hex'), '00abcd0000'); + + const buf4 = Buffer.alloc(4); + assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0])); + assert.strictEqual(buf4.write('xxabcd', 0, 'hex'), 0); + assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0])); + assert.strictEqual(buf4.write('xxab', 1, 'hex'), 0); + assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0])); + assert.strictEqual(buf4.write('cdxxab', 0, 'hex'), 1); + assert.deepStrictEqual(buf4, new Buffer([0xcd, 0, 0, 0])); + + const buf5 = Buffer.alloc(256); + for (let i = 0; i < 256; i++) + buf5[i] = i; + + const hex = buf5.toString('hex'); + assert.deepStrictEqual(Buffer.from(hex, 'hex'), buf5); + + const badHex = hex.slice(0, 256) + 'xx' + hex.slice(256, 510); + assert.deepStrictEqual(Buffer.from(badHex, 'hex'), buf5.slice(0, 128)); +} From aa045cd22656bf99f8ec0dc46bc2a79ec08265c4 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 13 Jul 2016 09:12:59 -0700 Subject: [PATCH 24/34] test: fix flaky test-http-server-consumed-timeout Using identical timeout values appears to have eliminated the flakiness in the test. Fixes: https://github.com/nodejs/node/issues/7643 PR-URL: https://github.com/nodejs/node/pull/7717 Reviewed-By: Fedor Indutny --- test/parallel/test-http-server-consumed-timeout.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-http-server-consumed-timeout.js b/test/parallel/test-http-server-consumed-timeout.js index 362b052ee78d58..799992e2c4a6ba 100644 --- a/test/parallel/test-http-server-consumed-timeout.js +++ b/test/parallel/test-http-server-consumed-timeout.js @@ -1,7 +1,6 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const http = require('http'); const server = http.createServer((req, res) => { @@ -11,7 +10,7 @@ const server = http.createServer((req, res) => { res.flushHeaders(); req.setTimeout(common.platformTimeout(200), () => { - assert(false, 'Should not happen'); + common.fail('Request timeout should not fire'); }); req.resume(); req.once('end', common.mustCall(() => { @@ -30,7 +29,7 @@ server.listen(0, common.mustCall(() => { setTimeout(() => { clearInterval(interval); req.end(); - }, common.platformTimeout(400)); + }, common.platformTimeout(200)); }); req.write('.'); })); From f7d3af67aadb50b20d4c1cb7e62adff184ce74f7 Mon Sep 17 00:00:00 2001 From: "Italo A. Casas" Date: Mon, 13 Jun 2016 10:32:44 -0400 Subject: [PATCH 25/34] doc: add `added:` information for stream Ref: https://github.com/nodejs/node/issues/6578 PR-URL: https://github.com/nodejs/node/pull/7287 Reviewed-By: Anna Henningsen Reviewed-By: Claudio Rodriguez --- doc/api/stream.md | 93 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 90 insertions(+), 3 deletions(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index ad014a2a69b5bb..2afdbf51fa25c9 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -116,7 +116,7 @@ const server = http.createServer( (req, res) => { // req is an http.IncomingMessage, which is a Readable Stream // res is an http.ServerResponse, which is a Writable Stream - var body = ''; + let body = ''; // Get the data as utf8 strings. // If an encoding is not set, Buffer objects will be received. req.setEncoding('utf8'); @@ -205,10 +205,16 @@ myStream.end('done writing data'); ``` #### Class: stream.Writable + ##### Event: 'close' + The `'close'` event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates @@ -217,6 +223,9 @@ that no more events will be emitted, and no further computation will occur. Not all Writable streams will emit the `'close'` event. ##### Event: 'drain' + If a call to [`stream.write(chunk)`][stream-write] returns `false`, the `'drain'` event will be emitted when it is appropriate to resume writing data @@ -226,7 +235,7 @@ to the stream. // Write the data to the supplied writable stream one million times. // Be attentive to back-pressure. function writeOneMillionTimes(writer, data, encoding, callback) { - var i = 1000000; + let i = 1000000; write(); function write() { var ok = true; @@ -251,6 +260,9 @@ function writeOneMillionTimes(writer, data, encoding, callback) { ``` ##### Event: 'error' + * {Error} @@ -260,6 +272,9 @@ data. The listener callback is passed a single `Error` argument when called. *Note*: The stream is not closed when the `'error'` event is emitted. ##### Event: 'finish' + The `'finish'` event is emitted after the [`stream.end()`][stream-end] method has been called, and all data has been flushed to the underlying system. @@ -276,6 +291,9 @@ writer.on('finish', () => { ``` ##### Event: 'pipe' + * `src` {stream.Readable} source stream that is piping to this writable @@ -293,6 +311,9 @@ reader.pipe(writer); ``` ##### Event: 'unpipe' + * `src` {[Readable][] Stream} The source stream that [unpiped][`stream.unpipe()`] this writable @@ -313,6 +334,9 @@ reader.unpipe(writer); ``` ##### writable.cork() + The `writable.cork()` method forces all written data to be buffered in memory. The buffered data will be flushed when either the [`stream.uncork()`][] or @@ -325,6 +349,9 @@ implementations that implement the `writable._writev()` method can perform buffered writes in a more optimized manner. ##### writable.end([chunk][, encoding][, callback]) + * `chunk` {String|Buffer|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string or a `Buffer`. For object mode @@ -350,6 +377,9 @@ file.end('world!'); ``` ##### writable.setDefaultEncoding(encoding) + * `encoding` {String} The new default encoding * Return: `this` @@ -358,6 +388,9 @@ The `writable.setDefaultEncoding()` method sets the default `encoding` for a [Writable][] stream. ##### writable.uncork() + The `writable.uncork()` method flushes all data buffered since [`stream.cork()`][] was called. @@ -391,6 +424,9 @@ process.nextTick(() => { ``` ##### writable.write(chunk[, encoding][, callback]) + * `chunk` {String|Buffer} The data to write * `encoding` {String} The encoding, if `chunk` is a String @@ -516,10 +552,16 @@ require more fine-grained control over the transfer and generation of data can use the [`EventEmitter`][] and `readable.pause()`/`readable.resume()` APIs. #### Class: stream.Readable + ##### Event: 'close' + The `'close'` event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates @@ -528,6 +570,9 @@ that no more events will be emitted, and no further computation will occur. Not all [Readable][] streams will emit the `'close'` event. ##### Event: 'data' + * `chunk` {Buffer|String|any} The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. @@ -558,6 +603,9 @@ readable.on('data', (chunk) => { ``` ##### Event: 'end' + The `'end'` event is emitted when there is no more data to be consumed from the stream. @@ -578,6 +626,9 @@ readable.on('end', () => { ``` ##### Event: 'error' + * {Error} @@ -589,6 +640,9 @@ to push an invalid chunk of data. The listener callback will be passed a single `Error` object. ##### Event: 'readable' + The `'readable'` event is emitted when there is data available to be read from the stream. In some cases, attaching a listener for the `'readable'` event will @@ -632,6 +686,9 @@ end preferred over the use of the `'readable'` event. ##### readable.isPaused() + * Return: {Boolean} @@ -651,6 +708,9 @@ readable.isPaused() // === false ``` ##### readable.pause() + * Return: `this` @@ -672,6 +732,9 @@ readable.on('data', (chunk) => { ``` ##### readable.pipe(destination[, options]) + * `destination` {stream.Writable} The destination for writing data * `options` {Object} Pipe options @@ -727,6 +790,9 @@ never closed until the Node.js process exits, regardless of the specified options. ##### readable.read([size]) + * `size` {Number} Optional argument to specify how much data to read. * Return {String|Buffer|Null} @@ -774,6 +840,9 @@ event will also be emitted. event has been emitted will return `null`. No runtime error will be raised. ##### readable.resume() + * Return: `this` @@ -793,6 +862,9 @@ getReadableStreamSomehow() ``` ##### readable.setEncoding(encoding) + * `encoding` {String} The encoding to use. * Return: `this` @@ -825,6 +897,9 @@ readable.on('data', (chunk) => { ``` ##### readable.unpipe([destination]) + * `destination` {stream.Writable} Optional specific stream to unpipe @@ -851,6 +926,9 @@ setTimeout(() => { ``` ##### readable.unshift(chunk) + * `chunk` {Buffer|String} Chunk of data to unshift onto the read queue @@ -911,6 +989,9 @@ appropriately, however it is best to simply avoid calling `readable.unshift()` while in the process of performing a read. ##### readable.wrap(stream) + * `stream` {Stream} An "old style" readable stream @@ -943,6 +1024,9 @@ myReader.on('readable', () => { ### Duplex and Transform Streams #### Class: stream.Duplex + @@ -956,6 +1040,9 @@ Examples of Duplex streams include: * [crypto streams][crypto] #### Class: stream.Transform + @@ -1579,7 +1666,7 @@ For Duplex streams, `objectMode` can be set exclusively for either the Readable or Writable side using the `readableObjectMode` and `writableObjectMode` options respectively. -In the following example, for instance, a new Transform stream (which is a +In the following example, for instance, a new Transform stream (which is a type of [Duplex][] stream) is created that has an object mode Writable side that accepts JavaScript numbers that are converted to hexidecimal strings on the Readable side. From 06bfb9e93c8643503d0c9bd9fceedc0a426e87ad Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 13 Jul 2016 16:06:18 +0200 Subject: [PATCH 26/34] src: fix handle leak in Buffer::New() Fix handle leaks in Buffer::New() and Buffer::Copy() by creating the handle scope before looking up the env with Environment::GetCurrent(). Environment::GetCurrent() calls v8::Isolate::GetCurrentContext(), which creates a handle in the current scope, i.e., the scope created by the caller of Buffer::New() or Buffer::Copy(). PR-URL: https://github.com/nodejs/node/pull/7711 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Trevor Norris --- src/node_buffer.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 042f4219efeb6e..e9551eba8cca08 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -320,8 +320,8 @@ MaybeLocal New(Environment* env, size_t length) { MaybeLocal Copy(Isolate* isolate, const char* data, size_t length) { + EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); - EscapableHandleScope handle_scope(env->isolate()); Local obj; if (Buffer::Copy(env, data, length).ToLocal(&obj)) return handle_scope.Escape(obj); @@ -370,8 +370,8 @@ MaybeLocal New(Isolate* isolate, size_t length, FreeCallback callback, void* hint) { + EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); - EscapableHandleScope handle_scope(env->isolate()); Local obj; if (Buffer::New(env, data, length, callback, hint).ToLocal(&obj)) return handle_scope.Escape(obj); @@ -409,8 +409,8 @@ MaybeLocal New(Environment* env, MaybeLocal New(Isolate* isolate, char* data, size_t length) { + EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); - EscapableHandleScope handle_scope(env->isolate()); Local obj; if (Buffer::New(env, data, length).ToLocal(&obj)) return handle_scope.Escape(obj); From 978362d3b652f7d4534e49dec6399e020f142f96 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 13 Jul 2016 16:16:40 +0200 Subject: [PATCH 27/34] src: fix handle leak in BuildStatsObject() Create a handle scope before performing a check that creates a handle, otherwise the handle is leaked into the handle scope of the caller. PR-URL: https://github.com/nodejs/node/pull/7711 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Trevor Norris --- src/node_file.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/node_file.cc b/src/node_file.cc index 968284788a4b72..1fdef68ca6129b 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -420,11 +420,11 @@ static void Close(const FunctionCallbackInfo& args) { Local BuildStatsObject(Environment* env, const uv_stat_t* s) { + EscapableHandleScope handle_scope(env->isolate()); + // If you hit this assertion, you forgot to enter the v8::Context first. CHECK_EQ(env->context(), env->isolate()->GetCurrentContext()); - EscapableHandleScope handle_scope(env->isolate()); - // The code below is very nasty-looking but it prevents a segmentation fault // when people run JS code like the snippet below. It's apparently more // common than you would expect, several people have reported this crash... From e46efd9244aafbd459212d56dea571154ce3adb0 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 13 Jul 2016 16:16:52 +0200 Subject: [PATCH 28/34] src: fix handle leak in UDPWrap::Instantiate() Create a handle scope before performing a check that creates a handle, otherwise the handle is leaked into the handle scope of the caller. PR-URL: https://github.com/nodejs/node/pull/7711 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Trevor Norris --- src/udp_wrap.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/udp_wrap.cc b/src/udp_wrap.cc index bd7aa418bd89cf..a0d8b1f7613b61 100644 --- a/src/udp_wrap.cc +++ b/src/udp_wrap.cc @@ -436,9 +436,9 @@ void UDPWrap::OnRecv(uv_udp_t* handle, Local UDPWrap::Instantiate(Environment* env, AsyncWrap* parent) { + EscapableHandleScope scope(env->isolate()); // If this assert fires then Initialize hasn't been called yet. CHECK_EQ(env->udp_constructor_function().IsEmpty(), false); - EscapableHandleScope scope(env->isolate()); Local ptr = External::New(env->isolate(), parent); return scope.Escape(env->udp_constructor_function() ->NewInstance(env->context(), 1, &ptr).ToLocalChecked()); From 61d88d959fdee1abc13ca6b1295aff0bc1f65d48 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 13 Jul 2016 16:38:27 +0200 Subject: [PATCH 29/34] src: remove unnecessary HandleScopes API function callbacks run inside an implicit HandleScope. We don't need to explicitly create one and in fact introduce some unnecessary overhead when we do. PR-URL: https://github.com/nodejs/node/pull/7711 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Trevor Norris --- src/node_crypto.cc | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/node_crypto.cc b/src/node_crypto.cc index a7964cde94ac54..2b85d1a60980dd 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -1822,8 +1822,6 @@ template void SSLWrap::SetOCSPResponse( const v8::FunctionCallbackInfo& args) { #ifdef NODE__HAVE_TLSEXT_STATUS_CB - HandleScope scope(args.GetIsolate()); - Base* w; ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); Environment* env = w->env(); @@ -1842,8 +1840,6 @@ template void SSLWrap::RequestOCSP( const v8::FunctionCallbackInfo& args) { #ifdef NODE__HAVE_TLSEXT_STATUS_CB - HandleScope scope(args.GetIsolate()); - Base* w; ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); @@ -1901,7 +1897,6 @@ void SSLWrap::GetEphemeralKeyInfo( template void SSLWrap::SetMaxSendFragment( const v8::FunctionCallbackInfo& args) { - HandleScope scope(args.GetIsolate()); CHECK(args.Length() >= 1 && args[0]->IsNumber()); Base* w; @@ -2204,7 +2199,6 @@ template void SSLWrap::GetALPNNegotiatedProto( const FunctionCallbackInfo& args) { #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation - HandleScope scope(args.GetIsolate()); Base* w; ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); @@ -2226,7 +2220,6 @@ template void SSLWrap::SetALPNProtocols( const FunctionCallbackInfo& args) { #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation - HandleScope scope(args.GetIsolate()); Base* w; ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); Environment* env = w->env(); From 62a3ff27d07b157f193a9ffdf0a9de82960c70b3 Mon Sep 17 00:00:00 2001 From: "Hargobind S. Khalsa" Date: Sun, 17 Jul 2016 16:01:52 -0600 Subject: [PATCH 30/34] doc: correct sample output of buf.compare Comparing the buffers `ABC` and `ABCD` returns `-1` not `1`. PR-URL: https://github.com/nodejs/node/pull/7777 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen --- doc/api/buffer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 92908fd38b8177..413d5b7167da18 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -806,7 +806,7 @@ console.log(buf1.compare(buf1)); console.log(buf1.compare(buf2)); // Prints: -1 console.log(buf1.compare(buf3)); - // Prints: 1 + // Prints: -1 console.log(buf2.compare(buf1)); // Prints: 1 console.log(buf2.compare(buf3)); From 9d59b7d1f7a52ace4b49f7e0f0c668e18ff7d522 Mon Sep 17 00:00:00 2001 From: Gireesh Punathil Date: Wed, 13 Jul 2016 02:03:55 -0400 Subject: [PATCH 31/34] test: avoid usage of mixed IPV6 addresses The test case fails in AIX due to the mixed-use of unspecified and loopback addresses. This is not a problem in most platforms but fails in AIX. (In Windows too, but does not manifest as the test is omitted in Windows for a different reason). There exists no documented evidence which supports the mixed use of unspecified and loopback addresses. While AIX strictly follows the IPV6 specification with respect to unspecified address ('::') and loopback address ('::1'), the test case latches on to the behavior exhibited by other platforms, and hence it fails in AIX. The proposed fix is to make it work in all platforms including AIX by using the loopback address for the client to connect, as that is the address at which the server listens. Fixes: https://github.com/nodejs/node/issues/7563 PR-URL: https://github.com/nodejs/node/pull/7702 Reviewed-By: Michael Dawson Reviewed-By: Rich Trott Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig --- test/parallel/test-cluster-disconnect-handles.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-cluster-disconnect-handles.js b/test/parallel/test-cluster-disconnect-handles.js index 49b8218ab9c8d3..680e316cf0ba92 100644 --- a/test/parallel/test-cluster-disconnect-handles.js +++ b/test/parallel/test-cluster-disconnect-handles.js @@ -92,7 +92,7 @@ if (cluster.isMaster) { debugger; }; if (common.hasIPv6) - server.listen(cb); + server.listen(0, '::1', cb); else server.listen(0, common.localhostIPv4, cb); process.on('disconnect', process.exit); From 059a721ec5b940c8bbf09c312095f33f91d7a8b1 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 13 Jul 2016 15:30:08 -0700 Subject: [PATCH 32/34] doc: update CTC governance information MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update some outdated material. Provide some minor fixes. Wrap to 80 characters. PR-URL: https://github.com/nodejs/node/pull/7719 Reviewed-By: Rod Vagg Reviewed-By: Ben Noordhuis Reviewed-By: Jeremiah Senkpiel Reviewed-By: Michael Dawson Reviewed-By: Julien Gilli Reviewed-By: Colin Ihrig Reviewed-By: Ali Ijaz Sheikh Reviewed-By: Evan Lucas Reviewed-By: Fedor Indutny Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Trevor Norris --- GOVERNANCE.md | 45 +++++++++++++++++++-------------------------- 1 file changed, 19 insertions(+), 26 deletions(-) diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 06cec91e7db8b6..34b2f5fd1ec936 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -2,8 +2,8 @@ ## Core Technical Committee -The Node.js project is jointly governed by a Core Technical Committee (CTC) -which is responsible for high-level guidance of the project. +The Node.js project is governed by a Core Technical Committee (CTC) which is +responsible for high-level guidance of the project. The CTC has final authority over this project including: @@ -14,11 +14,6 @@ The CTC has final authority over this project including: * Conduct guidelines * Maintaining the list of additional Collaborators -Initial membership invitations to the CTC were given to individuals who -had been active contributors to Node.js, and who have significant -experience with the management of the Node.js project. Membership is -expected to evolve over time according to the needs of the project. - For the current list of CTC members, see the project [README.md](./README.md#current-project-team-members). @@ -46,8 +41,8 @@ responsibility for the change. In the case of pull requests proposed by an existing Collaborator, an additional Collaborator is required for sign-off. Consensus should be sought if additional Collaborators participate and there is disagreement around a particular -modification. See [Consensus Seeking Process](#consensus-seeking-process) below for further detail -on the consensus model used for governance. +modification. See [Consensus Seeking Process](#consensus-seeking-process) below +for further detail on the consensus model used for governance. Collaborators may opt to elevate significant or controversial modifications, or modifications that have not found consensus to the @@ -87,9 +82,8 @@ members affiliated with the over-represented employer(s). ## CTC Meetings -The CTC meets weekly on a Google Hangout On Air. The meeting is run by -a designated moderator approved by the CTC. Each meeting should be -published to YouTube. +The CTC meets weekly in a voice conference call. The meeting is run by a +designated moderator approved by the CTC. Each meeting is streamed on YouTube. Items are added to the CTC agenda which are considered contentious or are modifications of governance, contribution policy, CTC membership, @@ -100,20 +94,20 @@ That should happen continuously on GitHub and be handled by the larger group of Collaborators. Any community member or contributor can ask that something be added to -the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +the next meeting's agenda by logging a GitHub issue. Any Collaborator, CTC member or the moderator can add the item to the agenda by adding the ***ctc-agenda*** tag to the issue. -Prior to each CTC meeting, the moderator will share the Agenda with -members of the CTC. CTC members can add any items they like to the -agenda at the beginning of each meeting. The moderator and the CTC -cannot veto or remove items. +Prior to each CTC meeting, the moderator will share the agenda with +members of the CTC. CTC members can also add items to the agenda at the +beginning of each meeting. The moderator and the CTC cannot veto or remove +items. The CTC may invite persons or representatives from certain projects to participate in a non-voting capacity. -The moderator is responsible for summarizing the discussion of each -agenda item and sending it as a pull request after the meeting. +The moderator is responsible for summarizing the discussion of each agenda item +and sending it as a pull request after the meeting. ## Consensus Seeking Process @@ -121,11 +115,10 @@ The CTC follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. -When an agenda item has appeared to reach a consensus, the moderator -will ask "Does anyone object?" as a final call for dissent from the -consensus. +When an agenda item has appeared to reach a consensus, the moderator will ask +"Does anyone object?" as a final call for dissent from the consensus. -If an agenda item cannot reach a consensus, a CTC member can call for -either a closing vote or a vote to table the issue to the next -meeting. The call for a vote must be approved by a majority of the CTC -or else the discussion will continue. Simple majority wins. +If an agenda item cannot reach a consensus, a CTC member can call for either a +closing vote or a vote to table the issue to the next meeting. The call for a +vote must be approved by a simple majority of the CTC or else the discussion +will continue. From f3182f6971c67a79ffe994135124675ae86c447b Mon Sep 17 00:00:00 2001 From: Ali Ijaz Sheikh Date: Fri, 15 Jul 2016 09:05:20 -0700 Subject: [PATCH 33/34] deps: v8_inspector no longer depends on wtf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove wtf files as v8_inspector no longer needs them. Ref: https://github.com/nodejs/node/issues/7123 PR-URL: https://github.com/nodejs/node/pull/7751 Reviewed-By: Colin Ihrig Reviewed-By: Michaël Zasso Reviewed-By: Minwoo Jung --- deps/v8_inspector/deps/wtf/README.md | 1 - deps/v8_inspector/deps/wtf/wtf/Assertions.h | 40 --- deps/v8_inspector/deps/wtf/wtf/Compiler.h | 54 ---- deps/v8_inspector/deps/wtf/wtf/PtrUtil.h | 275 -------------------- 4 files changed, 370 deletions(-) delete mode 100644 deps/v8_inspector/deps/wtf/README.md delete mode 100644 deps/v8_inspector/deps/wtf/wtf/Assertions.h delete mode 100644 deps/v8_inspector/deps/wtf/wtf/Compiler.h delete mode 100644 deps/v8_inspector/deps/wtf/wtf/PtrUtil.h diff --git a/deps/v8_inspector/deps/wtf/README.md b/deps/v8_inspector/deps/wtf/README.md deleted file mode 100644 index 6fe75ce24cd74a..00000000000000 --- a/deps/v8_inspector/deps/wtf/README.md +++ /dev/null @@ -1 +0,0 @@ -# wtf diff --git a/deps/v8_inspector/deps/wtf/wtf/Assertions.h b/deps/v8_inspector/deps/wtf/wtf/Assertions.h deleted file mode 100644 index 18f21cacb740f0..00000000000000 --- a/deps/v8_inspector/deps/wtf/wtf/Assertions.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2003, 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2013 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WTF_Assertions_h -#define WTF_Assertions_h - -#ifndef CHECK -#define CHECK(condition) ((void) 0) -#endif -#define DCHECK(condition) ((void) 0) -#define NOTREACHED() -#define DCHECK_GE(i, j) DCHECK(i >= j) - -template -inline void USE(T) { } - -#endif /* WTF_Assertions_h */ diff --git a/deps/v8_inspector/deps/wtf/wtf/Compiler.h b/deps/v8_inspector/deps/wtf/wtf/Compiler.h deleted file mode 100644 index 61926a054fa1b9..00000000000000 --- a/deps/v8_inspector/deps/wtf/wtf/Compiler.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2011, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WTF_Compiler_h -#define WTF_Compiler_h - -/* COMPILER() - the compiler being used to build the project */ -#define COMPILER(WTF_FEATURE) (defined WTF_COMPILER_##WTF_FEATURE && WTF_COMPILER_##WTF_FEATURE) - -/* ==== COMPILER() - the compiler being used to build the project ==== */ - -/* COMPILER(CLANG) - Clang */ -#if defined(__clang__) -#define WTF_COMPILER_CLANG 1 -#endif - -/* COMPILER(MSVC) - Microsoft Visual C++ (and Clang when compiling for Windows). */ -#if defined(_MSC_VER) -#define WTF_COMPILER_MSVC 1 -#endif - -/* COMPILER(GCC) - GNU Compiler Collection (and Clang when compiling for platforms other than Windows). */ -#if defined(__GNUC__) -#define WTF_COMPILER_GCC 1 -#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) -#define GCC_VERSION_AT_LEAST(major, minor, patch) (GCC_VERSION >= (major * 10000 + minor * 100 + patch)) -#else -/* Define this for !GCC compilers, just so we can write things like GCC_VERSION_AT_LEAST(4, 1, 0). */ -#define GCC_VERSION_AT_LEAST(major, minor, patch) 0 -#endif - -#endif /* WTF_Compiler_h */ diff --git a/deps/v8_inspector/deps/wtf/wtf/PtrUtil.h b/deps/v8_inspector/deps/wtf/wtf/PtrUtil.h deleted file mode 100644 index 0d5a7fdd810141..00000000000000 --- a/deps/v8_inspector/deps/wtf/wtf/PtrUtil.h +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. - * Copyright (C) 2013 Intel Corporation. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#ifndef WTF_PtrUtil_h -#define WTF_PtrUtil_h - -#include "wtf/Assertions.h" -#include - -#if defined(__APPLE__) && !defined(_LIBCPP_VERSION) - -namespace std { - -template -struct is_convertible -{ -private: - struct True_ { char x[2]; }; - struct False_ { }; - - static True_ helper(T2 const &); - static False_ helper(...); - -public: - static bool const value = ( - sizeof(True_) == sizeof(is_convertible::helper(T1())) - ); -}; - -template -struct enable_if {}; - -template -struct enable_if -{ - typedef T type; -}; - -template -struct remove_extent { typedef T type; }; - -template -struct remove_extent { typedef T type; }; - -template -struct remove_extent { typedef T type;}; - -typedef decltype(nullptr) nullptr_t; - -template -struct integral_constant { - static constexpr T value = v; - typedef T value_type; - typedef integral_constant type; - constexpr operator value_type() const noexcept { return value; } - constexpr value_type operator()() const noexcept { return value; } //since c++14 -}; - -typedef integral_constant true_type; -typedef integral_constant false_type; - -template -struct is_array : false_type {}; - -template -struct is_array : true_type {}; - -template -struct is_array : true_type {}; - -template -struct OwnedPtrDeleter { - static void deletePtr(T* ptr) - { - static_assert(sizeof(T) > 0, "type must be complete"); - delete ptr; - } -}; - -template -struct OwnedPtrDeleter { - static void deletePtr(T* ptr) - { - static_assert(sizeof(T) > 0, "type must be complete"); - delete[] ptr; - } -}; - -template -struct OwnedPtrDeleter { - static_assert(sizeof(T) < 0, "do not use array with size as type"); -}; - - -template class unique_ptr { -public: - typedef typename remove_extent::type ValueType; - typedef ValueType* PtrType; - - unique_ptr() : m_ptr(nullptr) {} - unique_ptr(std::nullptr_t) : m_ptr(nullptr) {} - unique_ptr(unique_ptr&&); - template ::value>::type> unique_ptr(unique_ptr&&); - - ~unique_ptr() - { - OwnedPtrDeleter::deletePtr(m_ptr); - m_ptr = nullptr; - } - - PtrType get() const { return m_ptr; } - - void reset(PtrType ptr = nullptr); - PtrType release(); - - ValueType& operator*() const { DCHECK(m_ptr); return *m_ptr; } - PtrType operator->() const { DCHECK(m_ptr); return m_ptr; } - - ValueType& operator[](std::ptrdiff_t i) const; - - bool operator!() const { return !m_ptr; } - explicit operator bool() const { return m_ptr; } - - unique_ptr& operator=(std::nullptr_t) { reset(); return *this; } - - - unique_ptr& operator=(unique_ptr&&); - template unique_ptr& operator=(unique_ptr&&); - - void swap(unique_ptr& o) { std::swap(m_ptr, o.m_ptr); } - - static T* hashTableDeletedValue() { return reinterpret_cast(-1); } - - explicit unique_ptr(PtrType ptr) : m_ptr(ptr) {} - -private: - - // We should never have two unique_ptrs for the same underlying object - // (otherwise we'll get double-destruction), so these equality operators - // should never be needed. - template bool operator==(const unique_ptr&) const - { - static_assert(!sizeof(U*), "unique_ptrs should never be equal"); - return false; - } - template bool operator!=(const unique_ptr&) const - { - static_assert(!sizeof(U*), "unique_ptrs should never be equal"); - return false; - } - - PtrType m_ptr; -}; - - -template inline void unique_ptr::reset(PtrType ptr) -{ - PtrType p = m_ptr; - m_ptr = ptr; - OwnedPtrDeleter::deletePtr(p); -} - -template inline typename unique_ptr::PtrType unique_ptr::release() -{ - PtrType ptr = m_ptr; - m_ptr = nullptr; - return ptr; -} - -template inline typename unique_ptr::ValueType& unique_ptr::operator[](std::ptrdiff_t i) const -{ - static_assert(is_array::value, "elements access is possible for arrays only"); - DCHECK(m_ptr); - DCHECK(i >= 0); - return m_ptr[i]; -} - -template inline unique_ptr::unique_ptr(unique_ptr&& o) - : m_ptr(o.release()) -{ -} - -template -template inline unique_ptr::unique_ptr(unique_ptr&& o) - : m_ptr(o.release()) -{ - static_assert(!is_array::value, "pointers to array must never be converted"); -} - -template inline unique_ptr& unique_ptr::operator=(unique_ptr&& o) -{ - PtrType ptr = m_ptr; - m_ptr = o.release(); - DCHECK(!ptr || m_ptr != ptr); - OwnedPtrDeleter::deletePtr(ptr); - - return *this; -} - -template -template inline unique_ptr& unique_ptr::operator=(unique_ptr&& o) -{ - static_assert(!is_array::value, "pointers to array must never be converted"); - PtrType ptr = m_ptr; - m_ptr = o.release(); - DCHECK(!ptr || m_ptr != ptr); - OwnedPtrDeleter::deletePtr(ptr); - - return *this; -} - -template inline void swap(unique_ptr& a, unique_ptr& b) -{ - a.swap(b); -} - -template inline bool operator==(const unique_ptr& a, U* b) -{ - return a.get() == b; -} - -template inline bool operator==(T* a, const unique_ptr& b) -{ - return a == b.get(); -} - -template inline bool operator!=(const unique_ptr& a, U* b) -{ - return a.get() != b; -} - -template inline bool operator!=(T* a, const unique_ptr& b) -{ - return a != b.get(); -} - -template inline typename unique_ptr::PtrType getPtr(const unique_ptr& p) -{ - return p.get(); -} - -template -unique_ptr move(unique_ptr& ptr) -{ - return unique_ptr(ptr.release()); -} - -} - -#endif - -template -std::unique_ptr wrapUnique(T* ptr) { - return std::unique_ptr(ptr); -} - -#endif // WTF_PtrUtil_h From bb187bb9b0ab44fe734b217fd579b69c2be36cdd Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Thu, 7 Jul 2016 14:29:32 -0700 Subject: [PATCH 34/34] deps: cherry-pick 1f53e42 from v8 upstream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Original commit message: Handle symbols in FrameMirror#invocationText(). Fix a TypeError when putting together the invocationText for a symbol method's stack frame. See https://github.com/nodejs/node/issues/7536. Review-Url: https://codereview.chromium.org/2122793003 Cr-Commit-Position: refs/heads/master@{#37597} Fixes: https://github.com/nodejs/node/issues/7536 PR-URL: https://github.com/nodejs/node/pull/7612 Reviewed-By: Colin Ihrig Reviewed-By: Michaël Zasso --- deps/v8/include/v8-version.h | 2 +- deps/v8/src/debug/mirrors.js | 10 ++- deps/v8/test/mjsunit/debug-backtrace-text.js | 80 +++++++++++++------- 3 files changed, 63 insertions(+), 29 deletions(-) diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index c30ace1e885cf1..16a93f1b708edb 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 5 #define V8_MINOR_VERSION 0 #define V8_BUILD_NUMBER 71 -#define V8_PATCH_LEVEL 55 +#define V8_PATCH_LEVEL 56 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/src/debug/mirrors.js b/deps/v8/src/debug/mirrors.js index 8b9dd02b6ea0bd..4c280c7b54ecee 100644 --- a/deps/v8/src/debug/mirrors.js +++ b/deps/v8/src/debug/mirrors.js @@ -1494,6 +1494,12 @@ PropertyMirror.prototype.name = function() { }; +PropertyMirror.prototype.toText = function() { + if (IS_SYMBOL(this.name_)) return %SymbolDescriptiveString(this.name_); + return this.name_; +}; + + PropertyMirror.prototype.isIndexed = function() { for (var i = 0; i < this.name_.length; i++) { if (this.name_[i] < '0' || '9' < this.name_[i]) { @@ -2054,10 +2060,10 @@ FrameMirror.prototype.invocationText = function() { if (display_receiver) { result += '.'; } - result += property.name(); + result += property.toText(); } else { result += '['; - result += property.name(); + result += property.toText(); result += ']'; } // Also known as - if the name in the function doesn't match the name diff --git a/deps/v8/test/mjsunit/debug-backtrace-text.js b/deps/v8/test/mjsunit/debug-backtrace-text.js index 61648fa4e2e6ee..cfc89e6c1d6762 100644 --- a/deps/v8/test/mjsunit/debug-backtrace-text.js +++ b/deps/v8/test/mjsunit/debug-backtrace-text.js @@ -35,7 +35,8 @@ function Point(x, y) { Point.prototype.distanceTo = function(p) { debugger; - return Math.sqrt(Math.pow(Math.abs(this.x - p.x), 2) + Math.pow(Math.abs(this.y - p.y), 2)) + return Math.sqrt(Math.pow(Math.abs(this.x - p.x), 2) + + Math.pow(Math.abs(this.y - p.y), 2)) } p1 = new Point(1,1); @@ -58,7 +59,7 @@ a=[1,2,distance]; // Get the Debug object exposed from the debug context global object. Debug = debug.Debug -testConstructor = false; // Flag to control which part of the test is run. +what = 'constructor'; // Flag to control which part of the test is run. listenerCalled = false; exception = false; @@ -72,30 +73,47 @@ function safeEval(code) { function listener(event, exec_state, event_data, data) { try { - if (event == Debug.DebugEvent.Break) - { - if (!testConstructor) { - // The expected backtrace is - // 0: Call distance on Point where distance is a property on the prototype - // 1: Call distance on Point where distance is a direct property - // 2: Call on function an array element 2 - // 3: [anonymous] - assertEquals("#.distanceTo(p=#)", exec_state.frame(0).invocationText()); - assertEquals("#.distanceTo(p=#)", exec_state.frame(1).invocationText()); - assertEquals("#[2](aka distance)(p=#, q=#)", exec_state.frame(2).invocationText()); - assertEquals("[anonymous]()", exec_state.frame(3).invocationText()); - listenerCalled = true; - } else { - // The expected backtrace is - // 0: Call Point constructor - // 1: Call on global function createPoint - // 2: [anonymous] - assertEquals("new Point(x=0, y=0)", exec_state.frame(0).invocationText()); - assertEquals("createPoint(x=0, y=0)", exec_state.frame(1).invocationText()); - assertEquals("[anonymous]()", exec_state.frame(2).invocationText()); - listenerCalled = true; + if (event == Debug.DebugEvent.Break) { + if (what == 'constructor') { + // The expected backtrace is + // 0: Call distance on Point where distance is a prototype property + // 1: Call distance on Point where distance is a direct property + // 2: Call on function an array element 2 + // 3: [anonymous] + assertEquals("#.distanceTo(p=#)", + exec_state.frame(0).invocationText()); + assertEquals("#.distanceTo(p=#)", + exec_state.frame(1).invocationText()); + assertEquals("#[2](aka distance)(p=#, q=#)", + exec_state.frame(2).invocationText()); + assertEquals("[anonymous]()", exec_state.frame(3).invocationText()); + listenerCalled = true; + } else if (what == 'breakpoint') { + // The expected backtrace is + // 0: Call Point constructor + // 1: Call on global function createPoint + // 2: [anonymous] + assertEquals("new Point(x=0, y=0)", + exec_state.frame(0).invocationText()); + assertEquals("createPoint(x=0, y=0)", + exec_state.frame(1).invocationText()); + assertEquals("[anonymous]()", exec_state.frame(2).invocationText()); + listenerCalled = true; + } else if (what == 'symbol') { + // The expected backtrace is + // 0: Call Point constructor + // 1: Call on symbol method + // 2: [anonymous] + assertEquals("new Point(x=0, y=0)", + exec_state.frame(0).invocationText()); + assertEquals("#[Symbol(Das Symbol)](x=0, y=0)", + exec_state.frame(1).invocationText()); + assertEquals("[anonymous]()", exec_state.frame(2).invocationText()); + listenerCalled = true; + } else { + assertUnreachable(); + } } - } } catch (e) { exception = e }; @@ -112,11 +130,21 @@ assertTrue(listenerCalled); assertFalse(exception, "exception in listener") // Set a break point and call to invoke the debug event listener. +what = 'breakpoint'; listenerCalled = false; -testConstructor = true; Debug.setBreakPoint(Point, 0, 0); createPoint(0, 0); // Make sure that the debug event listener vas invoked (again). assertTrue(listenerCalled); assertFalse(exception, "exception in listener") + +what = 'symbol'; +listenerCalled = false; +var S = Symbol('Das Symbol'); +var o = { [S](x, y) { return new Point(x, y); } }; +Debug.setBreakPoint(Point, 0, 0); +o[S](0, 0); + +assertTrue(listenerCalled); +assertFalse(exception, "exception in listener")