From 18be4761162d2365159862c8e6cd67c18a90161a Mon Sep 17 00:00:00 2001
From: Timothy Gu
* codes,
+ Code* topmost_optimized_code,
+ bool safe_to_deopt_topmost_optimized_code)
+ : codes_(codes) {
+#ifdef DEBUG
+ topmost_ = topmost_optimized_code;
+ safe_to_deopt_ = safe_to_deopt_topmost_optimized_code;
+#endif
+ }
+
+ // Find the frames with activations of codes marked for deoptimization, search
+ // for the trampoline to the deoptimizer call respective to each code, and use
+ // it to replace the current pc on the stack.
+ void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
+ for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
+ if (it.frame()->type() == StackFrame::OPTIMIZED) {
+ Code* code = it.frame()->LookupCode();
+ if (code->kind() == Code::OPTIMIZED_FUNCTION &&
+ code->marked_for_deoptimization()) {
+ codes_->erase(code);
+ // Obtain the trampoline to the deoptimizer call.
+ SafepointEntry safepoint = code->GetSafepointEntry(it.frame()->pc());
+ int trampoline_pc = safepoint.trampoline_pc();
+ DCHECK_IMPLIES(code == topmost_, safe_to_deopt_);
+ // Replace the current pc on the stack with the trampoline.
+ it.frame()->set_pc(code->instruction_start() + trampoline_pc);
+ }
+ }
+ }
+ }
+
+ private:
+ std::set* codes_;
+
+#ifdef DEBUG
+ Code* topmost_;
+ bool safe_to_deopt_;
+#endif
+};
+} // namespace
+
void Deoptimizer::VisitAllOptimizedFunctionsForContext(
Context* context, OptimizedFunctionVisitor* visitor) {
DisallowHeapAllocation no_allocation;
@@ -264,9 +308,9 @@ void Deoptimizer::DeoptimizeMarkedCodeForContext(Context* context) {
VisitAllOptimizedFunctionsForContext(context, &unlinker);
Isolate* isolate = context->GetHeap()->isolate();
-#ifdef DEBUG
Code* topmost_optimized_code = NULL;
bool safe_to_deopt_topmost_optimized_code = false;
+#ifdef DEBUG
// Make sure all activations of optimized code can deopt at their current PC.
// The topmost optimized code has special handling because it cannot be
// deoptimized due to weak object dependency.
@@ -304,6 +348,10 @@ void Deoptimizer::DeoptimizeMarkedCodeForContext(Context* context) {
}
#endif
+ // We will use this set to mark those Code objects that are marked for
+ // deoptimization and have not been found in stack frames.
+ std::set codes;
+
// Move marked code from the optimized code list to the deoptimized
// code list.
// Walk over all optimized code objects in this native context.
@@ -335,25 +383,14 @@ void Deoptimizer::DeoptimizeMarkedCodeForContext(Context* context) {
element = next;
}
- // Finds the with activations of codes marked for deoptimization, search for
- // the trampoline to the deoptimizer call respective to each code, and use it
- // to replace the current pc on the stack.
- for (StackFrameIterator it(isolate, isolate->thread_local_top()); !it.done();
- it.Advance()) {
- if (it.frame()->type() == StackFrame::OPTIMIZED) {
- Code* code = it.frame()->LookupCode();
- if (code->kind() == Code::OPTIMIZED_FUNCTION &&
- code->marked_for_deoptimization()) {
- // Obtain the trampoline to the deoptimizer call.
- SafepointEntry safepoint = code->GetSafepointEntry(it.frame()->pc());
- int trampoline_pc = safepoint.trampoline_pc();
- DCHECK_IMPLIES(code == topmost_optimized_code,
- safe_to_deopt_topmost_optimized_code);
- // Replace the current pc on the stack with the trampoline.
- it.frame()->set_pc(code->instruction_start() + trampoline_pc);
- }
- }
- }
+ ActivationsFinder visitor(&codes, topmost_optimized_code,
+ safe_to_deopt_topmost_optimized_code);
+ // Iterate over the stack of this thread.
+ visitor.VisitThread(isolate, isolate->thread_local_top());
+ // In addition to iterate over the stack of this thread, we also
+ // need to consider all the other threads as they may also use
+ // the code currently beings deoptimized.
+ isolate->thread_manager()->IterateArchivedThreads(&visitor);
}
diff --git a/deps/v8/test/cctest/test-lockers.cc b/deps/v8/test/cctest/test-lockers.cc
index a310bfd68456c4..36a9f11ee27773 100644
--- a/deps/v8/test/cctest/test-lockers.cc
+++ b/deps/v8/test/cctest/test-lockers.cc
@@ -55,6 +55,244 @@ using ::v8::Value;
using ::v8::V8;
+namespace {
+
+class DeoptimizeCodeThread : public v8::base::Thread {
+ public:
+ DeoptimizeCodeThread(v8::Isolate* isolate, v8::Local context,
+ const char* trigger)
+ : Thread(Options("DeoptimizeCodeThread")),
+ isolate_(isolate),
+ context_(isolate, context),
+ source_(trigger) {}
+
+ void Run() {
+ v8::Locker locker(isolate_);
+ isolate_->Enter();
+ v8::HandleScope handle_scope(isolate_);
+ v8::Local context =
+ v8::Local::New(isolate_, context_);
+ v8::Context::Scope context_scope(context);
+ CHECK_EQ(isolate_, v8::Isolate::GetCurrent());
+ // This code triggers deoptimization of some function that will be
+ // used in a different thread.
+ CompileRun(source_);
+ isolate_->Exit();
+ }
+
+ private:
+ v8::Isolate* isolate_;
+ Persistent context_;
+ // The code that triggers the deoptimization.
+ const char* source_;
+};
+
+void UnlockForDeoptimization(const v8::FunctionCallbackInfo& args) {
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
+ // Gets the pointer to the thread that will trigger the deoptimization of the
+ // code.
+ DeoptimizeCodeThread* deoptimizer =
+ reinterpret_cast(isolate->GetData(0));
+ {
+ // Exits and unlocks the isolate.
+ isolate->Exit();
+ v8::Unlocker unlocker(isolate);
+ // Starts the deoptimizing thread.
+ deoptimizer->Start();
+ // Waits for deoptimization to finish.
+ deoptimizer->Join();
+ }
+ // The deoptimizing thread has finished its work, and the isolate
+ // will now be used by the current thread.
+ isolate->Enter();
+}
+
+void UnlockForDeoptimizationIfReady(
+ const v8::FunctionCallbackInfo& args) {
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
+ bool* ready_to_deoptimize = reinterpret_cast(isolate->GetData(1));
+ if (*ready_to_deoptimize) {
+ // The test should enter here only once, so put the flag back to false.
+ *ready_to_deoptimize = false;
+ // Gets the pointer to the thread that will trigger the deoptimization of
+ // the code.
+ DeoptimizeCodeThread* deoptimizer =
+ reinterpret_cast(isolate->GetData(0));
+ {
+ // Exits and unlocks the thread.
+ isolate->Exit();
+ v8::Unlocker unlocker(isolate);
+ // Starts the thread that deoptimizes the function.
+ deoptimizer->Start();
+ // Waits for the deoptimizing thread to finish.
+ deoptimizer->Join();
+ }
+ // The deoptimizing thread has finished its work, and the isolate
+ // will now be used by the current thread.
+ isolate->Enter();
+ }
+}
+} // namespace
+
+TEST(LazyDeoptimizationMultithread) {
+ i::FLAG_allow_natives_syntax = true;
+ v8::Isolate::CreateParams create_params;
+ create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
+ v8::Isolate* isolate = v8::Isolate::New(create_params);
+ {
+ v8::Locker locker(isolate);
+ v8::Isolate::Scope isolate_scope(isolate);
+ v8::HandleScope scope(isolate);
+ v8::Local context = v8::Context::New(isolate);
+ const char* trigger_deopt = "obj = { y: 0, x: 1 };";
+
+ // We use the isolate to pass arguments to the UnlockForDeoptimization
+ // function. Namely, we pass a pointer to the deoptimizing thread.
+ DeoptimizeCodeThread deoptimize_thread(isolate, context, trigger_deopt);
+ isolate->SetData(0, &deoptimize_thread);
+ v8::Context::Scope context_scope(context);
+
+ // Create the function templace for C++ code that is invoked from
+ // JavaScript code.
+ Local fun_templ =
+ v8::FunctionTemplate::New(isolate, UnlockForDeoptimization);
+ Local fun = fun_templ->GetFunction(context).ToLocalChecked();
+ CHECK(context->Global()
+ ->Set(context, v8_str("unlock_for_deoptimization"), fun)
+ .FromJust());
+
+ // Optimizes a function f, which will be deoptimized in another
+ // thread.
+ CompileRun(
+ "var b = false; var obj = { x: 1 };"
+ "function f() { g(); return obj.x; }"
+ "function g() { if (b) { unlock_for_deoptimization(); } }"
+ "%NeverOptimizeFunction(g);"
+ "f(); f(); %OptimizeFunctionOnNextCall(f);"
+ "f();");
+
+ // Trigger the unlocking.
+ Local v = CompileRun("b = true; f();");
+
+ // Once the isolate has been unlocked, the thread will wait for the
+ // other thread to finish its task. Once this happens, this thread
+ // continues with its execution, that is, with the execution of the
+ // function g, which then returns to f. The function f should have
+ // also been deoptimized. If the replacement did not happen on this
+ // thread's stack, then the test will fail here.
+ CHECK(v->IsNumber());
+ CHECK_EQ(1, static_cast(v->NumberValue(context).FromJust()));
+ }
+ isolate->Dispose();
+}
+
+TEST(LazyDeoptimizationMultithreadWithNatives) {
+ i::FLAG_allow_natives_syntax = true;
+ v8::Isolate::CreateParams create_params;
+ create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
+ v8::Isolate* isolate = v8::Isolate::New(create_params);
+ {
+ v8::Locker locker(isolate);
+ v8::Isolate::Scope isolate_scope(isolate);
+ v8::HandleScope scope(isolate);
+ v8::Local context = v8::Context::New(isolate);
+ const char* trigger_deopt = "%DeoptimizeFunction(f);";
+
+ // We use the isolate to pass arguments to the UnlockForDeoptimization
+ // function. Namely, we pass a pointer to the deoptimizing thread.
+ DeoptimizeCodeThread deoptimize_thread(isolate, context, trigger_deopt);
+ isolate->SetData(0, &deoptimize_thread);
+ bool ready_to_deopt = false;
+ isolate->SetData(1, &ready_to_deopt);
+ v8::Context::Scope context_scope(context);
+
+ // Create the function templace for C++ code that is invoked from
+ // JavaScript code.
+ Local fun_templ =
+ v8::FunctionTemplate::New(isolate, UnlockForDeoptimizationIfReady);
+ Local fun = fun_templ->GetFunction(context).ToLocalChecked();
+ CHECK(context->Global()
+ ->Set(context, v8_str("unlock_for_deoptimization"), fun)
+ .FromJust());
+
+ // Optimizes a function f, which will be deoptimized in another
+ // thread.
+ CompileRun(
+ "var obj = { x: 1 };"
+ "function f() { g(); return obj.x;}"
+ "function g() { "
+ " unlock_for_deoptimization(); }"
+ "%NeverOptimizeFunction(g);"
+ "f(); f(); %OptimizeFunctionOnNextCall(f);");
+
+ // Trigger the unlocking.
+ ready_to_deopt = true;
+ isolate->SetData(1, &ready_to_deopt);
+ Local v = CompileRun("f();");
+
+ // Once the isolate has been unlocked, the thread will wait for the
+ // other thread to finish its task. Once this happens, this thread
+ // continues with its execution, that is, with the execution of the
+ // function g, which then returns to f. The function f should have
+ // also been deoptimized. Otherwise, the test will fail here.
+ CHECK(v->IsNumber());
+ CHECK_EQ(1, static_cast(v->NumberValue(context).FromJust()));
+ }
+ isolate->Dispose();
+}
+
+TEST(EagerDeoptimizationMultithread) {
+ i::FLAG_allow_natives_syntax = true;
+ v8::Isolate::CreateParams create_params;
+ create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
+ v8::Isolate* isolate = v8::Isolate::New(create_params);
+ {
+ v8::Locker locker(isolate);
+ v8::Isolate::Scope isolate_scope(isolate);
+ v8::HandleScope scope(isolate);
+ v8::Local context = v8::Context::New(isolate);
+ const char* trigger_deopt = "f({y: 0, x: 1});";
+
+ // We use the isolate to pass arguments to the UnlockForDeoptimization
+ // function. Namely, we pass a pointer to the deoptimizing thread.
+ DeoptimizeCodeThread deoptimize_thread(isolate, context, trigger_deopt);
+ isolate->SetData(0, &deoptimize_thread);
+ bool ready_to_deopt = false;
+ isolate->SetData(1, &ready_to_deopt);
+ v8::Context::Scope context_scope(context);
+
+ // Create the function templace for C++ code that is invoked from
+ // JavaScript code.
+ Local fun_templ =
+ v8::FunctionTemplate::New(isolate, UnlockForDeoptimizationIfReady);
+ Local fun = fun_templ->GetFunction(context).ToLocalChecked();
+ CHECK(context->Global()
+ ->Set(context, v8_str("unlock_for_deoptimization"), fun)
+ .FromJust());
+
+ // Optimizes a function f, which will be deoptimized by another thread.
+ CompileRun(
+ "function f(obj) { unlock_for_deoptimization(); return obj.x; }"
+ "f({x: 1}); f({x: 1});"
+ "%OptimizeFunctionOnNextCall(f);"
+ "f({x: 1});");
+
+ // Trigger the unlocking.
+ ready_to_deopt = true;
+ isolate->SetData(1, &ready_to_deopt);
+ Local v = CompileRun("f({x: 1});");
+
+ // Once the isolate has been unlocked, the thread will wait for the
+ // other thread to finish its task. Once this happens, this thread
+ // continues with its execution, that is, with the execution of the
+ // function g, which then returns to f. The function f should have
+ // also been deoptimized. Otherwise, the test will fail here.
+ CHECK(v->IsNumber());
+ CHECK_EQ(1, static_cast(v->NumberValue(context).FromJust()));
+ }
+ isolate->Dispose();
+}
+
// Migrating an isolate
class KangarooThread : public v8::base::Thread {
public:
From 16bf5fed69905e64d860c6997a00e0248f5b7cf4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?=
Date: Mon, 18 Dec 2017 13:23:46 +0100
Subject: [PATCH 047/218] crypto: reuse variable instead of reevaluation
Backport-PR-URL: https://github.com/nodejs/node/pull/19114
PR-URL: https://github.com/nodejs/node/pull/17735
Reviewed-By: Colin Ihrig
Reviewed-By: Daniel Bevenius
Reviewed-By: Jon Moss
Reviewed-By: James M Snell
Reviewed-By: Luigi Pinca
---
src/node_crypto.cc | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/node_crypto.cc b/src/node_crypto.cc
index 685e7bb73b5a5c..6b5958b35e7049 100644
--- a/src/node_crypto.cc
+++ b/src/node_crypto.cc
@@ -3449,7 +3449,7 @@ void CipherBase::Init(const char* cipher_type,
nullptr,
reinterpret_cast(key),
reinterpret_cast(iv),
- kind_ == kCipher);
+ encrypt);
}
@@ -3518,7 +3518,7 @@ void CipherBase::InitIv(const char* cipher_type,
nullptr,
reinterpret_cast(key),
reinterpret_cast(iv),
- kind_ == kCipher);
+ encrypt);
}
From 745600a0b336c5d1591ec15f3e59e2e0c1cc1f5f Mon Sep 17 00:00:00 2001
From: Kyle Farnung
Date: Tue, 27 Feb 2018 10:53:45 -0800
Subject: [PATCH 048/218] test: remove orphaned entries from status
PR-URL: https://github.com/nodejs/node/pull/18092
Backport-PR-URL: https://github.com/nodejs/node/pull/19043
Reviewed-By: James M Snell
Reviewed-By: Colin Ihrig
Reviewed-By: Rich Trott
Reviewed-By: Gireesh Punathil
Reviewed-By: Daniel Bevenius
---
test/known_issues/known_issues.status | 2 --
1 file changed, 2 deletions(-)
diff --git a/test/known_issues/known_issues.status b/test/known_issues/known_issues.status
index 46c8ed32741c7d..e21913e232c03f 100644
--- a/test/known_issues/known_issues.status
+++ b/test/known_issues/known_issues.status
@@ -7,8 +7,6 @@ prefix known_issues
[true] # This section applies to all platforms
[$system==win32]
-test-stdout-buffer-flush-on-exit: SKIP
-test-cluster-disconnect-handles: SKIP
[$system==linux]
From 016a28ac08a60498dd1f36dfdc550df8e6f8118c Mon Sep 17 00:00:00 2001
From: Sarat Addepalli
Date: Mon, 8 Jan 2018 23:16:27 +0530
Subject: [PATCH 049/218] tools: non-Ascii linter for /lib only
Non-ASCII characters in /lib get compiled into the node binary,
and may bloat the binary size unnecessarily. A linter rule may
help prevent this.
PR-URL: https://github.com/nodejs/node/pull/18043
Backport-PR-URL: https://github.com/nodejs/node/pull/19499
Fixes: https://github.com/nodejs/node/issues/11209
Reviewed-By: Anna Henningsen
Reviewed-By: Ruben Bridgewater
Reviewed-By: Teddy Katz
---
lib/.eslintrc.yaml | 1 +
lib/console.js | 4 +-
lib/internal/http2/core.js | 2 +-
lib/internal/test/unicode.js | 2 +
lib/stream.js | 2 +-
lib/timers.js | 2 +
lib/zlib.js | 2 +-
tools/eslint-rules/non-ascii-character.js | 61 +++++++++++++++++++++++
8 files changed, 71 insertions(+), 5 deletions(-)
create mode 100644 tools/eslint-rules/non-ascii-character.js
diff --git a/lib/.eslintrc.yaml b/lib/.eslintrc.yaml
index 437aa575645ad6..0b00638e2a638c 100644
--- a/lib/.eslintrc.yaml
+++ b/lib/.eslintrc.yaml
@@ -6,3 +6,4 @@ rules:
buffer-constructor: error
no-let-in-for-declaration: error
lowercase-name-for-primitive: error
+ non-ascii-character: error
diff --git a/lib/console.js b/lib/console.js
index d0f7e61fd5a709..4495074231a2eb 100644
--- a/lib/console.js
+++ b/lib/console.js
@@ -81,7 +81,7 @@ function createWriteErrorHandler(stream) {
// If there was an error, it will be emitted on `stream` as
// an `error` event. Adding a `once` listener will keep that error
// from becoming an uncaught exception, but since the handler is
- // removed after the event, non-console.* writes won’t be affected.
+ // removed after the event, non-console.* writes won't be affected.
// we are only adding noop if there is no one else listening for 'error'
if (stream.listenerCount('error') === 0) {
stream.on('error', noop);
@@ -114,7 +114,7 @@ function write(ignoreErrors, stream, string, errorhandler, groupIndent) {
// even in edge cases such as low stack space.
if (e.message === 'Maximum call stack size exceeded')
throw e;
- // Sorry, there’s no proper way to pass along the error here.
+ // Sorry, there's no proper way to pass along the error here.
} finally {
stream.removeListener('error', noop);
}
diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js
index d83897c20b7902..cce54ef377fe0c 100644
--- a/lib/internal/http2/core.js
+++ b/lib/internal/http2/core.js
@@ -1537,7 +1537,7 @@ function processRespondWithFD(fd, headers, offset = 0, length = -1,
return;
}
// exact length of the file doesn't matter here, since the
- // stream is closing anyway — just use 1 to signify that
+ // stream is closing anyway - just use 1 to signify that
// a write does exist
trackWriteState(this, 1);
}
diff --git a/lib/internal/test/unicode.js b/lib/internal/test/unicode.js
index 1445276d9ae891..7172a43ec20a8a 100644
--- a/lib/internal/test/unicode.js
+++ b/lib/internal/test/unicode.js
@@ -3,4 +3,6 @@
// This module exists entirely for regression testing purposes.
// See `test/parallel/test-internal-unicode.js`.
+/* eslint-disable non-ascii-character */
module.exports = '✓';
+/* eslint-enable non-ascii-character */
diff --git a/lib/stream.js b/lib/stream.js
index edc5f231b83411..9a816600a05e5a 100644
--- a/lib/stream.js
+++ b/lib/stream.js
@@ -45,7 +45,7 @@ try {
try {
Stream._isUint8Array = process.binding('util').isUint8Array;
} catch (e) {
- // This throws for Node < 4.2.0 because there’s no util binding and
+ // This throws for Node < 4.2.0 because there's no util binding and
// returns undefined for Node < 7.4.0.
}
}
diff --git a/lib/timers.js b/lib/timers.js
index 0e6ae45950c5c1..f3c3c6308433eb 100644
--- a/lib/timers.js
+++ b/lib/timers.js
@@ -89,6 +89,7 @@ const TIMEOUT_MAX = 2147483647; // 2^31-1
// TimerWrap C++ handle, which makes the call after the duration to process the
// list it is attached to.
//
+/* eslint-disable non-ascii-character */
//
// ╔════ > Object Map
// ║
@@ -110,6 +111,7 @@ const TIMEOUT_MAX = 2147483647; // 2^31-1
// ║
// ╚════ > Linked List
//
+/* eslint-enable non-ascii-character */
//
// With this, virtually constant-time insertion (append), removal, and timeout
// is possible in the JavaScript layer. Any one list of timers is able to be
diff --git a/lib/zlib.js b/lib/zlib.js
index 7f41200f86be19..bbe89043248459 100644
--- a/lib/zlib.js
+++ b/lib/zlib.js
@@ -339,7 +339,7 @@ Zlib.prototype.flush = function flush(kind, callback) {
this._scheduledFlushFlag = maxFlush(kind, this._scheduledFlushFlag);
// If a callback was passed, always register a new `drain` + flush handler,
- // mostly because that’s simpler and flush callbacks piling up is a rare
+ // mostly because that's simpler and flush callbacks piling up is a rare
// thing anyway.
if (!alreadyHadFlushScheduled || callback) {
const drainHandler = () => this.flush(this._scheduledFlushFlag, callback);
diff --git a/tools/eslint-rules/non-ascii-character.js b/tools/eslint-rules/non-ascii-character.js
new file mode 100644
index 00000000000000..e67aac7cd91e82
--- /dev/null
+++ b/tools/eslint-rules/non-ascii-character.js
@@ -0,0 +1,61 @@
+/**
+ * @fileOverview Any non-ASCII characters in lib/ will increase the size
+ * of the compiled node binary. This linter rule ensures that
+ * any such character is reported.
+ * @author Sarat Addepalli
+ */
+
+'use strict';
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+const nonAsciiRegexPattern = /[^\r\n\x20-\x7e]/;
+const suggestions = {
+ '’': '\'',
+ '‛': '\'',
+ '‘': '\'',
+ '“': '"',
+ '‟': '"',
+ '”': '"',
+ '«': '"',
+ '»': '"',
+ '—': '-'
+};
+
+module.exports = (context) => {
+
+ const reportIfError = (node, sourceCode) => {
+
+ const matches = sourceCode.text.match(nonAsciiRegexPattern);
+
+ if (!matches) return;
+
+ const offendingCharacter = matches[0];
+ const offendingCharacterPosition = matches.index;
+ const suggestion = suggestions[offendingCharacter];
+
+ let message = `Non-ASCII character '${offendingCharacter}' detected.`;
+
+ message = suggestion ?
+ `${message} Consider replacing with: ${suggestion}` :
+ message;
+
+ context.report({
+ node,
+ message,
+ loc: sourceCode.getLocFromIndex(offendingCharacterPosition),
+ fix: (fixer) => {
+ return fixer.replaceText(
+ node,
+ suggestion ? `${suggestion}` : ''
+ );
+ }
+ });
+ };
+
+ return {
+ Program: (node) => reportIfError(node, context.getSourceCode())
+ };
+};
From d537f45aaaced00202efbd45ad6bc9a2c9bf289f Mon Sep 17 00:00:00 2001
From: Joyee Cheung
Date: Sun, 21 Jan 2018 01:14:03 +0800
Subject: [PATCH 050/218] build: make lint-md independent of local node
PR-URL: https://github.com/nodejs/node/pull/18272
Backport-PR-URL: https://github.com/nodejs/node/pull/19190
Reviewed-By: Gibson Fahnestock
Reviewed-By: James M Snell
---
Makefile | 27 ++++++++++++++++-----------
1 file changed, 16 insertions(+), 11 deletions(-)
diff --git a/Makefile b/Makefile
index 9ea385e46a362d..d6756107d7ce1d 100644
--- a/Makefile
+++ b/Makefile
@@ -1008,26 +1008,31 @@ lint-md-clean:
lint-md-build:
@if [ ! -d tools/remark-cli/node_modules ]; then \
echo "Markdown linter: installing remark-cli into tools/"; \
- cd tools/remark-cli && ../../$(NODE) ../../$(NPM) install; fi
+ cd tools/remark-cli && $(call available-node,$(run-npm-install)) fi
@if [ ! -d tools/remark-preset-lint-node/node_modules ]; then \
echo "Markdown linter: installing remark-preset-lint-node into tools/"; \
- cd tools/remark-preset-lint-node && ../../$(NODE) ../../$(NPM) install; fi
+ cd tools/remark-preset-lint-node && $(call available-node,$(run-npm-install)) fi
+
ifneq ("","$(wildcard tools/remark-cli/node_modules/)")
-LINT_MD_TARGETS = src lib benchmark tools/doc tools/icu
-LINT_MD_ROOT_DOCS := $(wildcard *.md)
-LINT_MD_FILES := $(shell find $(LINT_MD_TARGETS) -type f \
- -not -path '*node_modules*' -name '*.md') $(LINT_MD_ROOT_DOCS)
-LINT_DOC_MD_FILES = $(shell ls doc/**/*.md)
-tools/.docmdlintstamp: $(LINT_DOC_MD_FILES)
+LINT_MD_DOC_FILES = $(shell ls doc/**/*.md)
+run-lint-doc-md = tools/remark-cli/cli.js -q -f $(LINT_MD_DOC_FILES)
+# Lint all changed markdown files under doc/
+tools/.docmdlintstamp: $(LINT_MD_DOC_FILES)
@echo "Running Markdown linter on docs..."
- @$(NODE) tools/remark-cli/cli.js -q -f $(LINT_DOC_MD_FILES)
+ @$(call available-node,$(run-lint-doc-md))
@touch $@
-tools/.miscmdlintstamp: $(LINT_MD_FILES)
+LINT_MD_TARGETS = src lib benchmark tools/doc tools/icu
+LINT_MD_ROOT_DOCS := $(wildcard *.md)
+LINT_MD_MISC_FILES := $(shell find $(LINT_MD_TARGETS) -type f \
+ -not -path '*node_modules*' -name '*.md') $(LINT_MD_ROOT_DOCS)
+run-lint-misc-md = tools/remark-cli/cli.js -q -f $(LINT_MD_MISC_FILES)
+# Lint other changed markdown files maintained by us
+tools/.miscmdlintstamp: $(LINT_MD_MISC_FILES)
@echo "Running Markdown linter on misc docs..."
- @$(NODE) tools/remark-cli/cli.js -q -f $(LINT_MD_FILES)
+ @$(call available-node,$(run-lint-misc-md))
@touch $@
tools/.mdlintstamp: tools/.miscmdlintstamp tools/.docmdlintstamp
From 333d7dda84447e30d9f27d5b66fd7e30f54d226f Mon Sep 17 00:00:00 2001
From: Joyee Cheung
Date: Sun, 21 Jan 2018 01:17:47 +0800
Subject: [PATCH 051/218] build: make lint-js independent of local node
PR-URL: https://github.com/nodejs/node/pull/18272
Backport-PR-URL: https://github.com/nodejs/node/pull/19190
Reviewed-By: Gibson Fahnestock
Reviewed-By: James M Snell
---
Makefile | 32 ++++++++++++--------------------
1 file changed, 12 insertions(+), 20 deletions(-)
diff --git a/Makefile b/Makefile
index d6756107d7ce1d..d0b481d03ab9f3 100644
--- a/Makefile
+++ b/Makefile
@@ -1045,37 +1045,29 @@ lint-md:
endif
LINT_JS_TARGETS = benchmark doc lib test tools
-LINT_JS_CMD = tools/eslint/bin/eslint.js --cache \
- --rulesdir=tools/eslint-rules --ext=.js,.mjs,.md \
- $(LINT_JS_TARGETS)
+
+run-lint-js = tools/eslint/bin/eslint.js --cache \
+ --rulesdir=tools/eslint-rules --ext=.js,.mjs,.md $(LINT_JS_TARGETS)
+run-lint-js-fix = $(run-lint-js) --fix
lint-js-fix:
- @if [ -x $(NODE) ]; then \
- $(NODE) $(LINT_JS_CMD) --fix; \
- else \
- node $(LINT_JS_CMD) --fix; \
- fi
+ @$(call available-node,$(run-lint-js-fix))
lint-js:
@echo "Running JS linter..."
- @if [ -x $(NODE) ]; then \
- $(NODE) $(LINT_JS_CMD); \
- else \
- node $(LINT_JS_CMD); \
- fi
+ @$(call available-node,$(run-lint-js))
jslint: lint-js
@echo "Please use lint-js instead of jslint"
+run-lint-js-ci = tools/lint-js.js $(PARALLEL_ARGS) -f tap -o test-eslint.tap \
+ $(LINT_JS_TARGETS)
+
+.PHONY: lint-js-ci
+# On the CI the output is emitted in the TAP format.
lint-js-ci:
@echo "Running JS linter..."
- @if [ -x $(NODE) ]; then \
- $(NODE) tools/lint-js.js $(PARALLEL_ARGS) -f tap -o test-eslint.tap \
- $(LINT_JS_TARGETS); \
- else \
- node tools/lint-js.js $(PARALLEL_ARGS) -f tap -o test-eslint.tap \
- $(LINT_JS_TARGETS); \
- fi
+ @$(call available-node,$(run-lint-js-ci))
jslint-ci: lint-js-ci
@echo "Please use lint-js-ci instead of jslint-ci"
From c89781583bb53389f0881a166beb7e2d0e59a194 Mon Sep 17 00:00:00 2001
From: Vse Mozhet Byt
Date: Mon, 2 Apr 2018 17:35:56 +0300
Subject: [PATCH 052/218] doc: fix various nits
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* Replace 2 hyphens (--) by spaced m-dashes (—) as per STYLE_GUIDE.md.
* Space infix operators.
* Unify quotes in inline code spans (use only single quotes).
* Unify `* Returns:` (eliminate deviations).
* Dedupe spaces.
PR-URL: https://github.com/nodejs/node/pull/19743
Backport-PR-URL: https://github.com/nodejs/node/pull/19753
Reviewed-By: James M Snell
Reviewed-By: Trivikram Kamat
---
doc/api/addons.md | 2 +-
doc/api/async_hooks.md | 2 +-
doc/api/buffer.md | 10 +++----
doc/api/child_process.md | 32 ++++++++++-----------
doc/api/cli.md | 6 ++--
doc/api/cluster.md | 14 +++++-----
doc/api/console.md | 2 +-
doc/api/crypto.md | 4 +--
doc/api/debugger.md | 2 +-
doc/api/dgram.md | 30 ++++++++++----------
doc/api/dns.md | 22 +++++++--------
doc/api/domain.md | 30 ++++++++++----------
doc/api/errors.md | 16 +++++------
doc/api/esm.md | 14 +++++-----
doc/api/fs.md | 36 ++++++++++++------------
doc/api/http.md | 60 ++++++++++++++++++++--------------------
doc/api/http2.md | 28 +++++++++----------
doc/api/https.md | 2 +-
doc/api/modules.md | 50 ++++++++++++++++-----------------
doc/api/n-api.md | 24 ++++++++--------
doc/api/net.md | 16 +++++------
doc/api/os.md | 4 +--
doc/api/path.md | 6 ++--
doc/api/process.md | 40 +++++++++++++--------------
doc/api/readline.md | 2 +-
doc/api/repl.md | 6 ++--
doc/api/stream.md | 8 +++---
doc/api/tls.md | 22 +++++++--------
doc/api/url.md | 4 +--
doc/api/util.md | 10 +++----
doc/api/v8.md | 2 +-
doc/api/vm.md | 2 +-
doc/api/zlib.md | 20 +++++++-------
33 files changed, 264 insertions(+), 264 deletions(-)
diff --git a/doc/api/addons.md b/doc/api/addons.md
index c6802530f6dc67..03feb8ec619ed5 100644
--- a/doc/api/addons.md
+++ b/doc/api/addons.md
@@ -101,7 +101,7 @@ Addon module name is `addon`.
Once the source code has been written, it must be compiled into the binary
`addon.node` file. To do so, create a file called `binding.gyp` in the
top-level of the project describing the build configuration of the module
-using a JSON-like format. This file is used by [node-gyp][] -- a tool written
+using a JSON-like format. This file is used by [node-gyp][] — a tool written
specifically to compile Node.js Addons.
```json
diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md
index 781509900cc4c9..a80e70758a37d3 100644
--- a/doc/api/async_hooks.md
+++ b/doc/api/async_hooks.md
@@ -582,7 +582,7 @@ asyncResource.triggerAsyncId();
* `type` {string} The type of async event.
* `options` {Object}
* `triggerAsyncId` {number} The ID of the execution context that created this
- async event. **Default:** `executionAsyncId()`
+ async event. **Default:** `executionAsyncId()`
* `requireManualDestroy` {boolean} Disables automatic `emitDestroy` when the
object is garbage collected. This usually does not need to be set (even if
`emitDestroy` is called manually), unless the resource's asyncId is retrieved
diff --git a/doc/api/buffer.md b/doc/api/buffer.md
index 3f827088ce5676..8ab7b472605ba6 100644
--- a/doc/api/buffer.md
+++ b/doc/api/buffer.md
@@ -449,7 +449,7 @@ changes:
* `size` {integer} The desired length of the new `Buffer`.
-Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
+Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
[`buffer.constants.MAX_LENGTH`] or smaller than 0, a [`RangeError`] will be
thrown. A zero-length `Buffer` will be created if `size` is 0.
@@ -535,7 +535,7 @@ const buf = Buffer.alloc(5);
console.log(buf);
```
-Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
+Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
[`buffer.constants.MAX_LENGTH`] or smaller than 0, a [`RangeError`] will be
thrown. A zero-length `Buffer` will be created if `size` is 0.
@@ -580,7 +580,7 @@ changes:
* `size` {integer} The desired length of the new `Buffer`.
-Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
+Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
[`buffer.constants.MAX_LENGTH`] or smaller than 0, a [`RangeError`] will be
thrown. A zero-length `Buffer` will be created if `size` is 0.
@@ -626,7 +626,7 @@ added: v5.12.0
* `size` {integer} The desired length of the new `Buffer`.
-Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
+Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
[`buffer.constants.MAX_LENGTH`] or smaller than 0, a [`RangeError`] will be
thrown. A zero-length `Buffer` will be created if `size` is 0.
@@ -2660,7 +2660,7 @@ deprecated: v6.0.0
* `size` {integer} The desired length of the new `SlowBuffer`.
-Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
+Allocates a new `Buffer` of `size` bytes. If the `size` is larger than
[`buffer.constants.MAX_LENGTH`] or smaller than 0, a [`RangeError`] will be
thrown. A zero-length `Buffer` will be created if `size` is 0.
diff --git a/doc/api/child_process.md b/doc/api/child_process.md
index cfdd650b7603b1..620719111c48c8 100755
--- a/doc/api/child_process.md
+++ b/doc/api/child_process.md
@@ -38,7 +38,7 @@ the event loop until the spawned process either exits or is terminated.
For convenience, the `child_process` module provides a handful of synchronous
and asynchronous alternatives to [`child_process.spawn()`][] and
-[`child_process.spawnSync()`][]. *Note that each of these alternatives are
+[`child_process.spawnSync()`][]. *Note that each of these alternatives are
implemented on top of [`child_process.spawn()`][] or [`child_process.spawnSync()`][].*
* [`child_process.exec()`][]: spawns a shell and runs a command within that shell,
@@ -143,8 +143,8 @@ changes:
[Shell Requirements][] and [Default Windows Shell][].
* `timeout` {number} **Default:** `0`
* `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
- stderr. **Default:** `200*1024`. If exceeded, the child process is terminated.
- See caveat at [`maxBuffer` and Unicode][].
+ stderr. **Default:** `200 * 1024`. If exceeded, the child process is
+ terminated. See caveat at [`maxBuffer` and Unicode][].
* `killSignal` {string|integer} **Default:** `'SIGTERM'`
* `uid` {number} Sets the user identity of the process (see setuid(2)).
* `gid` {number} Sets the group identity of the process (see setgid(2)).
@@ -187,7 +187,7 @@ exec('cat *.js bad_file | wc -l', (error, stdout, stderr) => {
```
If a `callback` function is provided, it is called with the arguments
-`(error, stdout, stderr)`. On success, `error` will be `null`. On error,
+`(error, stdout, stderr)`. On success, `error` will be `null`. On error,
`error` will be an instance of [`Error`][]. The `error.code` property will be
the exit code of the child process while `error.signal` will be set to the
signal that terminated the process. Any exit code other than `0` is considered
@@ -257,8 +257,8 @@ changes:
* `encoding` {string} **Default:** `'utf8'`
* `timeout` {number} **Default:** `0`
* `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
- stderr. **Default:** `200*1024` If exceeded, the child process is terminated.
- See caveat at [`maxBuffer` and Unicode][].
+ stderr. **Default:** `200 * 1024` If exceeded, the child process is
+ terminated. See caveat at [`maxBuffer` and Unicode][].
* `killSignal` {string|integer} **Default:** `'SIGTERM'`
* `uid` {number} Sets the user identity of the process (see setuid(2)).
* `gid` {number} Sets the group identity of the process (see setgid(2)).
@@ -536,7 +536,7 @@ disabled*.
On non-Windows platforms, if `options.detached` is set to `true`, the child
process will be made the leader of a new process group and session. Note that
child processes may continue running after the parent exits regardless of
-whether they are detached or not. See setsid(2) for more information.
+whether they are detached or not. See setsid(2) for more information.
By default, the parent will wait for the detached child to exit. To prevent
the parent from waiting for a given `subprocess`, use the `subprocess.unref()`
@@ -706,8 +706,8 @@ changes:
* `killSignal` {string|integer} The signal value to be used when the spawned
process will be killed. **Default:** `'SIGTERM'`
* `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
- stderr. **Default:** `200*1024` If exceeded, the child process is terminated.
- See caveat at [`maxBuffer` and Unicode][].
+ stderr. **Default:** `200 * 1024` If exceeded, the child process is
+ terminated. See caveat at [`maxBuffer` and Unicode][].
* `encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`
* `windowsHide` {boolean} Hide the subprocess console window that would
normally be created on Windows systems. **Default:** `false`.
@@ -767,8 +767,8 @@ changes:
* `killSignal` {string|integer} The signal value to be used when the spawned
process will be killed. **Default:** `'SIGTERM'`
* `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
- stderr. **Default:** `200*1024` If exceeded, the child process is terminated.
- See caveat at [`maxBuffer` and Unicode][].
+ stderr. **Default:** `200 * 1024` If exceeded, the child process is
+ terminated. See caveat at [`maxBuffer` and Unicode][].
* `encoding` {string} The encoding used for all stdio inputs and outputs.
**Default:** `'buffer'`
* `windowsHide` {boolean} Hide the subprocess console window that would
@@ -779,12 +779,12 @@ The `child_process.execSync()` method is generally identical to
[`child_process.exec()`][] with the exception that the method will not return until
the child process has fully closed. When a timeout has been encountered and
`killSignal` is sent, the method won't return until the process has completely
-exited. *Note that if the child process intercepts and handles the `SIGTERM`
+exited. *Note that if the child process intercepts and handles the `SIGTERM`
signal and doesn't exit, the parent process will wait until the child
process has exited.*
If the process times out or has a non-zero exit code, this method ***will***
-throw. The [`Error`][] object will contain the entire result from
+throw. The [`Error`][] object will contain the entire result from
[`child_process.spawnSync()`][]
*Note*: Never pass unsanitized user input to this function. Any input
@@ -825,8 +825,8 @@ changes:
* `killSignal` {string|integer} The signal value to be used when the spawned
process will be killed. **Default:** `'SIGTERM'`
* `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
- stderr. **Default:** `200*1024` If exceeded, the child process is terminated.
- See caveat at [`maxBuffer` and Unicode][].
+ stderr. **Default:** `200 * 1024` If exceeded, the child process is
+ terminated. See caveat at [`maxBuffer` and Unicode][].
* `encoding` {string} The encoding used for all stdio inputs and outputs.
**Default:** `'buffer'`
* `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses
@@ -1169,7 +1169,7 @@ properties:
Defaults to `false`.
The optional `callback` is a function that is invoked after the message is
-sent but before the child may have received it. The function is called with a
+sent but before the child may have received it. The function is called with a
single argument: `null` on success, or an [`Error`][] object on failure.
If no `callback` function is provided and the message cannot be sent, an
diff --git a/doc/api/cli.md b/doc/api/cli.md
index 2e918c2876c1a8..3192d846e77933 100644
--- a/doc/api/cli.md
+++ b/doc/api/cli.md
@@ -454,7 +454,7 @@ added: v8.0.0
A space-separated list of command line options. `options...` are interpreted as
if they had been specified on the command line before the actual command line
-(so they can be overridden). Node will exit with an error if an option that is
+(so they can be overridden). Node will exit with an error if an option that is
not allowed in the environment is used, such as `-p` or a script file.
Node options that are allowed are:
@@ -516,7 +516,7 @@ added: v3.0.0
Path to the file used to store the persistent REPL history. The default path is
`~/.node_repl_history`, which is overridden by this variable. Setting the value
-to an empty string (`""` or `" "`) disables persistent REPL history.
+to an empty string (`''` or `' '`) disables persistent REPL history.
### `NODE_EXTRA_CA_CERTS=file`
@@ -601,7 +601,7 @@ reason any of these APIs takes a long time, other (seemingly unrelated) APIs
that run in libuv's threadpool will experience degraded performance. In order to
mitigate this issue, one potential solution is to increase the size of libuv's
threadpool by setting the `'UV_THREADPOOL_SIZE'` environment variable to a value
-greater than `4` (its current default value). For more information, see the
+greater than `4` (its current default value). For more information, see the
[libuv threadpool documentation][].
[`--openssl-config`]: #cli_openssl_config_file
diff --git a/doc/api/cluster.md b/doc/api/cluster.md
index 3b56b4888a696e..2c42c9e701adb4 100644
--- a/doc/api/cluster.md
+++ b/doc/api/cluster.md
@@ -92,8 +92,8 @@ Node.js process and a cluster worker differs:
the worker to use the supplied handle, rather than talk to the master
process.
3. `server.listen(0)` Normally, this will cause servers to listen on a
- random port. However, in a cluster, each worker will receive the
- same "random" port each time they do `listen(0)`. In essence, the
+ random port. However, in a cluster, each worker will receive the
+ same "random" port each time they do `listen(0)`. In essence, the
port is random the first time, but predictable thereafter. To listen
on a unique port, generate a port number based on the cluster worker ID.
@@ -103,8 +103,8 @@ objects for things like sessions and login.
Because workers are all separate processes, they can be killed or
re-spawned depending on a program's needs, without affecting other
-workers. As long as there are some workers still alive, the server will
-continue to accept connections. If no workers are alive, existing connections
+workers. As long as there are some workers still alive, the server will
+continue to accept connections. If no workers are alive, existing connections
will be dropped and new connections will be refused. Node.js does not
automatically manage the number of workers, however. It is the application's
responsibility to manage the worker pool based on its own needs.
@@ -499,7 +499,7 @@ Emitted after the worker IPC channel has disconnected. This can occur when a
worker exits gracefully, is killed, or is disconnected manually (such as with
worker.disconnect()).
-There may be a delay between the `'disconnect'` and `'exit'` events. These events
+There may be a delay between the `'disconnect'` and `'exit'` events. These events
can be used to detect if the process is stuck in a cleanup or if there are
long-living connections.
@@ -590,7 +590,7 @@ The `addressType` is one of:
* `4` (TCPv4)
* `6` (TCPv6)
* `-1` (unix domain socket)
-* `"udp4"` or `"udp6"` (UDP v4 or v6)
+* `'udp4'` or `'udp6'` (UDP v4 or v6)
## Event: 'message'
-* Returns {number} the `SO_RCVBUF` socket receive buffer size in bytes.
+* Returns: {number} the `SO_RCVBUF` socket receive buffer size in bytes.
### socket.getSendBufferSize()
-* Returns {number} the `SO_SNDBUF` socket send buffer size in bytes.
+* Returns: {number} the `SO_SNDBUF` socket send buffer size in bytes.
### socket.ref()
Sometimes, the domain in use is not the one that ought to be used for a
-specific event emitter. Or, the event emitter could have been created
+specific event emitter. Or, the event emitter could have been created
in the context of one domain, but ought to instead be bound to some
other domain.
@@ -280,7 +280,7 @@ Returns a new Domain object.
The Domain class encapsulates the functionality of routing errors and
uncaught exceptions to the active Domain object.
-Domain is a child class of [`EventEmitter`][]. To handle the errors that it
+Domain is a child class of [`EventEmitter`][]. To handle the errors that it
catches, listen to its `'error'` event.
### domain.members
@@ -294,13 +294,13 @@ to the domain.
* `emitter` {EventEmitter|Timer} emitter or timer to be added to the domain
-Explicitly adds an emitter to the domain. If any event handlers called by
+Explicitly adds an emitter to the domain. If any event handlers called by
the emitter throw an error, or if the emitter emits an `'error'` event, it
will be routed to the domain's `'error'` event, just like with implicit
binding.
This also works with timers that are returned from [`setInterval()`][] and
-[`setTimeout()`][]. If their callback function throws, it will be caught by
+[`setTimeout()`][]. If their callback function throws, it will be caught by
the domain 'error' handler.
If the Timer or EventEmitter was already bound to a domain, it is removed
@@ -312,7 +312,7 @@ from that one, and bound to this one instead.
* Returns: {Function} The bound function
The returned function will be a wrapper around the supplied callback
-function. When the returned function is called, any errors that are
+function. When the returned function is called, any errors that are
thrown will be routed to the domain's `'error'` event.
#### Example
@@ -336,7 +336,7 @@ d.on('error', (er) => {
### domain.dispose()
-> Stability: 0 - Deprecated. Please recover from failed IO actions
+> Stability: 0 - Deprecated. Please recover from failed IO actions
> explicitly via error event handlers set on the domain.
Once `dispose` has been called, the domain will no longer be used by callbacks
@@ -382,7 +382,7 @@ without exiting the domain.
* `callback` {Function} The callback function
* Returns: {Function} The intercepted function
-This method is almost identical to [`domain.bind(callback)`][]. However, in
+This method is almost identical to [`domain.bind(callback)`][]. However, in
addition to catching thrown errors, it will also intercept [`Error`][]
objects sent as the first argument to the function.
@@ -419,7 +419,7 @@ d.on('error', (er) => {
* `emitter` {EventEmitter|Timer} emitter or timer to be removed from the domain
-The opposite of [`domain.add(emitter)`][]. Removes domain handling from the
+The opposite of [`domain.add(emitter)`][]. Removes domain handling from the
specified emitter.
### domain.run(fn[, ...args])
diff --git a/doc/api/errors.md b/doc/api/errors.md
index 2088fea0de6552..f2de6717a57ee2 100755
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -107,7 +107,7 @@ pass or fail).
For *all* `EventEmitter` objects, if an `'error'` event handler is not
provided, the error will be thrown, causing the Node.js process to report an
-unhandled exception and crash unless either: The [`domain`][domains] module is
+unhandled exception and crash unless either: The [`domain`][domains] module is
used appropriately or a handler has been registered for the
[`process.on('uncaughtException')`][] event.
@@ -133,7 +133,7 @@ exactly how errors raised by those methods are propagated.
Most asynchronous methods exposed by the Node.js core API follow an idiomatic
-pattern referred to as an _error-first callback_ (sometimes referred to as
+pattern referred to as an _error-first callback_ (sometimes referred to as
a _Node.js style callback_). With this pattern, a callback function is passed
to the method as an argument. When the operation either completes or an error
is raised, the callback function is called with
@@ -156,7 +156,7 @@ fs.readFile('/some/file/that/does-exist', errorFirstCallback);
```
The JavaScript `try / catch` mechanism **cannot** be used to intercept errors
-generated by asynchronous APIs. A common mistake for beginners is to try to
+generated by asynchronous APIs. A common mistake for beginners is to try to
use `throw` inside an error-first callback:
```js
@@ -209,7 +209,7 @@ provided text message. If an object is passed as `message`, the text message
is generated by calling `message.toString()`. The `error.stack` property will
represent the point in the code at which `new Error()` was called. Stack traces
are dependent on [V8's stack trace API][]. Stack traces extend only to either
-(a) the beginning of *synchronous code execution*, or (b) the number of frames
+(a) the beginning of *synchronous code execution*, or (b) the number of frames
given by the property `Error.stackTraceLimit`, whichever is smaller.
### Error.captureStackTrace(targetObject[, constructorOpt])
@@ -526,7 +526,7 @@ found [here][online].
- `EACCES` (Permission denied): An attempt was made to access a file in a way
forbidden by its file access permissions.
-- `EADDRINUSE` (Address already in use): An attempt to bind a server
+- `EADDRINUSE` (Address already in use): An attempt to bind a server
([`net`][], [`http`][], or [`https`][]) to a local address failed due to
another server on the local system already occupying that address.
@@ -554,14 +554,14 @@ found [here][online].
`ulimit -n 2048` in the same shell that will run the Node.js process.
- `ENOENT` (No such file or directory): Commonly raised by [`fs`][] operations
- to indicate that a component of the specified pathname does not exist -- no
+ to indicate that a component of the specified pathname does not exist — no
entity (file or directory) could be found by the given path.
- `ENOTDIR` (Not a directory): A component of the given pathname existed, but
was not a directory as expected. Commonly raised by [`fs.readdir`][].
- `ENOTEMPTY` (Directory not empty): A directory with entries was the target
- of an operation that requires an empty directory -- usually [`fs.unlink`][].
+ of an operation that requires an empty directory — usually [`fs.unlink`][].
- `EPERM` (Operation not permitted): An attempt was made to perform an
operation that requires elevated privileges.
@@ -573,7 +573,7 @@ found [here][online].
- `ETIMEDOUT` (Operation timed out): A connect or send request failed because
the connected party did not properly respond after a period of time. Usually
- encountered by [`http`][] or [`net`][] -- often a sign that a `socket.end()`
+ encountered by [`http`][] or [`net`][] — often a sign that a `socket.end()`
was not properly called.
diff --git a/doc/api/esm.md b/doc/api/esm.md
index b90927c0d57cec..926555fc771484 100644
--- a/doc/api/esm.md
+++ b/doc/api/esm.md
@@ -132,12 +132,12 @@ module. This can be one of the following:
| `format` | Description |
| --- | --- |
-| `"esm"` | Load a standard JavaScript module |
-| `"commonjs"` | Load a node-style CommonJS module |
-| `"builtin"` | Load a node builtin CommonJS module |
-| `"json"` | Load a JSON file |
-| `"addon"` | Load a [C++ Addon][addons] |
-| `"dynamic"` | Use a [dynamic instantiate hook][] |
+| `'esm'` | Load a standard JavaScript module |
+| `'commonjs'` | Load a node-style CommonJS module |
+| `'builtin'` | Load a node builtin CommonJS module |
+| `'json'` | Load a JSON file |
+| `'addon'` | Load a [C++ Addon][addons] |
+| `'dynamic'` | Use a [dynamic instantiate hook][] |
For example, a dummy loader to load JavaScript restricted to browser resolution
rules with only JS file extension and Node builtin modules support could
@@ -191,7 +191,7 @@ would load the module `x.js` as an ES module with relative resolution support
To create a custom dynamic module that doesn't correspond to one of the
existing `format` interpretations, the `dynamicInstantiate` hook can be used.
-This hook is called only for modules that return `format: "dynamic"` from
+This hook is called only for modules that return `format: 'dynamic'` from
the `resolve` hook.
```js
diff --git a/doc/api/fs.md b/doc/api/fs.md
index d4ee09bd0b9afe..85add1571691ba 100644
--- a/doc/api/fs.md
+++ b/doc/api/fs.md
@@ -6,7 +6,7 @@
-File I/O is provided by simple wrappers around standard POSIX functions. To
+File I/O is provided by simple wrappers around standard POSIX functions. To
use this module do `require('fs')`. All the methods have asynchronous and
synchronous forms.
@@ -68,7 +68,7 @@ fs.rename('/tmp/hello', '/tmp/world', (err) => {
In busy processes, the programmer is _strongly encouraged_ to use the
asynchronous versions of these calls. The synchronous versions will block
-the entire process until they complete--halting all connections.
+the entire process until they complete — halting all connections.
The relative path to a filename can be used. Remember, however, that this path
will be relative to `process.cwd()`.
@@ -369,16 +369,16 @@ value, will not be reflected in the corresponding alternate representation.
The times in the stat object have the following semantics:
-* `atime` "Access Time" - Time when file data last accessed. Changed
+* `atime` "Access Time" - Time when file data last accessed. Changed
by the mknod(2), utimes(2), and read(2) system calls.
* `mtime` "Modified Time" - Time when file data last modified.
Changed by the mknod(2), utimes(2), and write(2) system calls.
* `ctime` "Change Time" - Time when file status was last changed
- (inode data modification). Changed by the chmod(2), chown(2),
+ (inode data modification). Changed by the chmod(2), chown(2),
link(2), mknod(2), rename(2), unlink(2), utimes(2),
read(2), and write(2) system calls.
-* `birthtime` "Birth Time" - Time of file creation. Set once when the
- file is created. On filesystems where birthtime is not available,
+* `birthtime` "Birth Time" - Time of file creation. Set once when the
+ file is created. On filesystems where birthtime is not available,
this field may instead hold either the `ctime` or
`1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). Note that this
value may be greater than `atime` or `mtime` in this case. On Darwin
@@ -387,7 +387,7 @@ The times in the stat object have the following semantics:
utimes(2) system call.
Prior to Node v0.12, the `ctime` held the `birthtime` on Windows
-systems. Note that as of v0.12, `ctime` is not "creation time", and
+systems. Note that as of v0.12, `ctime` is not "creation time", and
on Unix systems, it never was.
## Class: fs.WriteStream
@@ -862,7 +862,7 @@ changes:
* `callback` {Function}
* `err` {Error}
-Asynchronous close(2). No arguments other than a possible exception are given
+Asynchronous close(2). No arguments other than a possible exception are given
to the completion callback.
## fs.closeSync(fd)
@@ -1009,7 +1009,7 @@ const defaults = {
```
`options` can include `start` and `end` values to read a range of bytes from
-the file instead of the entire file. Both `start` and `end` are inclusive and
+the file instead of the entire file. Both `start` and `end` are inclusive and
start counting at 0. If `fd` is specified and `start` is omitted or `undefined`,
`fs.createReadStream()` reads sequentially from the current file position.
The `encoding` can be any one of those accepted by [`Buffer`][].
@@ -1079,7 +1079,7 @@ const defaults = {
```
`options` may also include a `start` option to allow writing data at
-some position past the beginning of the file. Modifying a file rather
+some position past the beginning of the file. Modifying a file rather
than replacing it may require a `flags` mode of `r+` rather than the
default mode `w`. The `encoding` can be any one of those accepted by
[`Buffer`][].
@@ -1115,7 +1115,7 @@ deprecated: v1.0.0
* `exists` {boolean}
Test whether or not the given path exists by checking with the file system.
-Then call the `callback` argument with either true or false. Example:
+Then call the `callback` argument with either true or false. Example:
```js
fs.exists('/etc/passwd', (exists) => {
@@ -1809,7 +1809,7 @@ to a non-existent file. The exclusive flag may or may not work with network file
systems.
`flags` can also be a number as documented by open(2); commonly used constants
-are available from `fs.constants`. On Windows, flags are translated to
+are available from `fs.constants`. On Windows, flags are translated to
their equivalent ones where applicable, e.g. `O_WRONLY` to `FILE_GENERIC_WRITE`,
or `O_EXCL|O_CREAT` to `CREATE_NEW`, as accepted by CreateFileW.
@@ -1923,7 +1923,7 @@ changes:
* `err` {Error}
* `files` {string[]|Buffer[]}
-Asynchronous readdir(3). Reads the contents of a directory.
+Asynchronous readdir(3). Reads the contents of a directory.
The callback gets two arguments `(err, files)` where `files` is an array of
the names of the files in the directory excluding `'.'` and `'..'`.
@@ -2468,7 +2468,7 @@ Calling `fs.unwatchFile()` with a filename that is not being watched is a
no-op, not an error.
*Note*: [`fs.watch()`][] is more efficient than `fs.watchFile()` and
-`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`
+`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`
and `fs.unwatchFile()` when possible.
## fs.utimes(path, atime, mtime, callback)
@@ -2559,12 +2559,12 @@ changes:
* `filename` {string|Buffer}
Watch for changes on `filename`, where `filename` is either a file or a
-directory. The returned object is a [`fs.FSWatcher`][].
+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 `(eventType, filename)`. `eventType` 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.
@@ -2626,7 +2626,7 @@ content, and one for truncation).
Providing `filename` argument in the callback is only supported on Linux,
-macOS, Windows, and AIX. Even on supported platforms, `filename` is not always
+macOS, Windows, and AIX. Even on supported platforms, `filename` is not always
guaranteed to be provided. Therefore, don't assume that `filename` argument is
always provided in the callback, and have some fallback logic if it is null.
@@ -2775,7 +2775,7 @@ changes:
* `written` {integer}
* `string` {string}
-Write `string` to the file specified by `fd`. If `string` is not a string, then
+Write `string` to the file specified by `fd`. If `string` is not a string, then
the value will be coerced to one.
`position` refers to the offset from the beginning of the file where this data
diff --git a/doc/api/http.md b/doc/api/http.md
index cdd6bfd8a4d0fb..49083e2193953c 100644
--- a/doc/api/http.md
+++ b/doc/api/http.md
@@ -9,7 +9,7 @@ To use the HTTP server and client one must `require('http')`.
The HTTP interfaces in Node.js are designed to support many features
of the protocol which have been traditionally difficult to use.
In particular, large, possibly chunk-encoded, messages. The interface is
-careful to never buffer entire requests or responses--the
+careful to never buffer entire requests or responses — the
user is able to stream data.
HTTP message headers are represented by an object like this:
@@ -33,7 +33,7 @@ parse the actual headers or the body.
See [`message.headers`][] for details on how duplicate headers are handled.
The raw headers as they were received are retained in the `rawHeaders`
-property, which is an array of `[key, value, key2, value2, ...]`. For
+property, which is an array of `[key, value, key2, value2, ...]`. For
example, the previous message header object might have a `rawHeaders`
list like the following:
@@ -122,9 +122,9 @@ added: v0.3.4
for TCP Keep-Alive packets. Ignored when the
`keepAlive` option is `false` or `undefined`. Defaults to `1000`.
* `maxSockets` {number} Maximum number of sockets to allow per
- host. Defaults to `Infinity`.
+ host. Defaults to `Infinity`.
* `maxFreeSockets` {number} Maximum number of sockets to leave open
- in a free state. Only relevant if `keepAlive` is set to `true`.
+ in a free state. Only relevant if `keepAlive` is set to `true`.
Defaults to `256`.
The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
@@ -203,9 +203,9 @@ added: v0.11.4
Destroy any sockets that are currently in use by the agent.
-It is usually not necessary to do this. However, if using an
+It is usually not necessary to do this. However, if using an
agent with `keepAlive` enabled, then it is best to explicitly shut down
-the agent when it will no longer be used. Otherwise,
+the agent when it will no longer be used. Otherwise,
sockets may hang open for quite a long time before the server
terminates them.
@@ -217,7 +217,7 @@ added: v0.11.4
* {Object}
An object which contains arrays of sockets currently awaiting use by
-the agent when `keepAlive` is enabled. Do not modify.
+the agent when `keepAlive` is enabled. Do not modify.
### agent.getName(options)
-This object is created internally and returned from [`http.request()`][]. It
-represents an _in-progress_ request whose header has already been queued. The
+This object is created internally and returned from [`http.request()`][]. It
+represents an _in-progress_ request whose header has already been queued. The
header is still mutable using the [`setHeader(name, value)`][],
- [`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will
+ [`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will
be sent along with the first data chunk or when calling [`request.end()`][].
To get the response, add a listener for [`'response'`][] to the request object.
[`'response'`][] will be emitted from the request object when the response
-headers have been received. The [`'response'`][] event is executed with one
+headers have been received. The [`'response'`][] event is executed with one
argument which is an instance of [`http.IncomingMessage`][].
During the [`'response'`][] event, one can add listeners to the
response object; particularly to listen for the `'data'` event.
If no [`'response'`][] handler is added, then the response will be
-entirely discarded. However, if a [`'response'`][] event handler is added,
+entirely discarded. However, if a [`'response'`][] event handler is added,
then the data from the response object **must** be consumed, either by
calling `response.read()` whenever there is a `'readable'` event, or
by adding a `'data'` handler, or by calling the `.resume()` method.
-Until the data is consumed, the `'end'` event will not fire. Also, until
+Until the data is consumed, the `'end'` event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.
@@ -541,7 +541,7 @@ For efficiency reasons, Node.js normally buffers the request headers until
then tries to pack the request headers and data into a single TCP packet.
That's usually desired (it saves a TCP round-trip), but not when the first
-data is not sent until possibly much later. `request.flushHeaders()` bypasses
+data is not sent until possibly much later. `request.flushHeaders()` bypasses
the optimization and kickstarts the request.
### request.getHeader(name)
@@ -669,9 +669,9 @@ added: v0.1.29
* `encoding` {string}
* `callback` {Function}
-Sends a chunk of the body. By calling this method
+Sends a chunk of the body. By calling this method
many times, a request body can be sent to a
-server--in that case it is suggested to use the
+server — in that case it is suggested to use the
`['Transfer-Encoding', 'chunked']` header line when
creating the request.
@@ -853,7 +853,7 @@ added: v0.1.90
* `callback` {Function}
-Stops the server from accepting new connections. See [`net.Server.close()`][].
+Stops the server from accepting new connections. See [`net.Server.close()`][].
### server.listen()
@@ -896,7 +896,7 @@ If there is a `'timeout'` event listener on the Server object, then it
will be called with the timed-out socket as an argument.
By default, the Server's timeout value is 2 minutes, and sockets are
-destroyed automatically if they time out. However, if a callback is assigned
+destroyed automatically if they time out. However, if a callback is assigned
to the Server's `'timeout'` event, timeouts must be handled explicitly.
Returns `server`.
@@ -941,7 +941,7 @@ value only affects new connections to the server, not any existing connections.
added: v0.1.17
-->
-This object is created internally by an HTTP server--not by the user. It is
+This object is created internally by an HTTP server — not by the user. It is
passed as the second parameter to the [`'request'`][] event.
The response implements, but does not inherit from, the [Writable Stream][]
@@ -1161,8 +1161,8 @@ added: v0.4.0
* `name` {string}
* `value` {string | string[]}
-Sets a single header value for implicit headers. If this header already exists
-in the to-be-sent headers, its value will be replaced. Use an array of strings
+Sets a single header value for implicit headers. If this header already exists
+in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name.
Example:
@@ -1202,12 +1202,12 @@ added: v0.9.12
* `msecs` {number}
* `callback` {Function}
-Sets the Socket's timeout value to `msecs`. If a callback is
+Sets the Socket's timeout value to `msecs`. If a callback is
provided, then it is added as a listener on the `'timeout'` event on
the response object.
If no `'timeout'` listener is added to the request, the response, or
-the server, then sockets are destroyed when they time out. If a handler is
+the server, then sockets are destroyed when they time out. If a handler is
assigned to the request, the response, or the server's `'timeout'` events,
timed out sockets must be handled explicitly.
@@ -1487,8 +1487,8 @@ added: v0.11.6
The raw request/response headers list exactly as they were received.
-Note that the keys and values are in the same list. It is *not* a
-list of tuples. So, the even-numbered offsets are key values, and the
+Note that the keys and values are in the same list. It is *not* a
+list of tuples. So, the even-numbered offsets are key values, and the
odd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
@@ -1515,7 +1515,7 @@ added: v0.11.6
* {Array}
The raw request/response trailer keys and values exactly as they were
-received. Only populated at the `'end'` event.
+received. Only populated at the `'end'` event.
### message.setTimeout(msecs, callback)
* `settings` {[Settings Object][]}
-* Returns {undefined}
+* Returns: {undefined}
Updates the current local settings for this `Http2Session` and sends a new
`SETTINGS` frame to the connected HTTP/2 peer.
@@ -1282,7 +1282,7 @@ added: v8.4.0
* Extends: {net.Server}
In `Http2Server`, there is no `'clientError'` event as there is in
-HTTP1. However, there are `'socketError'`, `'sessionError'`, and
+HTTP1. However, there are `'socketError'`, `'sessionError'`, and
`'streamError'`, for error happened on the socket, session, or stream
respectively.
@@ -1609,7 +1609,7 @@ changes:
* ...: Any [`tls.createServer()`][] options can be provided. For
servers, the identity options (`pfx` or `key`/`cert`) are usually required.
* `onRequestHandler` {Function} See [Compatibility API][]
-* Returns {Http2SecureServer}
+* Returns: {Http2SecureServer}
Returns a `tls.Server` instance that creates and manages `Http2Session`
instances.
@@ -1691,7 +1691,7 @@ changes:
[`Duplex`][] stream that is to be used as the connection for this session.
* ...: Any [`net.connect()`][] or [`tls.connect()`][] options can be provided.
* `listener` {Function}
-* Returns {Http2Session}
+* Returns: {Http2Session}
Returns a HTTP/2 client `Http2Session` instance.
@@ -2191,8 +2191,8 @@ added: v8.4.0
The raw request/response headers list exactly as they were received.
-Note that the keys and values are in the same list. It is *not* a
-list of tuples. So, the even-numbered offsets are key values, and the
+Note that the keys and values are in the same list. It is *not* a
+list of tuples. So, the even-numbered offsets are key values, and the
odd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
@@ -2219,7 +2219,7 @@ added: v8.4.0
* {Array}
The raw request/response trailer keys and values exactly as they were
-received. Only populated at the `'end'` event.
+received. Only populated at the `'end'` event.
#### request.setTimeout(msecs, callback)
-This object is created internally by an HTTP server--not by the user. It is
+This object is created internally by an HTTP server — not by the user. It is
passed as the second parameter to the [`'request'`][] event.
The response implements, but does not inherit from, the [Writable Stream][]
@@ -2560,8 +2560,8 @@ added: v8.4.0
* `name` {string}
* `value` {string|string[]}
-Sets a single header value for implicit headers. If this header already exists
-in the to-be-sent headers, its value will be replaced. Use an array of strings
+Sets a single header value for implicit headers. If this header already exists
+in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name.
Example:
@@ -2601,7 +2601,7 @@ added: v8.4.0
* `msecs` {number}
* `callback` {Function}
-Sets the [`Http2Stream`]()'s timeout value to `msecs`. If a callback is
+Sets the [`Http2Stream`]()'s timeout value to `msecs`. If a callback is
provided, then it is added as a listener on the `'timeout'` event on
the response object.
@@ -2760,7 +2760,7 @@ response.writeHead(200, {
```
Note that Content-Length is given in bytes not characters. The
-`Buffer.byteLength()` API may be used to determine the number of bytes in a
+`Buffer.byteLength()` API may be used to determine the number of bytes in a
given encoding. On outbound messages, Node.js does not check if Content-Length
and the length of the body being transmitted are equal or not. However, when
receiving messages, Node.js will automatically reject messages when the
diff --git a/doc/api/https.md b/doc/api/https.md
index 4740986170b39a..daf10ac4a2bb94 100644
--- a/doc/api/https.md
+++ b/doc/api/https.md
@@ -12,7 +12,7 @@ separate module.
added: v0.4.5
-->
-An Agent object for HTTPS similar to [`http.Agent`][]. See [`https.request()`][]
+An Agent object for HTTPS similar to [`http.Agent`][]. See [`https.request()`][]
for more information.
## Class: https.Server
diff --git a/doc/api/modules.md b/doc/api/modules.md
index 07c469c11408ad..6bac6a8b23144b 100644
--- a/doc/api/modules.md
+++ b/doc/api/modules.md
@@ -123,12 +123,12 @@ the version that is symlinked into
Furthermore, to make the module lookup process even more optimal, rather
than putting packages directly in `/usr/lib/node`, we could put them in
-`/usr/lib/node_modules//`. Then Node.js will not bother
+`/usr/lib/node_modules//`. Then Node.js will not bother
looking for missing dependencies in `/usr/node_modules` or `/node_modules`.
In order to make modules available to the Node.js REPL, it might be useful to
also add the `/usr/lib/node_modules` folder to the `$NODE_PATH` environment
-variable. Since the module lookups using `node_modules` folders are all
+variable. Since the module lookups using `node_modules` folders are all
relative, and based on the real path of the files making the calls to
`require()`, the packages themselves can be anywhere.
@@ -196,12 +196,12 @@ NODE_MODULES_PATHS(START)
-Modules are cached after the first time they are loaded. This means
+Modules are cached after the first time they are loaded. This means
(among other things) that every call to `require('foo')` will get
exactly the same object returned, if it would resolve to the same file.
Multiple calls to `require('foo')` may not cause the module code to be
-executed multiple times. This is an important feature. With it,
+executed multiple times. This is an important feature. With it,
"partially done" objects can be returned, thus allowing transitive
dependencies to be loaded even when they would cause cycles.
@@ -212,7 +212,7 @@ that function.
-Modules are cached based on their resolved filename. Since modules may
+Modules are cached based on their resolved filename. Since modules may
resolve to a different filename based on the location of the calling
module (loading from `node_modules` folders), it is not a *guarantee*
that `require('foo')` will always return the exact same object, if it
@@ -228,14 +228,14 @@ irrespective of whether or not `./foo` and `./FOO` are the same file.
-Node.js has several modules compiled into the binary. These modules are
+Node.js has several modules compiled into the binary. These modules are
described in greater detail elsewhere in this documentation.
The core modules are defined within Node.js's source and are located in the
`lib/` folder.
Core modules are always preferentially loaded if their identifier is
-passed to `require()`. For instance, `require('http')` will always
+passed to `require()`. For instance, `require('http')` will always
return the built in HTTP module, even if there is a file by that name.
## Cycles
@@ -275,13 +275,13 @@ console.log('b done');
console.log('main starting');
const a = require('./a.js');
const b = require('./b.js');
-console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
+console.log('in main, a.done = %j, b.done = %j', a.done, b.done);
```
-When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that
-point, `b.js` tries to load `a.js`. In order to prevent an infinite
+When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that
+point, `b.js` tries to load `a.js`. In order to prevent an infinite
loop, an **unfinished copy** of the `a.js` exports object is returned to the
-`b.js` module. `b.js` then finishes loading, and its `exports` object is
+`b.js` module. `b.js` then finishes loading, and its `exports` object is
provided to the `a.js` module.
By the time `main.js` has loaded both modules, they're both finished.
@@ -296,7 +296,7 @@ in b, a.done = false
b done
in a, b.done = true
a done
-in main, a.done=true, b.done=true
+in main, a.done = true, b.done = true
```
Careful planning is required to allow cyclic module dependencies to work
@@ -314,7 +314,7 @@ required filename with the added extensions: `.js`, `.json`, and finally
parsed as JSON text files. `.node` files are interpreted as compiled addon
modules loaded with `dlopen`.
-A required module prefixed with `'/'` is an absolute path to the file. For
+A required module prefixed with `'/'` is an absolute path to the file. For
example, `require('/home/marco/foo.js')` will load the file at
`/home/marco/foo.js`.
@@ -338,7 +338,7 @@ There are three ways in which a folder may be passed to `require()` as
an argument.
The first is to create a `package.json` file in the root of the folder,
-which specifies a `main` module. An example package.json file might
+which specifies a `main` module. An example package.json file might
look like this:
```json
@@ -352,7 +352,7 @@ If this was in a folder at `./some-library`, then
This is the extent of Node.js's awareness of package.json files.
-*Note*: If the file specified by the `"main"` entry of `package.json` is
+*Note*: If the file specified by the `'main'` entry of `package.json` is
missing and can not be resolved, Node.js will report the entire module as
missing with the default error:
@@ -362,7 +362,7 @@ Error: Cannot find module 'some-library'
If there is no package.json file present in the directory, then Node.js
will attempt to load an `index.js` or `index.node` file out of that
-directory. For example, if there was no package.json file in the above
+directory. For example, if there was no package.json file in the above
example, then `require('./some-library')` would attempt to load:
* `./some-library/index.js`
@@ -415,7 +415,7 @@ varying paths before the current [module resolution][] algorithm was frozen.
`NODE_PATH` is still supported, but is less necessary now that the Node.js
ecosystem has settled on a convention for locating dependent modules.
Sometimes deployments that rely on `NODE_PATH` show surprising behavior
-when people are unaware that `NODE_PATH` must be set. Sometimes a
+when people are unaware that `NODE_PATH` must be set. Sometimes a
module's dependencies change, causing a different version (or even a
different module) to be loaded as the `NODE_PATH` is searched.
@@ -583,14 +583,14 @@ Process files with the extension `.sjs` as `.js`:
require.extensions['.sjs'] = require.extensions['.js'];
```
-**Deprecated** In the past, this list has been used to load
+**Deprecated** In the past, this list has been used to load
non-JavaScript modules into Node.js by compiling them on-demand.
However, in practice, there are much better ways to do this, such as
loading modules via some other Node.js program, or compiling them to
JavaScript ahead of time.
Since the module system is locked, this feature will probably never go
-away. However, it may have subtle bugs and complexities that are best
+away. However, it may have subtle bugs and complexities that are best
left untouched.
Note that the number of file system operations that the module system
@@ -643,7 +643,7 @@ added: v0.1.16
* {Object}
In each module, the `module` free variable is a reference to the object
-representing the current module. For convenience, `module.exports` is
+representing the current module. For convenience, `module.exports` is
also accessible via the `exports` module-global. `module` is not actually
a global but rather local to each module.
@@ -694,7 +694,7 @@ a.on('ready', () => {
Note that assignment to `module.exports` must be done immediately. It cannot be
-done in any callbacks. This does not work:
+done in any callbacks. This does not work:
x.js:
@@ -774,7 +774,7 @@ added: v0.1.16
* {string}
-The identifier for the module. Typically this is the fully resolved
+The identifier for the module. Typically this is the fully resolved
filename.
### module.loaded
@@ -817,7 +817,7 @@ The `module.require` method provides a way to load a module as if
`require()` was called from the original module.
*Note*: In order to do this, it is necessary to get a reference to the
-`module` object. Since `require()` returns the `module.exports`, and the
+`module` object. Since `require()` returns the `module.exports`, and the
`module` is typically *only* available within a specific module's code, it must
be explicitly exported in order to be used.
@@ -830,7 +830,7 @@ added: v0.3.7
* {Object}
Provides general utility methods when interacting with instances of
-`Module` -- the `module` variable often seen in file modules. Accessed
+`Module` — the `module` variable often seen in file modules. Accessed
via `require('module')`.
### module.builtinModules
@@ -840,7 +840,7 @@ added: v8.10.0
* {string[]}
-A list of the names of all modules provided by Node.js. Can be used to verify
+A list of the names of all modules provided by Node.js. Can be used to verify
if a module is maintained by a third-party module or not.
[`__dirname`]: #modules_dirname
diff --git a/doc/api/n-api.md b/doc/api/n-api.md
index 689536c227aafd..f9c24fe4a0e2b1 100644
--- a/doc/api/n-api.md
+++ b/doc/api/n-api.md
@@ -14,7 +14,7 @@ compiled for one version to run on later versions of Node.js without
recompilation.
Addons are built/packaged with the same approach/tools
-outlined in the section titled [C++ Addons](addons.html).
+outlined in the section titled [C++ Addons](addons.html).
The only difference is the set of APIs that are used by the native code.
Instead of using the V8 or [Native Abstractions for Node.js][] APIs,
the functions available in the N-API are used.
@@ -308,7 +308,7 @@ where the native code can catch the exception, take the appropriate action,
and then continue. This is only recommended in specific cases
where it is known that the exception can be safely handled. In these
cases [`napi_get_and_clear_last_exception`][] can be used to get and
-clear the exception. On success, result will contain the handle to
+clear the exception. On success, result will contain the handle to
the last JavaScript Object thrown. If it is determined, after
retrieving the exception, the exception cannot be handled after all
it can be re-thrown it with [`napi_throw`][] where error is the
@@ -316,7 +316,7 @@ JavaScript Error object to be thrown.
The following utility functions are also available in case native code
needs to throw an exception or determine if a `napi_value` is an instance
-of a JavaScript `Error` object: [`napi_throw_error`][],
+of a JavaScript `Error` object: [`napi_throw_error`][],
[`napi_throw_type_error`][], [`napi_throw_range_error`][] and
[`napi_is_error`][].
@@ -327,7 +327,7 @@ where result is the napi_value that refers to the newly created
JavaScript Error object.
The Node.js project is adding error codes to all of the errors
-generated internally. The goal is for applications to use these
+generated internally. The goal is for applications to use these
error codes for all error checking. The associated error messages
will remain, but will only be meant to be used for logging and
display with the expectation that the message can change without
@@ -335,7 +335,7 @@ SemVer applying. In order to support this model with N-API, both
in internal functionality and for module specific functionality
(as its good practice), the `throw_` and `create_` functions
take an optional code parameter which is the string for the code
-to be added to the error object. If the optional parameter is NULL
+to be added to the error object. If the optional parameter is NULL
then no code will be associated with the error. If a code is provided,
the name associated with the error is also updated to be:
@@ -344,7 +344,7 @@ originalName [code]
```
where originalName is the original name associated with the error
-and code is the code that was provided. For example if the code
+and code is the code that was provided. For example if the code
is 'ERR_ERROR_1' and a TypeError is being created the name will be:
```text
@@ -2398,7 +2398,7 @@ They can be one or more of the following bitflags:
- `napi_default` - Used to indicate that no explicit attributes are set on the
given property. By default, a property is read only, not enumerable and not
configurable.
-- `napi_writable` - Used to indicate that a given property is writable.
+- `napi_writable` - Used to indicate that a given property is writable.
- `napi_enumerable` - Used to indicate that a given property is enumerable.
- `napi_configurable` - Used to indicate that a given property is
configurable, as defined in
@@ -2430,7 +2430,7 @@ typedef struct {
encoded as UTF8. One of `utf8name` or `name` must be provided for the
property.
- `name`: Optional napi_value that points to a JavaScript string or symbol
-to be used as the key for the property. One of `utf8name` or `name` must
+to be used as the key for the property. One of `utf8name` or `name` must
be provided for the property.
- `value`: The value that's retrieved by a get access of the property if the
property is a data property. If this is passed in, set `getter`, `setter`,
@@ -2883,7 +2883,7 @@ napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_value fn;
- status = napi_create_function(env, nullptr, 0, SayHello, nullptr, &fn);
+ status = napi_create_function(env, nullptr, 0, SayHello, nullptr, &fn);
if (status != napi_ok) return nullptr;
status = napi_set_named_property(env, exports, "sayHello", fn);
@@ -3254,7 +3254,7 @@ napi_status napi_queue_async_work(napi_env env,
napi_async_work work);
```
-[`napi_cancel_async_work`][] can be used if the work needs
+[`napi_cancel_async_work`][] can be used if the work needs
to be cancelled before the work has started execution.
After calling [`napi_cancel_async_work`][], the `complete` callback
@@ -3356,7 +3356,7 @@ napi_status napi_cancel_async_work(napi_env env,
Returns `napi_ok` if the API succeeded.
This API cancels queued work if it has not yet
-been started. If it has already started executing, it cannot be
+been started. If it has already started executing, it cannot be
cancelled and `napi_generic_failure` will be returned. If successful,
the `complete` callback will be invoked with a status value of
`napi_cancelled`. The work should not be deleted before the `complete`
@@ -3494,7 +3494,7 @@ napi_status napi_get_version(napi_env env,
Returns `napi_ok` if the API succeeded.
This API returns the highest N-API version supported by the
-Node.js runtime. N-API is planned to be additive such that
+Node.js runtime. N-API is planned to be additive such that
newer releases of Node.js may support additional API functions.
In order to allow an addon to use a newer function when running with
versions of Node.js that support it, while providing
diff --git a/doc/api/net.md b/doc/api/net.md
index 31e0ca7a596fa7..f281d480304862 100644
--- a/doc/api/net.md
+++ b/doc/api/net.md
@@ -185,8 +185,8 @@ Possible signatures:
* [`server.listen([port][, host][, backlog][, callback])`][`server.listen(port, host)`]
for TCP servers
-This function is asynchronous. When the server starts listening, the
-[`'listening'`][] event will be emitted. The last parameter `callback`
+This function is asynchronous. When the server starts listening, the
+[`'listening'`][] event will be emitted. The last parameter `callback`
will be added as a listener for the [`'listening'`][] event.
All `listen()` methods can take a `backlog` parameter to specify the maximum
@@ -420,8 +420,8 @@ added: v0.1.90
* {Buffer}
-Emitted when data is received. The argument `data` will be a `Buffer` or
-`String`. Encoding of data is set by `socket.setEncoding()`.
+Emitted when data is received. The argument `data` will be a `Buffer` or
+`String`. Encoding of data is set by `socket.setEncoding()`.
(See the [Readable Stream][] section for more information.)
Note that the **data will be lost** if there is no listener when a `Socket`
@@ -459,7 +459,7 @@ added: v0.1.90
* {Error}
-Emitted when an error occurs. The `'close'` event will be called directly
+Emitted when an error occurs. The `'close'` event will be called directly
following this event.
### Event: 'lookup'
@@ -474,9 +474,9 @@ changes:
Emitted after resolving the hostname but before connecting.
Not applicable to UNIX sockets.
-* `err` {Error|null} The error object. See [`dns.lookup()`][].
+* `err` {Error|null} The error object. See [`dns.lookup()`][].
* `address` {string} The IP address.
-* `family` {string|null} The address type. See [`dns.lookup()`][].
+* `family` {string|null} The address type. See [`dns.lookup()`][].
* `host` {string} The hostname.
### Event: 'timeout'
@@ -822,7 +822,7 @@ added: v0.1.90
-->
Sends data on the socket. The second parameter specifies the encoding in the
-case of a string--it defaults to UTF8 encoding.
+case of a string — it defaults to UTF8 encoding.
Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in user memory.
diff --git a/doc/api/os.md b/doc/api/os.md
index 306a11a3b8dd82..f46292b81386ec 100644
--- a/doc/api/os.md
+++ b/doc/api/os.md
@@ -225,7 +225,7 @@ The `os.loadavg()` method returns an array containing the 1, 5, and 15 minute
load averages.
The load average is a measure of system activity, calculated by the operating
-system and expressed as a fractional number. As a rule of thumb, the load
+system and expressed as a fractional number. As a rule of thumb, the load
average should ideally be less than the number of logical CPUs in the system.
The load average is a UNIX-specific concept with no real equivalent on
@@ -404,7 +404,7 @@ added: v6.0.0
* Returns: {Object}
The `os.userInfo()` method returns information about the currently effective
-user -- on POSIX platforms, this is typically a subset of the password file. The
+user — on POSIX platforms, this is typically a subset of the password file. The
returned object includes the `username`, `uid`, `gid`, `shell`, and `homedir`.
On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`.
diff --git a/doc/api/path.md b/doc/api/path.md
index f2015db47048d7..ab6039206fbd91 100644
--- a/doc/api/path.md
+++ b/doc/api/path.md
@@ -163,7 +163,7 @@ changes:
The `path.extname()` method returns the extension of the `path`, from the last
occurrence of the `.` (period) character to end of string in the last portion of
-the `path`. If there is no `.` in the last portion of the `path`, or if the
+the `path`. If there is no `.` in the last portion of the `path`, or if the
first character of the basename of `path` (see `path.basename()`) is `.`, then
an empty string is returned.
@@ -396,7 +396,7 @@ path.parse('/home/user/dir/file.txt');
│ root │ │ name │ ext │
" / home/user/dir / file .txt "
└──────┴──────────────┴──────┴─────┘
-(all spaces in the "" line should be ignored -- they are purely for formatting)
+(all spaces in the "" line should be ignored — they are purely for formatting)
```
On Windows:
@@ -418,7 +418,7 @@ path.parse('C:\\path\\dir\\file.txt');
│ root │ │ name │ ext │
" C:\ path\dir \ file .txt "
└──────┴──────────────┴──────┴─────┘
-(all spaces in the "" line should be ignored -- they are purely for formatting)
+(all spaces in the "" line should be ignored — they are purely for formatting)
```
A [`TypeError`][] is thrown if `path` is not a string.
diff --git a/doc/api/process.md b/doc/api/process.md
index 0fc006067137de..574fc933671d14 100644
--- a/doc/api/process.md
+++ b/doc/api/process.md
@@ -191,7 +191,7 @@ process will exit with a non-zero exit code and the stack trace will be printed.
This is to avoid infinite recursion.
Attempting to resume normally after an uncaught exception can be similar to
-pulling out of the power cord when upgrading a computer -- nine out of ten
+pulling out of the power cord when upgrading a computer — nine out of ten
times nothing happens - but the 10th time, the system becomes corrupted.
The correct use of `'uncaughtException'` is to perform synchronous cleanup
@@ -359,7 +359,7 @@ For example:
process.stdin.resume();
process.on('SIGINT', () => {
- console.log('Received SIGINT. Press Control-D to exit.');
+ console.log('Received SIGINT. Press Control-D to exit.');
});
```
@@ -436,7 +436,7 @@ added: v0.1.27
The `process.argv` property returns an array containing the command line
arguments passed when the Node.js process was launched. The first element will
be [`process.execPath`]. See `process.argv0` if access to the original value of
-`argv[0]` is needed. The second element will be the path to the JavaScript
+`argv[0]` is needed. The second element will be the path to the JavaScript
file being executed. The remaining elements will be any additional command line
arguments.
@@ -920,7 +920,7 @@ added: v0.1.13
The `process.exit()` method instructs Node.js to terminate the process
synchronously with an exit status of `code`. If `code` is omitted, exit uses
either the 'success' code `0` or the value of `process.exitCode` if it has been
-set. Node.js will not terminate until all the [`'exit'`] event listeners are
+set. Node.js will not terminate until all the [`'exit'`] event listeners are
called.
To exit with a 'failure' code:
@@ -1163,7 +1163,7 @@ Windows platforms will throw an error if the `pid` is used to kill a process
group.
*Note*: Even though the name of this function is `process.kill()`, it is
-really just a signal sender, like the `kill` system call. The signal sent may
+really just a signal sender, like the `kill` system call. The signal sent may
do something other than kill the target process.
For example:
@@ -1261,7 +1261,7 @@ Once the current turn of the event loop turn runs to completion, all callbacks
currently in the next tick queue will be called.
This is *not* a simple alias to [`setTimeout(fn, 0)`][]. It is much more
-efficient. It runs before any additional I/O events (including
+efficient. It runs before any additional I/O events (including
timers) fire in subsequent ticks of the event loop.
```js
@@ -1296,7 +1296,7 @@ thing.getReadyForStuff();
```
It is very important for APIs to be either 100% synchronous or 100%
-asynchronous. Consider this example:
+asynchronous. Consider this example:
```js
// WARNING! DO NOT USE! BAD UNSAFE HAZARD!
@@ -1338,7 +1338,7 @@ function definitelyAsync(arg, cb) {
```
*Note*: The next tick queue is completely drained on each pass of the
-event loop **before** additional I/O is processed. As a result,
+event loop **before** additional I/O is processed. As a result,
recursively setting nextTick callbacks will block any I/O from
happening, just like a `while(true);` loop.
@@ -1438,7 +1438,7 @@ tarball.
builds of Node.js and will be missing on all other platforms._
* `lts` {string} a string label identifying the [LTS][] label for this release.
This property only exists for LTS releases and is `undefined` for all other
- release types, including _Current_ releases. Currently the valid values are:
+ release types, including _Current_ releases. Currently the valid values are:
- `'Argon'` for the 4.x LTS line beginning with 4.2.0.
- `'Boron'` for the 6.x LTS line beginning with 6.9.0.
- `'Carbon'` for the 8.x LTS line beginning with 8.9.1.
@@ -1518,7 +1518,7 @@ added: v2.0.0
The `process.seteuid()` method sets the effective user identity of the process.
(See seteuid(2).) The `id` can be passed as either a numeric ID or a username
-string. If a username is specified, the method blocks while resolving the
+string. If a username is specified, the method blocks while resolving the
associated numeric ID.
```js
@@ -1544,7 +1544,7 @@ added: v0.1.31
* `id` {string|number} The group name or ID
The `process.setgid()` method sets the group identity of the process. (See
-setgid(2).) The `id` can be passed as either a numeric ID or a group name
+setgid(2).) The `id` can be passed as either a numeric ID or a group name
string. If a group name is specified, this method blocks while resolving the
associated numeric ID.
@@ -1585,7 +1585,7 @@ added: v0.1.28
-->
The `process.setuid(id)` method sets the user identity of the process. (See
-setuid(2).) The `id` can be passed as either a numeric ID or a username string.
+setuid(2).) The `id` can be passed as either a numeric ID or a username string.
If a username is specified, the method blocks while resolving the associated
numeric ID.
@@ -1747,7 +1747,7 @@ different maximum length restrictions on the title. Usually such restrictions
are quite limited. For instance, on Linux and macOS, `process.title` is limited
to the size of the binary name plus the length of the command line arguments
because setting the `process.title` overwrites the `argv` memory of the
-process. Node.js v0.8 allowed for longer process title strings by also
+process. Node.js v0.8 allowed for longer process title strings by also
overwriting the `environ` memory but that was potentially insecure and
confusing in some (rather obscure) cases.
@@ -1854,7 +1854,7 @@ Will generate an object similar to:
## Exit Codes
Node.js will normally exit with a `0` status code when no more async
-operations are pending. The following status codes are used in other
+operations are pending. The following status codes are used in other
cases:
* `1` **Uncaught Fatal Exception** - There was an uncaught exception,
@@ -1862,12 +1862,12 @@ cases:
handler.
* `2` - Unused (reserved by Bash for builtin misuse)
* `3` **Internal JavaScript Parse Error** - The JavaScript source code
- internal in Node.js's bootstrapping process caused a parse error. This
+ internal in Node.js's bootstrapping process caused a parse error. This
is extremely rare, and generally can only happen during development
of Node.js itself.
* `4` **Internal JavaScript Evaluation Failure** - The JavaScript
source code internal in Node.js's bootstrapping process failed to
- return a function value when evaluated. This is extremely rare, and
+ return a function value when evaluated. This is extremely rare, and
generally can only happen during development of Node.js itself.
* `5` **Fatal Error** - There was a fatal unrecoverable error in V8.
Typically a message will be printed to stderr with the prefix `FATAL
@@ -1877,22 +1877,22 @@ cases:
function was somehow set to a non-function, and could not be called.
* `7` **Internal Exception Handler Run-Time Failure** - There was an
uncaught exception, and the internal fatal exception handler
- function itself threw an error while attempting to handle it. This
+ function itself threw an error while attempting to handle it. This
can happen, for example, if a [`'uncaughtException'`][] or
`domain.on('error')` handler throws an error.
-* `8` - Unused. In previous versions of Node.js, exit code 8 sometimes
+* `8` - Unused. In previous versions of Node.js, exit code 8 sometimes
indicated an uncaught exception.
* `9` - **Invalid Argument** - Either an unknown option was specified,
or an option requiring a value was provided without a value.
* `10` **Internal JavaScript Run-Time Failure** - The JavaScript
source code internal in Node.js's bootstrapping process threw an error
- when the bootstrapping function was called. This is extremely rare,
+ when the bootstrapping function was called. This is extremely rare,
and generally can only happen during development of Node.js itself.
* `12` **Invalid Debug Argument** - The `--inspect` and/or `--inspect-brk`
options were set, but the port number chosen was invalid or unavailable.
* `>128` **Signal Exits** - If Node.js receives a fatal signal such as
`SIGKILL` or `SIGHUP`, then its exit code will be `128` plus the
- value of the signal code. This is a standard POSIX practice, since
+ value of the signal code. This is a standard POSIX practice, since
exit codes are defined to be 7-bit integers, and signal exits set
the high-order bit, and then contain the value of the signal code.
diff --git a/doc/api/readline.md b/doc/api/readline.md
index 42d07da2d0e418..78571d7e993ef8 100644
--- a/doc/api/readline.md
+++ b/doc/api/readline.md
@@ -295,7 +295,7 @@ added: v0.1.98
* `shift` {boolean} `true` to indicate the `` key.
* `name` {string} The name of the a key.
-The `rl.write()` method will write either `data` or a key sequence identified
+The `rl.write()` method will write either `data` or a key sequence identified
by `key` to the `output`. The `key` argument is supported only if `output` is
a [TTY][] text terminal.
diff --git a/doc/api/repl.md b/doc/api/repl.md
index 7a54928e187ae2..1b6013cf4ca4ed 100644
--- a/doc/api/repl.md
+++ b/doc/api/repl.md
@@ -96,7 +96,7 @@ are declared at the global scope.
The default evaluator provides access to any variables that exist in the global
scope. It is possible to expose a variable to the REPL explicitly by assigning
-it to the `context` object associated with each `REPLServer`. For example:
+it to the `context` object associated with each `REPLServer`. For example:
```js
const repl = require('repl');
@@ -398,7 +398,7 @@ changes:
stream upon instantiation.
* `eval` {Function} The function to be used when evaluating each given line
of input. Defaults to an async wrapper for the JavaScript `eval()`
- function. An `eval` function can error with `repl.Recoverable` to indicate
+ function. An `eval` function can error with `repl.Recoverable` to indicate
the input was incomplete and prompt for additional lines.
* `useColors` {boolean} If `true`, specifies that the default `writer`
function should include ANSI color styling to REPL output. If a custom
@@ -467,7 +467,7 @@ environment variables:
- `NODE_REPL_HISTORY` - When a valid path is given, persistent REPL history
will be saved to the specified file rather than `.node_repl_history` in the
- user's home directory. Setting this value to `""` will disable persistent
+ user's home directory. Setting this value to `''` will disable persistent
REPL history. Whitespace will be trimmed from the value.
- `NODE_REPL_HISTORY_SIZE` - Defaults to `1000`. Controls how many lines of
history will be persisted if history is available. Must be a positive number.
diff --git a/doc/api/stream.md b/doc/api/stream.md
index 74173abe34f18c..aed4a1fd90e1d9 100644
--- a/doc/api/stream.md
+++ b/doc/api/stream.md
@@ -901,7 +901,7 @@ added: v0.9.4
-->
* `size` {number} Optional argument to specify how much data to read.
-* Return {string|Buffer|null}
+* Returns: {string|Buffer|null}
The `readable.read()` method pulls some data out of the internal buffer and
returns it. If no data available to be read, `null` is returned. By default,
@@ -1482,7 +1482,7 @@ It is recommended that errors occurring during the processing of the
the callback and passing the error as the first argument. This will cause an
`'error'` event to be emitted by the Writable. Throwing an Error from within
`writable._write()` can result in unexpected and inconsistent behavior depending
-on how the stream is being used. Using the callback ensures consistent and
+on how the stream is being used. Using the callback ensures consistent and
predictable handling of errors.
```js
@@ -1684,7 +1684,7 @@ changes:
read queue. For streams not operating in object mode, `chunk` must be a
string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be
any JavaScript value.
-* `encoding` {string} Encoding of string chunks. Must be a valid
+* `encoding` {string} Encoding of string chunks. Must be a valid
Buffer encoding, such as `'utf8'` or `'ascii'`
* Returns: {boolean} `true` if additional chunks of data may continued to be
pushed; `false` otherwise.
@@ -2117,7 +2117,7 @@ The `transform._transform()` method is prefixed with an underscore because it
is internal to the class that defines it, and should never be called directly by
user programs.
-`transform._transform()` is never called in parallel; streams implement a
+`transform._transform()` is never called in parallel; streams implement a
queue mechanism, and to receive the next chunk, `callback` must be
called, either synchronously or asynchronously.
diff --git a/doc/api/tls.md b/doc/api/tls.md
index 8c82250b2182b3..e60e3fb8364b82 100644
--- a/doc/api/tls.md
+++ b/doc/api/tls.md
@@ -374,7 +374,7 @@ added: v0.6.0
-->
Returns the bound address, the address family name, and port of the
-server as reported by the operating system. See [`net.Server.address()`][] for
+server as reported by the operating system. See [`net.Server.address()`][] for
more information.
### server.close([callback])
@@ -462,7 +462,7 @@ changes:
* `options` {Object}
* `isServer`: The SSL/TLS protocol is asymmetrical, TLSSockets must know if
they are to behave as a server or a client. If `true` the TLS socket will be
- instantiated as a server. Defaults to `false`.
+ instantiated as a server. Defaults to `false`.
* `server` {net.Server} An optional [`net.Server`][] instance.
* `requestCert`: Whether to authenticate the remote peer by requesting a
certificate. Clients always request a server certificate. Servers
@@ -620,7 +620,7 @@ For example:
{ ... another certificate, possibly with a .issuerCertificate ... },
raw: < RAW DER buffer >,
valid_from: 'Nov 11 09:52:22 2009 GMT',
- valid_to: 'Nov 6 09:52:22 2029 GMT',
+ valid_to: 'Nov 6 09:52:22 2029 GMT',
fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF',
serialNumber: 'B9B0D332A1AA5635' }
```
@@ -822,7 +822,7 @@ changes:
rather than creating a new socket. Typically, this is an instance of
[`net.Socket`][], but any `Duplex` stream is allowed.
If this option is specified, `path`, `host` and `port` are ignored,
- except for certificate validation. Usually, a socket is already connected
+ except for certificate validation. Usually, a socket is already connected
when passed to `tls.connect()`, but it can be connected later. Note that
connection/disconnection/destruction of `socket` is the user's
responsibility, calling `tls.connect()` will not cause `net.connect()` to be
@@ -983,7 +983,7 @@ changes:
decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not.
* `key` {string|string[]|Buffer|Buffer[]|Object[]} Optional private keys in
PEM format. PEM allows the option of private keys being encrypted. Encrypted
- keys will be decrypted with `options.passphrase`. Multiple keys using
+ keys will be decrypted with `options.passphrase`. Multiple keys using
different algorithms can be provided either as an array of unencrypted key
strings or buffers, or an array of objects in the form `{pem:
[, passphrase: ]}`. The object form can only occur in
@@ -996,7 +996,7 @@ changes:
consist of the PEM formatted certificate for a provided private `key`,
followed by the PEM formatted intermediate certificates (if any), in order,
and not including the root CA (the root CA must be pre-known to the peer,
- see `ca`). When providing multiple cert chains, they do not have to be in
+ see `ca`). When providing multiple cert chains, they do not have to be in
the same order as their private keys in `key`. If the intermediate
certificates are not provided, the peer will not be able to validate the
certificate, and the handshake will fail.
@@ -1006,7 +1006,7 @@ changes:
using this option. The value can be a string or Buffer, or an Array of
strings and/or Buffers. Any string or Buffer can contain multiple PEM CAs
concatenated together. The peer's certificate must be chainable to a CA
- trusted by the server for the connection to be authenticated. When using
+ trusted by the server for the connection to be authenticated. When using
certificates that are not chainable to a well-known CA, the certificate's CA
must be explicitly specified as a trusted or the connection will fail to
authenticate.
@@ -1018,7 +1018,7 @@ changes:
* `crl` {string|string[]|Buffer|Buffer[]} Optional PEM formatted
CRLs (Certificate Revocation Lists).
* `ciphers` {string} Optional cipher suite specification, replacing the
- default. For more information, see [modifying the default cipher suite][].
+ default. For more information, see [modifying the default cipher suite][].
* `honorCipherOrder` {boolean} Attempt to use the server's cipher suite
preferences instead of the client's. When `true`, causes
`SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see
@@ -1037,8 +1037,8 @@ changes:
for stronger security. If omitted or invalid, the parameters are silently
discarded and DHE ciphers will not be available.
* `secureProtocol` {string} Optional SSL method to use, default is
- `"SSLv23_method"`. The possible values are listed as [SSL_METHODS][], use
- the function names as strings. For example, `"SSLv3_method"` to force SSL
+ `'SSLv23_method'`. The possible values are listed as [SSL_METHODS][], use
+ the function names as strings. For example, `'SSLv3_method'` to force SSL
version 3.
* `secureOptions` {number} Optionally affect the OpenSSL protocol behavior,
which is not usually necessary. This should be used carefully if at all!
@@ -1124,7 +1124,7 @@ changes:
servers, the identity options (`pfx` or `key`/`cert`) are usually required.
* `secureConnectionListener` {Function}
-Creates a new [tls.Server][]. The `secureConnectionListener`, if provided, is
+Creates a new [tls.Server][]. The `secureConnectionListener`, if provided, is
automatically set as a listener for the [`'secureConnection'`][] event.
*Note*: The `ticketKeys` options is automatically shared between `cluster`
diff --git a/doc/api/url.md b/doc/api/url.md
index 00211095627a46..2da532462543b0 100644
--- a/doc/api/url.md
+++ b/doc/api/url.md
@@ -51,7 +51,7 @@ properties of a WHATWG `URL` object.
├─────────────┴─────────────────────┴─────────────────────┴──────────┴────────────────┴───────┤
│ href │
└─────────────────────────────────────────────────────────────────────────────────────────────┘
-(all spaces in the "" line should be ignored -- they are purely for formatting)
+(all spaces in the "" line should be ignored — they are purely for formatting)
```
Parsing the URL string using the WHATWG API:
@@ -556,7 +556,7 @@ Instantiate a new `URLSearchParams` object with an iterable map in a way that
is similar to [`Map`][]'s constructor. `iterable` can be an Array or any
iterable object. That means `iterable` can be another `URLSearchParams`, in
which case the constructor will simply create a clone of the provided
-`URLSearchParams`. Elements of `iterable` are key-value pairs, and can
+`URLSearchParams`. Elements of `iterable` are key-value pairs, and can
themselves be any iterable object.
Duplicate keys are allowed.
diff --git a/doc/api/util.md b/doc/api/util.md
index 52e9e41639e0ca..cbbc5e92732894 100644
--- a/doc/api/util.md
+++ b/doc/api/util.md
@@ -82,9 +82,9 @@ added: v0.11.3
The `util.debuglog()` method is used to create a function that conditionally
writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`
-environment variable. If the `section` name appears within the value of that
+environment variable. If the `section` name appears within the value of that
environment variable, then the returned function operates similar to
-[`console.error()`][]. If not, then the returned function is a no-op.
+[`console.error()`][]. If not, then the returned function is a no-op.
For example:
@@ -102,7 +102,7 @@ it will output something like:
FOO 3245: hello from foo [123]
```
-where `3245` is the process id. If it is not run with that
+where `3245` is the process id. If it is not run with that
environment variable set, then it will not print anything.
Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`
@@ -172,7 +172,7 @@ corresponding argument. Supported placeholders are:
* `%d` - Number (integer or floating point value).
* `%i` - Integer.
* `%f` - Floating point value.
-* `%j` - JSON. Replaced with the string `'[Circular]'` if the argument
+* `%j` - JSON. Replaced with the string `'[Circular]'` if the argument
contains circular references.
* `%o` - Object. A string representation of an object
with generic JavaScript object formatting.
@@ -233,7 +233,7 @@ that the two styles are [semantically incompatible][].
* `constructor` {Function}
* `superConstructor` {Function}
-Inherit the prototype methods from one [constructor][] into another. The
+Inherit the prototype methods from one [constructor][] into another. The
prototype of `constructor` will be set to a new object created from
`superConstructor`.
diff --git a/doc/api/v8.md b/doc/api/v8.md
index 3684a61583cb37..63a4ded9fe96ea 100644
--- a/doc/api/v8.md
+++ b/doc/api/v8.md
@@ -144,7 +144,7 @@ after the VM has started may result in unpredictable behavior, including
crashes and data loss; or it may simply do nothing.
The V8 options available for a version of Node.js may be determined by running
-`node --v8-options`. An unofficial, community-maintained list of options
+`node --v8-options`. An unofficial, community-maintained list of options
and their effects is available [here][].
Usage:
diff --git a/doc/api/vm.md b/doc/api/vm.md
index 41101a5e5cf76f..842b0c8ac20cdd 100644
--- a/doc/api/vm.md
+++ b/doc/api/vm.md
@@ -116,7 +116,7 @@ changes:
will be thrown.
* `breakOnSigint`: if `true`, the execution will be terminated when
`SIGINT` (Ctrl+C) is received. Existing handlers for the
- event that have been attached via `process.on("SIGINT")` will be disabled
+ event that have been attached via `process.on('SIGINT')` will be disabled
during script execution, but will continue to work after that.
If execution is terminated, an [`Error`][] will be thrown.
diff --git a/doc/api/zlib.md b/doc/api/zlib.md
index 7c55b94b26706b..00d3a8c821d2eb 100644
--- a/doc/api/zlib.md
+++ b/doc/api/zlib.md
@@ -64,8 +64,8 @@ header is used to identify the compression encodings actually applied to a
message.
*Note*: the examples given below are drastically simplified to show
-the basic concept. Using `zlib` encoding can be expensive, and the results
-ought to be cached. See [Memory Usage Tuning][] for more information
+the basic concept. Using `zlib` encoding can be expensive, and the results
+ought to be cached. See [Memory Usage Tuning][] for more information
on the speed/memory/compression tradeoffs involved in `zlib` usage.
```js
@@ -165,7 +165,7 @@ The memory requirements for deflate are (in bytes):
(1 << (windowBits + 2)) + (1 << (memLevel + 9))
```
-That is: 128K for windowBits=15 + 128K for memLevel = 8
+That is: 128K for windowBits = 15 + 128K for memLevel = 8
(default values) plus a few kilobytes for small objects.
For example, to reduce the default memory requirements from 256K to 128K, the
@@ -178,20 +178,20 @@ const options = { windowBits: 14, memLevel: 7 };
This will, however, generally degrade compression.
The memory requirements for inflate are (in bytes) `1 << windowBits`.
-That is, 32K for windowBits=15 (default value) plus a few kilobytes
+That is, 32K for windowBits = 15 (default value) plus a few kilobytes
for small objects.
This is in addition to a single internal output slab buffer of size
`chunkSize`, which defaults to 16K.
The speed of `zlib` compression is affected most dramatically by the
-`level` setting. A higher level will result in better compression, but
-will take longer to complete. A lower level will result in less
+`level` setting. A higher level will result in better compression, but
+will take longer to complete. A lower level will result in less
compression, but will be much faster.
In general, greater memory usage options will mean that Node.js has to make
fewer calls to `zlib` because it will be able to process more data on
-each `write` operation. So, this is another factor that affects the
+each `write` operation. So, this is another factor that affects the
speed, at the cost of memory usage.
## Flushing
@@ -233,9 +233,9 @@ added: v0.5.8
All of the constants defined in `zlib.h` are also defined on
`require('zlib').constants`. In the normal course of operations, it will not be
-necessary to use these constants. They are documented so that their presence is
+necessary to use these constants. They are documented so that their presence is
not surprising. This section is taken almost directly from the
-[zlib documentation][]. See for more
+[zlib documentation][]. See for more
details.
*Note*: Previously, the constants were available directly from
@@ -296,7 +296,7 @@ changes:
-Each class takes an `options` object. All options are optional.
+Each class takes an `options` object. All options are optional.
Note that some options are only relevant when compressing, and are
ignored by the decompression classes.
From d2a884edf9de1013284a991302392c1114cfcc95 Mon Sep 17 00:00:00 2001
From: Ben Noordhuis
Date: Thu, 21 Dec 2017 16:27:39 +0100
Subject: [PATCH 053/218] http: fix parsing of binary upgrade response body
Fix a bug where a connection upgrade response with a Transfer-Encoding
header and a body whose first byte is > 127 causes said byte to be
dropped on the floor when passing the remainder of the message to
the 'upgrade' event listeners.
Fixes: https://github.com/nodejs/node/issues/17789
PR-URL: https://github.com/nodejs/node/pull/17806
Fixes: https://github.com/nodejs/node/issues/17789
Reviewed-By: James M Snell
Reviewed-By: Luigi Pinca
Reviewed-By: Tiancheng "Timothy" Gu
Reviewed-By: Richard Lau
Reviewed-By: Colin Ihrig
Reviewed-By: Ruben Bridgewater
---
lib/_http_client.js | 24 ++++++++-----------
lib/_http_common.js | 15 +++---------
lib/_http_server.js | 2 +-
test/parallel/test-http-upgrade-binary.js | 28 +++++++++++++++++++++++
4 files changed, 41 insertions(+), 28 deletions(-)
create mode 100644 test/parallel/test-http-upgrade-binary.js
diff --git a/lib/_http_client.js b/lib/_http_client.js
index a836b772cc05ad..c58be1fc3acdb2 100644
--- a/lib/_http_client.js
+++ b/lib/_http_client.js
@@ -493,7 +493,6 @@ function parserOnIncomingClient(res, shouldKeepAlive) {
var socket = this.socket;
var req = socket._httpMessage;
-
// propagate "domain" setting...
if (req.domain && !res.domain) {
debug('setting "res.domain"');
@@ -506,29 +505,22 @@ function parserOnIncomingClient(res, shouldKeepAlive) {
// We already have a response object, this means the server
// sent a double response.
socket.destroy();
- return;
+ return 0; // No special treatment.
}
req.res = res;
// Responses to CONNECT request is handled as Upgrade.
- if (req.method === 'CONNECT') {
+ const method = req.method;
+ if (method === 'CONNECT') {
res.upgrade = true;
- return 2; // skip body, and the rest
+ return 2; // Skip body and treat as Upgrade.
}
- // Responses to HEAD requests are crazy.
- // HEAD responses aren't allowed to have an entity-body
- // but *can* have a content-length which actually corresponds
- // to the content-length of the entity-body had the request
- // been a GET.
- var isHeadResponse = req.method === 'HEAD';
- debug('AGENT isHeadResponse', isHeadResponse);
-
if (res.statusCode === 100) {
// restart the parser, as this is a continue message.
req.res = null; // Clear res so that we don't hit double-responses.
req.emit('continue');
- return true;
+ return 1; // Skip body but don't treat as Upgrade.
}
if (req.shouldKeepAlive && !shouldKeepAlive && !req.upgradeOrConnect) {
@@ -538,7 +530,6 @@ function parserOnIncomingClient(res, shouldKeepAlive) {
req.shouldKeepAlive = false;
}
-
DTRACE_HTTP_CLIENT_RESPONSE(socket, req);
LTTNG_HTTP_CLIENT_RESPONSE(socket, req);
COUNTER_HTTP_CLIENT_RESPONSE();
@@ -556,7 +547,10 @@ function parserOnIncomingClient(res, shouldKeepAlive) {
if (!handled)
res._dump();
- return isHeadResponse;
+ if (method === 'HEAD')
+ return 1; // Skip body but don't treat as Upgrade.
+
+ return 0; // No special treatment.
}
// client
diff --git a/lib/_http_common.js b/lib/_http_common.js
index ad0dec520d1210..381ffeb807a84e 100644
--- a/lib/_http_common.js
+++ b/lib/_http_common.js
@@ -106,19 +106,10 @@ function parserOnHeadersComplete(versionMajor, versionMinor, headers, method,
parser.incoming.upgrade = upgrade;
- var skipBody = 0; // response to HEAD or CONNECT
+ if (upgrade)
+ return 2; // Skip body and treat as Upgrade.
- if (!upgrade) {
- // For upgraded connections and CONNECT method request, we'll emit this
- // after parser.execute so that we can capture the first part of the new
- // protocol.
- skipBody = parser.onIncoming(parser.incoming, shouldKeepAlive);
- }
-
- if (typeof skipBody !== 'number')
- return skipBody ? 1 : 0;
- else
- return skipBody;
+ return parser.onIncoming(parser.incoming, shouldKeepAlive);
}
// XXX This is a mess.
diff --git a/lib/_http_server.js b/lib/_http_server.js
index 32c39e6160e5a9..be591c437ca083 100644
--- a/lib/_http_server.js
+++ b/lib/_http_server.js
@@ -618,7 +618,7 @@ function parserOnIncoming(server, socket, state, req, keepAlive) {
} else {
server.emit('request', req, res);
}
- return false; // Not a HEAD response. (Not even a response!)
+ return 0; // No special treatment.
}
function resetSocketTimeout(server, socket, state) {
diff --git a/test/parallel/test-http-upgrade-binary.js b/test/parallel/test-http-upgrade-binary.js
new file mode 100644
index 00000000000000..002ac9c564ad1e
--- /dev/null
+++ b/test/parallel/test-http-upgrade-binary.js
@@ -0,0 +1,28 @@
+'use strict';
+const { mustCall } = require('../common');
+const assert = require('assert');
+const http = require('http');
+const net = require('net');
+
+// https://github.com/nodejs/node/issues/17789 - a connection upgrade response
+// that has a Transfer-Encoding header and a body whose first byte is > 127
+// triggers a bug where said byte is skipped over.
+net.createServer(mustCall(function(conn) {
+ conn.write('HTTP/1.1 101 Switching Protocols\r\n' +
+ 'Connection: upgrade\r\n' +
+ 'Transfer-Encoding: chunked\r\n' +
+ 'Upgrade: websocket\r\n' +
+ '\r\n' +
+ '\u0080', 'latin1');
+ this.close();
+})).listen(0, mustCall(function() {
+ http.get({
+ host: this.address().host,
+ port: this.address().port,
+ headers: { 'Connection': 'upgrade', 'Upgrade': 'websocket' },
+ }).on('upgrade', mustCall((res, conn, head) => {
+ assert.strictEqual(head.length, 1);
+ assert.strictEqual(head[0], 128);
+ conn.destroy();
+ }));
+}));
From 7813a0de0a91f1f0210c5fed5654835c10014ab7 Mon Sep 17 00:00:00 2001
From: Joyee Cheung
Date: Mon, 23 Oct 2017 02:04:07 +0800
Subject: [PATCH 054/218] test: introduce test/common/internet.addresses
This commit introduces test/common/internet.address, which
includes a set of addresses for doing internet tests.
These addresses can be overriden using NODE_TEST_* environment
variables.
PR-URL: https://github.com/nodejs/node/pull/16390
Backport-PR-URL: https://github.com/nodejs/node/pull/19706
Reviewed-By: Anna Henningsen
Reviewed-By: Refael Ackermann
Reviewed-By: Gibson Fahnestock
Reviewed-By: Colin Ihrig
Reviewed-By: James M Snell
---
test/common/README.md | 35 ++++++++++++++++++++++++++
test/common/dns.js | 4 ++-
test/common/internet.js | 54 +++++++++++++++++++++++++++++++++++++++++
3 files changed, 92 insertions(+), 1 deletion(-)
create mode 100644 test/common/internet.js
diff --git a/test/common/README.md b/test/common/README.md
index c6a3de0c35a1d0..bb96f88be8308b 100644
--- a/test/common/README.md
+++ b/test/common/README.md
@@ -10,6 +10,7 @@ This directory contains modules used to test the Node.js implementation.
* [DNS module](#dns-module)
* [Duplex pair helper](#duplex-pair-helper)
* [Fixtures module](#fixtures-module)
+* [Internet module](#internet-module)
* [tmpdir module](#tmpdir-module)
* [WPT module](#wpt-module)
@@ -483,6 +484,40 @@ Returns the result of
Returns the result of
`fs.readFileSync(path.join(fixtures.fixturesDir, 'keys', arg), 'enc')`.
+## Internet Module
+
+The `common/internet` module provides utilities for working with
+internet-related tests.
+
+### internet.addresses
+
+* [<Object>]
+ * `INET_HOST` [<String>] A generic host that has registered common
+ DNS records, supports both IPv4 and IPv6, and provides basic HTTP/HTTPS
+ services
+ * `INET4_HOST` [<String>] A host that provides IPv4 services
+ * `INET6_HOST` [<String>] A host that provides IPv6 services
+ * `INET4_IP` [<String>] An accessible IPv4 IP, defaults to the
+ Google Public DNS IPv4 address
+ * `INET6_IP` [<String>] An accessible IPv6 IP, defaults to the
+ Google Public DNS IPv6 address
+ * `INVALID_HOST` [<String>] An invalid host that cannot be resolved
+ * `MX_HOST` [<String>] A host with MX records registered
+ * `SRV_HOST` [<String>] A host with SRV records registered
+ * `PTR_HOST` [<String>] A host with PTR records registered
+ * `NAPTR_HOST` [<String>] A host with NAPTR records registered
+ * `SOA_HOST` [<String>] A host with SOA records registered
+ * `CNAME_HOST` [<String>] A host with CNAME records registered
+ * `NS_HOST` [<String>] A host with NS records registered
+ * `TXT_HOST` [<String>] A host with TXT records registered
+ * `DNS4_SERVER` [<String>] An accessible IPv4 DNS server
+ * `DNS6_SERVER` [<String>] An accessible IPv6 DNS server
+
+A set of addresses for internet-related tests. All properties are configurable
+via `NODE_TEST_*` environment variables. For example, to configure
+`internet.addresses.INET_HOST`, set the environment
+vairable `NODE_TEST_INET_HOST` to a specified host.
+
## tmpdir Module
The `tmpdir` module supports the use of a temporary directory for testing.
diff --git a/test/common/dns.js b/test/common/dns.js
index 6ab3fcbc91278b..432d1b764dde29 100644
--- a/test/common/dns.js
+++ b/test/common/dns.js
@@ -287,4 +287,6 @@ function writeDNSPacket(parsed) {
}));
}
-module.exports = { types, classes, writeDNSPacket, parseDNSPacket };
+module.exports = {
+ types, classes, writeDNSPacket, parseDNSPacket
+};
diff --git a/test/common/internet.js b/test/common/internet.js
new file mode 100644
index 00000000000000..48b532ca8e6606
--- /dev/null
+++ b/test/common/internet.js
@@ -0,0 +1,54 @@
+/* eslint-disable required-modules */
+'use strict';
+
+// Utilities for internet-related tests
+
+const addresses = {
+ // A generic host that has registered common DNS records,
+ // supports both IPv4 and IPv6, and provides basic HTTP/HTTPS services
+ INET_HOST: 'nodejs.org',
+ // A host that provides IPv4 services
+ INET4_HOST: 'nodejs.org',
+ // A host that provides IPv6 services
+ INET6_HOST: 'nodejs.org',
+ // An accessible IPv4 IP,
+ // defaults to the Google Public DNS IPv4 address
+ INET4_IP: '8.8.8.8',
+ // An accessible IPv6 IP,
+ // defaults to the Google Public DNS IPv6 address
+ INET6_IP: '2001:4860:4860::8888',
+ // An invalid host that cannot be resolved
+ // See https://tools.ietf.org/html/rfc2606#section-2
+ INVALID_HOST: 'something.invalid',
+ // A host with MX records registered
+ MX_HOST: 'nodejs.org',
+ // A host with SRV records registered
+ SRV_HOST: '_jabber._tcp.google.com',
+ // A host with PTR records registered
+ PTR_HOST: '8.8.8.8.in-addr.arpa',
+ // A host with NAPTR records registered
+ NAPTR_HOST: 'sip2sip.info',
+ // A host with SOA records registered
+ SOA_HOST: 'nodejs.org',
+ // A host with CNAME records registered
+ CNAME_HOST: 'blog.nodejs.org',
+ // A host with NS records registered
+ NS_HOST: 'nodejs.org',
+ // A host with TXT records registered
+ TXT_HOST: 'nodejs.org',
+ // An accessible IPv4 DNS server
+ DNS4_SERVER: '8.8.8.8',
+ // An accessible IPv4 DNS server
+ DNS6_SERVER: '2001:4860:4860::8888'
+};
+
+for (const key of Object.keys(addresses)) {
+ const envName = `NODE_TEST_${key}`;
+ if (process.env[envName]) {
+ addresses[key] = process.env[envName];
+ }
+}
+
+module.exports = {
+ addresses
+};
From daeb6de8ec1647faa4c0576ac77a29e0299e611e Mon Sep 17 00:00:00 2001
From: Joyee Cheung
Date: Mon, 23 Oct 2017 02:07:54 +0800
Subject: [PATCH 055/218] test: use internet.addresses in internet tests
PR-URL: https://github.com/nodejs/node/pull/16390
Backport-PR-URL: https://github.com/nodejs/node/pull/19706
Reviewed-By: Anna Henningsen
Reviewed-By: Refael Ackermann
Reviewed-By: Gibson Fahnestock
Reviewed-By: Colin Ihrig
Reviewed-By: James M Snell
---
test/internet/test-dns-cares-domains.js | 7 +-
test/internet/test-dns-ipv4.js | 77 +++++++++---------
test/internet/test-dns-ipv6.js | 76 ++++++++++--------
...t-dns-setserver-in-callback-of-resolve4.js | 11 ++-
test/internet/test-dns.js | 80 +++++++++++--------
.../internet/test-http-https-default-ports.js | 5 +-
6 files changed, 142 insertions(+), 114 deletions(-)
diff --git a/test/internet/test-dns-cares-domains.js b/test/internet/test-dns-cares-domains.js
index 62c1847ea29adf..6609758a7daf17 100644
--- a/test/internet/test-dns-cares-domains.js
+++ b/test/internet/test-dns-cares-domains.js
@@ -1,5 +1,6 @@
'use strict';
-require('../common');
+const common = require('../common');
+const { addresses } = require('../common/internet');
const assert = require('assert');
const dns = require('dns');
const domain = require('domain');
@@ -20,8 +21,8 @@ const methods = [
methods.forEach(function(method) {
const d = domain.create();
d.run(function() {
- dns[method]('google.com', function() {
+ dns[method](addresses.INET_HOST, common.mustCall(() => {
assert.strictEqual(process.domain, d, `${method} retains domain`);
- });
+ }));
});
});
diff --git a/test/internet/test-dns-ipv4.js b/test/internet/test-dns-ipv4.js
index d3d5ba22009675..4c6e0ae6865e3f 100644
--- a/test/internet/test-dns-ipv4.js
+++ b/test/internet/test-dns-ipv4.js
@@ -1,5 +1,6 @@
'use strict';
const common = require('../common');
+const { addresses } = require('../common/internet');
const assert = require('assert');
const dns = require('dns');
const net = require('net');
@@ -38,68 +39,72 @@ function checkWrap(req) {
}
TEST(function test_resolve4(done) {
- const req = dns.resolve4('www.google.com',
- common.mustCall((err, ips) => {
- assert.ifError(err);
+ const req = dns.resolve4(
+ addresses.INET4_HOST,
+ common.mustCall((err, ips) => {
+ assert.ifError(err);
- assert.ok(ips.length > 0);
+ assert.ok(ips.length > 0);
- for (let i = 0; i < ips.length; i++) {
- assert.ok(isIPv4(ips[i]));
- }
+ for (let i = 0; i < ips.length; i++) {
+ assert.ok(isIPv4(ips[i]));
+ }
- done();
- }));
+ done();
+ }));
checkWrap(req);
});
TEST(function test_reverse_ipv4(done) {
- const req = dns.reverse('8.8.8.8',
- common.mustCall((err, domains) => {
- assert.ifError(err);
+ const req = dns.reverse(
+ addresses.INET4_IP,
+ common.mustCall((err, domains) => {
+ assert.ifError(err);
- assert.ok(domains.length > 0);
+ assert.ok(domains.length > 0);
- for (let i = 0; i < domains.length; i++) {
- assert.ok(domains[i]);
- assert.ok(typeof domains[i] === 'string');
- }
+ for (let i = 0; i < domains.length; i++) {
+ assert.ok(domains[i]);
+ assert.ok(typeof domains[i] === 'string');
+ }
- done();
- }));
+ done();
+ }));
checkWrap(req);
});
TEST(function test_lookup_ipv4_explicit(done) {
- const req = dns.lookup('www.google.com', 4,
- common.mustCall((err, ip, family) => {
- assert.ifError(err);
- assert.ok(net.isIPv4(ip));
- assert.strictEqual(family, 4);
+ const req = dns.lookup(
+ addresses.INET4_HOST, 4,
+ common.mustCall((err, ip, family) => {
+ assert.ifError(err);
+ assert.ok(net.isIPv4(ip));
+ assert.strictEqual(family, 4);
- done();
- }));
+ done();
+ }));
checkWrap(req);
});
TEST(function test_lookup_ipv4_implicit(done) {
- const req = dns.lookup('www.google.com',
- common.mustCall((err, ip, family) => {
- assert.ifError(err);
- assert.ok(net.isIPv4(ip));
- assert.strictEqual(family, 4);
+ const req = dns.lookup(
+ addresses.INET4_HOST,
+ common.mustCall((err, ip, family) => {
+ assert.ifError(err);
+ assert.ok(net.isIPv4(ip));
+ assert.strictEqual(family, 4);
- done();
- }));
+ done();
+ }));
checkWrap(req);
});
TEST(function test_lookup_ipv4_explicit_object(done) {
- const req = dns.lookup('www.google.com', {
+ const req = dns.lookup(addresses.INET4_HOST, {
family: 4
}, common.mustCall((err, ip, family) => {
assert.ifError(err);
@@ -113,7 +118,7 @@ TEST(function test_lookup_ipv4_explicit_object(done) {
});
TEST(function test_lookup_ipv4_hint_addrconfig(done) {
- const req = dns.lookup('www.google.com', {
+ const req = dns.lookup(addresses.INET4_HOST, {
hints: dns.ADDRCONFIG
}, common.mustCall((err, ip, family) => {
assert.ifError(err);
@@ -154,7 +159,7 @@ TEST(function test_lookup_localhost_ipv4(done) {
TEST(function test_lookup_all_ipv4(done) {
const req = dns.lookup(
- 'www.google.com',
+ addresses.INET4_HOST,
{ all: true, family: 4 },
common.mustCall((err, ips) => {
assert.ifError(err);
diff --git a/test/internet/test-dns-ipv6.js b/test/internet/test-dns-ipv6.js
index a91b108456c027..8b1a8936802729 100644
--- a/test/internet/test-dns-ipv6.js
+++ b/test/internet/test-dns-ipv6.js
@@ -1,5 +1,6 @@
'use strict';
const common = require('../common');
+const { addresses } = require('../common/internet');
if (!common.hasIPv6)
common.skip('this test, no IPv6 support');
@@ -38,53 +39,57 @@ function checkWrap(req) {
}
TEST(function test_resolve6(done) {
- const req = dns.resolve6('ipv6.google.com',
- common.mustCall((err, ips) => {
- assert.ifError(err);
+ const req = dns.resolve6(
+ addresses.INET6_HOST,
+ common.mustCall((err, ips) => {
+ assert.ifError(err);
- assert.ok(ips.length > 0);
+ assert.ok(ips.length > 0);
- for (let i = 0; i < ips.length; i++)
- assert.ok(isIPv6(ips[i]));
+ for (let i = 0; i < ips.length; i++)
+ assert.ok(isIPv6(ips[i]));
- done();
- }));
+ done();
+ }));
checkWrap(req);
});
TEST(function test_reverse_ipv6(done) {
- const req = dns.reverse('2001:4860:4860::8888',
- common.mustCall((err, domains) => {
- assert.ifError(err);
+ const req = dns.reverse(
+ addresses.INET6_IP,
+ common.mustCall((err, domains) => {
+ assert.ifError(err);
- assert.ok(domains.length > 0);
+ assert.ok(domains.length > 0);
- for (let i = 0; i < domains.length; i++)
- assert.ok(typeof domains[i] === 'string');
+ for (let i = 0; i < domains.length; i++)
+ assert.ok(typeof domains[i] === 'string');
- done();
- }));
+ done();
+ }));
checkWrap(req);
});
TEST(function test_lookup_ipv6_explicit(done) {
- const req = dns.lookup('ipv6.google.com', 6,
- common.mustCall((err, ip, family) => {
- assert.ifError(err);
- assert.ok(isIPv6(ip));
- assert.strictEqual(family, 6);
+ const req = dns.lookup(
+ addresses.INET6_HOST,
+ 6,
+ common.mustCall((err, ip, family) => {
+ assert.ifError(err);
+ assert.ok(isIPv6(ip));
+ assert.strictEqual(family, 6);
- done();
- }));
+ done();
+ }));
checkWrap(req);
});
/* This ends up just being too problematic to test
TEST(function test_lookup_ipv6_implicit(done) {
- var req = dns.lookup('ipv6.google.com', function(err, ip, family) {
+ var req = dns.lookup(addresses.INET6_HOST, function(err, ip, family) {
assert.ifError(err);
assert.ok(net.isIPv6(ip));
assert.strictEqual(family, 6);
@@ -97,7 +102,7 @@ TEST(function test_lookup_ipv6_implicit(done) {
*/
TEST(function test_lookup_ipv6_explicit_object(done) {
- const req = dns.lookup('ipv6.google.com', {
+ const req = dns.lookup(addresses.INET6_HOST, {
family: 6
}, common.mustCall((err, ip, family) => {
assert.ifError(err);
@@ -111,7 +116,7 @@ TEST(function test_lookup_ipv6_explicit_object(done) {
});
TEST(function test_lookup_ipv6_hint(done) {
- const req = dns.lookup('www.google.com', {
+ const req = dns.lookup(addresses.INET6_HOST, {
family: 6,
hints: dns.V4MAPPED
}, common.mustCall((err, ip, family) => {
@@ -120,7 +125,7 @@ TEST(function test_lookup_ipv6_hint(done) {
if (common.isFreeBSD) {
assert(err instanceof Error);
assert.strictEqual(err.code, 'EAI_BADFLAGS');
- assert.strictEqual(err.hostname, 'www.google.com');
+ assert.strictEqual(err.hostname, addresses.INET_HOST);
assert.ok(/getaddrinfo EAI_BADFLAGS/.test(err.message));
done();
return;
@@ -139,21 +144,22 @@ TEST(function test_lookup_ipv6_hint(done) {
});
TEST(function test_lookup_ip_ipv6(done) {
- const req = dns.lookup('::1',
- common.mustCall((err, ip, family) => {
- assert.ifError(err);
- assert.ok(isIPv6(ip));
- assert.strictEqual(family, 6);
+ const req = dns.lookup(
+ '::1',
+ common.mustCall((err, ip, family) => {
+ assert.ifError(err);
+ assert.ok(isIPv6(ip));
+ assert.strictEqual(family, 6);
- done();
- }));
+ done();
+ }));
checkWrap(req);
});
TEST(function test_lookup_all_ipv6(done) {
const req = dns.lookup(
- 'www.google.com',
+ addresses.INET6_HOST,
{ all: true, family: 6 },
common.mustCall((err, ips) => {
assert.ifError(err);
diff --git a/test/internet/test-dns-setserver-in-callback-of-resolve4.js b/test/internet/test-dns-setserver-in-callback-of-resolve4.js
index 222ac4dcc8ee31..58b3327efe9475 100644
--- a/test/internet/test-dns-setserver-in-callback-of-resolve4.js
+++ b/test/internet/test-dns-setserver-in-callback-of-resolve4.js
@@ -5,11 +5,14 @@
// a crash or not. If it doesn't crash, the test succeeded.
const common = require('../common');
+const { addresses } = require('../common/internet');
const dns = require('dns');
-dns.resolve4('google.com', common.mustCall(function(/* err, nameServers */) {
- dns.setServers([ '8.8.8.8' ]);
-}));
+dns.resolve4(
+ addresses.INET4_HOST,
+ common.mustCall(function(/* err, nameServers */) {
+ dns.setServers([ addresses.DNS4_SERVER ]);
+ }));
// Test https://github.com/nodejs/node/issues/14734
-dns.resolve4('google.com', common.mustCall());
+dns.resolve4(addresses.INET4_HOST, common.mustCall());
diff --git a/test/internet/test-dns.js b/test/internet/test-dns.js
index e2214433c51436..054de88dd45f90 100644
--- a/test/internet/test-dns.js
+++ b/test/internet/test-dns.js
@@ -21,6 +21,7 @@
'use strict';
const common = require('../common');
+const { addresses } = require('../common/internet');
const assert = require('assert');
const dns = require('dns');
const net = require('net');
@@ -74,7 +75,9 @@ TEST(function test_reverse_bogus(done) {
});
TEST(function test_resolve4_ttl(done) {
- const req = dns.resolve4('google.com', { ttl: true }, function(err, result) {
+ const req = dns.resolve4(addresses.INET4_HOST, {
+ ttl: true
+ }, function(err, result) {
assert.ifError(err);
assert.ok(result.length > 0);
@@ -95,7 +98,9 @@ TEST(function test_resolve4_ttl(done) {
});
TEST(function test_resolve6_ttl(done) {
- const req = dns.resolve6('google.com', { ttl: true }, function(err, result) {
+ const req = dns.resolve6(addresses.INET6_HOST, {
+ ttl: true
+ }, function(err, result) {
assert.ifError(err);
assert.ok(result.length > 0);
@@ -116,7 +121,7 @@ TEST(function test_resolve6_ttl(done) {
});
TEST(function test_resolveMx(done) {
- const req = dns.resolveMx('gmail.com', function(err, result) {
+ const req = dns.resolveMx(addresses.MX_HOST, function(err, result) {
assert.ifError(err);
assert.ok(result.length > 0);
@@ -138,7 +143,7 @@ TEST(function test_resolveMx(done) {
});
TEST(function test_resolveMx_failure(done) {
- const req = dns.resolveMx('something.invalid', function(err, result) {
+ const req = dns.resolveMx(addresses.INVALID_HOST, function(err, result) {
assert.ok(err instanceof Error);
assert.strictEqual(err.errno, 'ENOTFOUND');
@@ -151,7 +156,7 @@ TEST(function test_resolveMx_failure(done) {
});
TEST(function test_resolveNs(done) {
- const req = dns.resolveNs('rackspace.com', function(err, names) {
+ const req = dns.resolveNs(addresses.NS_HOST, function(err, names) {
assert.ifError(err);
assert.ok(names.length > 0);
@@ -168,7 +173,7 @@ TEST(function test_resolveNs(done) {
});
TEST(function test_resolveNs_failure(done) {
- const req = dns.resolveNs('something.invalid', function(err, result) {
+ const req = dns.resolveNs(addresses.INVALID_HOST, function(err, result) {
assert.ok(err instanceof Error);
assert.strictEqual(err.errno, 'ENOTFOUND');
@@ -181,7 +186,7 @@ TEST(function test_resolveNs_failure(done) {
});
TEST(function test_resolveSrv(done) {
- const req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) {
+ const req = dns.resolveSrv(addresses.SRV_HOST, function(err, result) {
assert.ifError(err);
assert.ok(result.length > 0);
@@ -205,7 +210,7 @@ TEST(function test_resolveSrv(done) {
});
TEST(function test_resolveSrv_failure(done) {
- const req = dns.resolveSrv('something.invalid', function(err, result) {
+ const req = dns.resolveSrv(addresses.INVALID_HOST, function(err, result) {
assert.ok(err instanceof Error);
assert.strictEqual(err.errno, 'ENOTFOUND');
@@ -218,7 +223,7 @@ TEST(function test_resolveSrv_failure(done) {
});
TEST(function test_resolvePtr(done) {
- const req = dns.resolvePtr('8.8.8.8.in-addr.arpa', function(err, result) {
+ const req = dns.resolvePtr(addresses.PTR_HOST, function(err, result) {
assert.ifError(err);
assert.ok(result.length > 0);
@@ -235,7 +240,7 @@ TEST(function test_resolvePtr(done) {
});
TEST(function test_resolvePtr_failure(done) {
- const req = dns.resolvePtr('something.invalid', function(err, result) {
+ const req = dns.resolvePtr(addresses.INVALID_HOST, function(err, result) {
assert.ok(err instanceof Error);
assert.strictEqual(err.errno, 'ENOTFOUND');
@@ -248,7 +253,7 @@ TEST(function test_resolvePtr_failure(done) {
});
TEST(function test_resolveNaptr(done) {
- const req = dns.resolveNaptr('sip2sip.info', function(err, result) {
+ const req = dns.resolveNaptr(addresses.NAPTR_HOST, function(err, result) {
assert.ifError(err);
assert.ok(result.length > 0);
@@ -272,7 +277,7 @@ TEST(function test_resolveNaptr(done) {
});
TEST(function test_resolveNaptr_failure(done) {
- const req = dns.resolveNaptr('something.invalid', function(err, result) {
+ const req = dns.resolveNaptr(addresses.INVALID_HOST, function(err, result) {
assert.ok(err instanceof Error);
assert.strictEqual(err.errno, 'ENOTFOUND');
@@ -285,7 +290,7 @@ TEST(function test_resolveNaptr_failure(done) {
});
TEST(function test_resolveSoa(done) {
- const req = dns.resolveSoa('nodejs.org', function(err, result) {
+ const req = dns.resolveSoa(addresses.SOA_HOST, function(err, result) {
assert.ifError(err);
assert.ok(result);
assert.strictEqual(typeof result, 'object');
@@ -318,7 +323,7 @@ TEST(function test_resolveSoa(done) {
});
TEST(function test_resolveSoa_failure(done) {
- const req = dns.resolveSoa('something.invalid', function(err, result) {
+ const req = dns.resolveSoa(addresses.INVALID_HOST, function(err, result) {
assert.ok(err instanceof Error);
assert.strictEqual(err.errno, 'ENOTFOUND');
@@ -331,7 +336,7 @@ TEST(function test_resolveSoa_failure(done) {
});
TEST(function test_resolveCname(done) {
- const req = dns.resolveCname('www.microsoft.com', function(err, names) {
+ const req = dns.resolveCname(addresses.CNAME_HOST, function(err, names) {
assert.ifError(err);
assert.ok(names.length > 0);
@@ -348,7 +353,7 @@ TEST(function test_resolveCname(done) {
});
TEST(function test_resolveCname_failure(done) {
- const req = dns.resolveCname('something.invalid', function(err, result) {
+ const req = dns.resolveCname(addresses.INVALID_HOST, function(err, result) {
assert.ok(err instanceof Error);
assert.strictEqual(err.errno, 'ENOTFOUND');
@@ -362,7 +367,7 @@ TEST(function test_resolveCname_failure(done) {
TEST(function test_resolveTxt(done) {
- const req = dns.resolveTxt('google.com', function(err, records) {
+ const req = dns.resolveTxt(addresses.TXT_HOST, function(err, records) {
assert.ifError(err);
assert.strictEqual(records.length, 1);
assert.ok(util.isArray(records[0]));
@@ -374,7 +379,7 @@ TEST(function test_resolveTxt(done) {
});
TEST(function test_resolveTxt_failure(done) {
- const req = dns.resolveTxt('something.invalid', function(err, result) {
+ const req = dns.resolveTxt(addresses.INVALID_HOST, function(err, result) {
assert.ok(err instanceof Error);
assert.strictEqual(err.errno, 'ENOTFOUND');
@@ -388,12 +393,12 @@ TEST(function test_resolveTxt_failure(done) {
TEST(function test_lookup_failure(done) {
- const req = dns.lookup('does.not.exist', 4, function(err, ip, family) {
+ const req = dns.lookup(addresses.INVALID_HOST, 4, (err, ip, family) => {
assert.ok(err instanceof Error);
assert.strictEqual(err.errno, dns.NOTFOUND);
assert.strictEqual(err.errno, 'ENOTFOUND');
assert.ok(!/ENOENT/.test(err.message));
- assert.ok(/does\.not\.exist/.test(err.message));
+ assert.ok(err.message.includes(addresses.INVALID_HOST));
done();
});
@@ -458,7 +463,9 @@ TEST(function test_lookup_null_all(done) {
TEST(function test_lookup_all_mixed(done) {
- const req = dns.lookup('www.google.com', { all: true }, function(err, ips) {
+ const req = dns.lookup(addresses.INET_HOST, {
+ all: true
+ }, function(err, ips) {
assert.ifError(err);
assert.ok(Array.isArray(ips));
assert.ok(ips.length > 0);
@@ -508,11 +515,11 @@ TEST(function test_reverse_failure(done) {
TEST(function test_lookup_failure(done) {
- const req = dns.lookup('nosuchhostimsure', function(err) {
+ const req = dns.lookup(addresses.INVALID_HOST, (err) => {
assert(err instanceof Error);
assert.strictEqual(err.code, 'ENOTFOUND'); // Silly error code...
- assert.strictEqual(err.hostname, 'nosuchhostimsure');
- assert.ok(/nosuchhostimsure/.test(err.message));
+ assert.strictEqual(err.hostname, addresses.INVALID_HOST);
+ assert.ok(err.message.includes(addresses.INVALID_HOST));
done();
});
@@ -522,7 +529,7 @@ TEST(function test_lookup_failure(done) {
TEST(function test_resolve_failure(done) {
- const req = dns.resolve4('nosuchhostimsure', function(err) {
+ const req = dns.resolve4(addresses.INVALID_HOST, (err) => {
assert(err instanceof Error);
switch (err.code) {
@@ -534,8 +541,8 @@ TEST(function test_resolve_failure(done) {
break;
}
- assert.strictEqual(err.hostname, 'nosuchhostimsure');
- assert.ok(/nosuchhostimsure/.test(err.message));
+ assert.strictEqual(err.hostname, addresses.INVALID_HOST);
+ assert.ok(err.message.includes(addresses.INVALID_HOST));
done();
});
@@ -546,15 +553,16 @@ TEST(function test_resolve_failure(done) {
let getaddrinfoCallbackCalled = false;
-console.log('looking up nodejs.org...');
+console.log(`looking up ${addresses.INET4_HOST}..`);
const cares = process.binding('cares_wrap');
const req = new cares.GetAddrInfoReqWrap();
-cares.getaddrinfo(req, 'nodejs.org', 4, /* hints */ 0, /* verbatim */ true);
+cares.getaddrinfo(req, addresses.INET4_HOST, 4,
+ /* hints */ 0, /* verbatim */ true);
req.oncomplete = function(err, domains) {
assert.strictEqual(err, 0);
- console.log('nodejs.org = ', domains);
+ console.log(`${addresses.INET4_HOST} = ${domains}`);
assert.ok(Array.isArray(domains));
assert.ok(domains.length >= 1);
assert.strictEqual(typeof domains[0], 'string');
@@ -569,10 +577,14 @@ process.on('exit', function() {
});
-assert.doesNotThrow(() => dns.lookup('nodejs.org', 6, common.mustCall()));
+assert.doesNotThrow(() =>
+ dns.lookup(addresses.INET6_HOST, 6, common.mustCall()));
-assert.doesNotThrow(() => dns.lookup('nodejs.org', {}, common.mustCall()));
+assert.doesNotThrow(() =>
+ dns.lookup(addresses.INET_HOST, {}, common.mustCall()));
-assert.doesNotThrow(() => dns.lookupService('0.0.0.0', '0', common.mustCall()));
+assert.doesNotThrow(() =>
+ dns.lookupService('0.0.0.0', '0', common.mustCall()));
-assert.doesNotThrow(() => dns.lookupService('0.0.0.0', 0, common.mustCall()));
+assert.doesNotThrow(() =>
+ dns.lookupService('0.0.0.0', 0, common.mustCall()));
diff --git a/test/internet/test-http-https-default-ports.js b/test/internet/test-http-https-default-ports.js
index 567b045dc6eacf..5f1b9eddb4f416 100644
--- a/test/internet/test-http-https-default-ports.js
+++ b/test/internet/test-http-https-default-ports.js
@@ -21,6 +21,7 @@
'use strict';
const common = require('../common');
+const { addresses } = require('../common/internet');
if (!common.hasCrypto)
common.skip('missing crypto');
@@ -29,10 +30,10 @@ const https = require('https');
const http = require('http');
-https.get('https://www.google.com/', common.mustCall(function(res) {
+https.get(`https://${addresses.INET_HOST}/`, common.mustCall(function(res) {
res.resume();
}));
-http.get('http://www.google.com/', common.mustCall(function(res) {
+http.get(`http://${addresses.INET_HOST}/`, common.mustCall(function(res) {
res.resume();
}));
From bff725853542318f01b2ebb33a3feadf5eb53c3b Mon Sep 17 00:00:00 2001
From: Joyee Cheung
Date: Sat, 3 Feb 2018 18:27:21 +0800
Subject: [PATCH 056/218] test: do not check TXT content in test-dns-any
google.com added another TXT record which broke this test.
This removes the check on the content of the TXT record
since that depends on an external state subject to change.
PR-URL: https://github.com/nodejs/node/pull/18547
Backport-PR-URL: https://github.com/nodejs/node/pull/19706
Reviewed-By: Khaidi Chu
Reviewed-By: Ruben Bridgewater
Reviewed-By: Colin Ihrig
Reviewed-By: Jon Moss
Reviewed-By: Anatoli Papirovski
Reviewed-By: James M Snell
---
test/internet/test-dns-any.js | 3 ---
1 file changed, 3 deletions(-)
diff --git a/test/internet/test-dns-any.js b/test/internet/test-dns-any.js
index dd80e48bf44e91..a83040801f38f4 100644
--- a/test/internet/test-dns-any.js
+++ b/test/internet/test-dns-any.js
@@ -59,9 +59,6 @@ const checkers = {
checkTXT(r) {
assert.ok(Array.isArray(r.entries));
assert.ok(r.entries.length > 0);
- r.entries.forEach((txt) => {
- assert(txt.startsWith('v=spf1'));
- });
assert.strictEqual(r.type, 'TXT');
},
checkSOA(r) {
From 34af49401b1779379f3e6acc33c89a4138bab2f4 Mon Sep 17 00:00:00 2001
From: Joyee Cheung
Date: Sat, 25 Nov 2017 23:58:05 +0900
Subject: [PATCH 057/218] test: add common.dns.errorLookupMock
PR-URL: https://github.com/nodejs/node/pull/17296
Backport-PR-URL: https://github.com/nodejs/node/pull/19706
Refs: https://github.com/nodejs/help/issues/687
Reviewed-By: Refael Ackermann
Reviewed-By: Rich Trott
Reviewed-By: James M Snell
---
test/common/README.md | 21 ++++++++++++++++++++-
test/common/dns.js | 26 +++++++++++++++++++++++---
2 files changed, 43 insertions(+), 4 deletions(-)
diff --git a/test/common/README.md b/test/common/README.md
index bb96f88be8308b..030b3e0366b24a 100644
--- a/test/common/README.md
+++ b/test/common/README.md
@@ -404,7 +404,26 @@ called before the callback is invoked.
## DNS Module
-The `DNS` module provides a naïve DNS parser/serializer.
+The `DNS` module provides utilities related to the `dns` built-in module.
+
+### errorLookupMock(code, syscall)
+
+* `code` [<String>] Defaults to `dns.mockedErrorCode`.
+* `syscall` [<String>] Defaults to `dns.mockedSysCall`.
+* return [<Function>]
+
+
+A mock for the `lookup` option of `net.connect()` that would result in an error
+with the `code` and the `syscall` specified. Returns a function that has the
+same signature as `dns.lookup()`.
+
+### mockedErrorCode
+
+The default `code` of errors generated by `errorLookupMock`.
+
+### mockedSysCall
+
+The default `syscall` of errors generated by `errorLookupMock`.
### readDomainFromPacket(buffer, offset)
diff --git a/test/common/dns.js b/test/common/dns.js
index 432d1b764dde29..69c67ac541cf98 100644
--- a/test/common/dns.js
+++ b/test/common/dns.js
@@ -1,8 +1,6 @@
/* eslint-disable required-modules */
'use strict';
-// Naïve DNS parser/serializer.
-
const assert = require('assert');
const os = require('os');
@@ -22,6 +20,8 @@ const classes = {
IN: 1
};
+// Naïve DNS parser/serializer.
+
function readDomainFromPacket(buffer, offset) {
assert.ok(offset < buffer.length);
const length = buffer[offset];
@@ -287,6 +287,26 @@ function writeDNSPacket(parsed) {
}));
}
+const mockedErrorCode = 'ENOTFOUND';
+const mockedSysCall = 'getaddrinfo';
+
+function errorLookupMock(code = mockedErrorCode, syscall = mockedSysCall) {
+ return function lookupWithError(host, dnsopts, cb) {
+ const err = new Error(`${syscall} ${code} ${host}`);
+ err.code = code;
+ err.errno = code;
+ err.syscall = syscall;
+ err.hostname = host;
+ cb(err);
+ };
+}
+
module.exports = {
- types, classes, writeDNSPacket, parseDNSPacket
+ types,
+ classes,
+ writeDNSPacket,
+ parseDNSPacket,
+ errorLookupMock,
+ mockedErrorCode,
+ mockedSysCall
};
From da162278dea69e1372562305618834b6722c6e84 Mon Sep 17 00:00:00 2001
From: Joyee Cheung
Date: Sat, 25 Nov 2017 23:58:24 +0900
Subject: [PATCH 058/218] test: mock the lookup function in parallel tests
These tests should not make any DNS calls. The lookup would fail
when the DNS requests are hijacked and time out instead of erroring
out.
PR-URL: https://github.com/nodejs/node/pull/17296
Backport-PR-URL: https://github.com/nodejs/node/pull/19706
Refs: https://github.com/nodejs/help/issues/687
Reviewed-By: Refael Ackermann
Reviewed-By: Rich Trott
Reviewed-By: James M Snell
---
...net-better-error-messages-port-hostname.js | 27 +++++++++++------
.../test-net-connect-immediate-finish.js | 29 ++++++++++++-------
2 files changed, 36 insertions(+), 20 deletions(-)
diff --git a/test/parallel/test-net-better-error-messages-port-hostname.js b/test/parallel/test-net-better-error-messages-port-hostname.js
index 818ea4bfff41f6..1a8aa770b44a22 100644
--- a/test/parallel/test-net-better-error-messages-port-hostname.js
+++ b/test/parallel/test-net-better-error-messages-port-hostname.js
@@ -1,21 +1,30 @@
'use strict';
+
+// This tests that the error thrown from net.createConnection
+// comes with host and port properties.
+// See https://github.com/nodejs/node-v0.x-archive/issues/7005
+
const common = require('../common');
const net = require('net');
const assert = require('assert');
+const { addresses } = require('../common/internet');
+const {
+ errorLookupMock,
+ mockedErrorCode
+} = require('../common/dns');
+
// Using port 0 as hostname used is already invalid.
-const c = net.createConnection(0, 'this.hostname.is.invalid');
+const c = net.createConnection({
+ port: 0,
+ host: addresses.INVALID_HOST,
+ lookup: common.mustCall(errorLookupMock())
+});
c.on('connect', common.mustNotCall());
c.on('error', common.mustCall(function(e) {
- // If Name Service Switch is available on the operating system then it
- // might be configured differently (/etc/nsswitch.conf).
- // If the system is configured with no dns the error code will be EAI_AGAIN,
- // but if there are more services after the dns entry, for example some
- // linux distributions ship a myhostname service by default which would
- // still produce the ENOTFOUND error.
- assert.ok(e.code === 'ENOTFOUND' || e.code === 'EAI_AGAIN');
+ assert.strictEqual(e.code, mockedErrorCode);
assert.strictEqual(e.port, 0);
- assert.strictEqual(e.hostname, 'this.hostname.is.invalid');
+ assert.strictEqual(e.hostname, addresses.INVALID_HOST);
}));
diff --git a/test/parallel/test-net-connect-immediate-finish.js b/test/parallel/test-net-connect-immediate-finish.js
index e2e5e1c6715b9a..9adf8c31128b00 100644
--- a/test/parallel/test-net-connect-immediate-finish.js
+++ b/test/parallel/test-net-connect-immediate-finish.js
@@ -20,28 +20,35 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
+
+// This tests that if the socket is still in the 'connecting' state
+// when the user calls socket.end() ('finish'), the socket would emit
+// 'connect' and defer the handling until the 'connect' event is handled.
+
const common = require('../common');
const assert = require('assert');
const net = require('net');
+const { addresses } = require('../common/internet');
+const {
+ errorLookupMock,
+ mockedErrorCode,
+ mockedSysCall
+} = require('../common/dns');
+
const client = net.connect({
- host: 'this.hostname.is.invalid',
- port: common.PORT
+ host: addresses.INVALID_HOST,
+ port: common.PORT,
+ lookup: common.mustCall(errorLookupMock())
});
client.once('error', common.mustCall((err) => {
assert(err);
assert.strictEqual(err.code, err.errno);
- // If Name Service Switch is available on the operating system then it
- // might be configured differently (/etc/nsswitch.conf).
- // If the system is configured with no dns the error code will be EAI_AGAIN,
- // but if there are more services after the dns entry, for example some
- // linux distributions ship a myhostname service by default which would
- // still produce the ENOTFOUND error.
- assert.ok(err.code === 'ENOTFOUND' || err.code === 'EAI_AGAIN');
+ assert.strictEqual(err.code, mockedErrorCode);
assert.strictEqual(err.host, err.hostname);
- assert.strictEqual(err.host, 'this.hostname.is.invalid');
- assert.strictEqual(err.syscall, 'getaddrinfo');
+ assert.strictEqual(err.host, addresses.INVALID_HOST);
+ assert.strictEqual(err.syscall, mockedSysCall);
}));
client.end();
From 53b702fdbabb0ac0625d3d287237927b55ee48c1 Mon Sep 17 00:00:00 2001
From: Rich Trott
Date: Wed, 22 Nov 2017 14:39:38 -0800
Subject: [PATCH 059/218] test: remove common.PORT from parallel tests
`common.PORT` should not be used in parallel tests because another test
may experience a collision with `common.PORT` when using port 0 to get
an open port. This has been observed to result in test failures in CI.
PR-URL: https://github.com/nodejs/node/pull/17410
Reviewed-By: Jon Moss
Reviewed-By: Colin Ihrig
Reviewed-By: Lance Ball
Reviewed-By: Luigi Pinca
Reviewed-By: Yuta Hiroto
Reviewed-By: Michael Dawson
---
test/async-hooks/test-graph.tcp.js | 2 +-
test/async-hooks/test-graph.tls-write.js | 4 ++--
test/async-hooks/test-tcpwrap.js | 2 +-
test/async-hooks/test-writewrap.js | 4 ++--
test/parallel/test-net-connect-immediate-finish.js | 4 ++--
test/{parallel => sequential}/test-tls-connect.js | 0
test/{parallel => sequential}/test-tls-lookup.js | 0
7 files changed, 8 insertions(+), 8 deletions(-)
rename test/{parallel => sequential}/test-tls-connect.js (100%)
rename test/{parallel => sequential}/test-tls-lookup.js (100%)
diff --git a/test/async-hooks/test-graph.tcp.js b/test/async-hooks/test-graph.tcp.js
index c2458ef1def769..c2253486ee651e 100644
--- a/test/async-hooks/test-graph.tcp.js
+++ b/test/async-hooks/test-graph.tcp.js
@@ -15,7 +15,7 @@ const server = net
.createServer(common.mustCall(onconnection))
.on('listening', common.mustCall(onlistening));
-server.listen(common.PORT);
+server.listen(0);
net.connect({ port: server.address().port, host: '::1' },
common.mustCall(onconnected));
diff --git a/test/async-hooks/test-graph.tls-write.js b/test/async-hooks/test-graph.tls-write.js
index 0c725d153d731b..26fe1ce41e955c 100644
--- a/test/async-hooks/test-graph.tls-write.js
+++ b/test/async-hooks/test-graph.tls-write.js
@@ -25,14 +25,14 @@ const server = tls
})
.on('listening', common.mustCall(onlistening))
.on('secureConnection', common.mustCall(onsecureConnection))
- .listen(common.PORT);
+ .listen(0);
function onlistening() {
//
// Creating client and connecting it to server
//
tls
- .connect(common.PORT, { rejectUnauthorized: false })
+ .connect(server.address().port, { rejectUnauthorized: false })
.on('secureConnect', common.mustCall(onsecureConnect));
}
diff --git a/test/async-hooks/test-tcpwrap.js b/test/async-hooks/test-tcpwrap.js
index e7d879caf70551..f3100aba0f0aaa 100644
--- a/test/async-hooks/test-tcpwrap.js
+++ b/test/async-hooks/test-tcpwrap.js
@@ -24,7 +24,7 @@ const server = net
// Calling server.listen creates a TCPWRAP synchronously
{
- server.listen(common.PORT);
+ server.listen(0);
const tcpsservers = hooks.activitiesOfTypes('TCPSERVERWRAP');
const tcpconnects = hooks.activitiesOfTypes('TCPCONNECTWRAP');
assert.strictEqual(tcpsservers.length, 1);
diff --git a/test/async-hooks/test-writewrap.js b/test/async-hooks/test-writewrap.js
index 65f7b6175fb63a..d349f635665ddd 100644
--- a/test/async-hooks/test-writewrap.js
+++ b/test/async-hooks/test-writewrap.js
@@ -23,7 +23,7 @@ const server = tls
})
.on('listening', common.mustCall(onlistening))
.on('secureConnection', common.mustCall(onsecureConnection))
- .listen(common.PORT);
+ .listen(0);
assert.strictEqual(hooks.activitiesOfTypes('WRITEWRAP').length, 0);
@@ -33,7 +33,7 @@ function onlistening() {
// Creating client and connecting it to server
//
tls
- .connect(common.PORT, { rejectUnauthorized: false })
+ .connect(server.address().port, { rejectUnauthorized: false })
.on('secureConnect', common.mustCall(onsecureConnect));
assert.strictEqual(hooks.activitiesOfTypes('WRITEWRAP').length, 0);
diff --git a/test/parallel/test-net-connect-immediate-finish.js b/test/parallel/test-net-connect-immediate-finish.js
index 9adf8c31128b00..27d988ab5af45f 100644
--- a/test/parallel/test-net-connect-immediate-finish.js
+++ b/test/parallel/test-net-connect-immediate-finish.js
@@ -38,9 +38,9 @@ const {
const client = net.connect({
host: addresses.INVALID_HOST,
- port: common.PORT,
+ port: 80, // port number doesn't matter because host name is invalid
lookup: common.mustCall(errorLookupMock())
-});
+}, common.mustNotCall());
client.once('error', common.mustCall((err) => {
assert(err);
diff --git a/test/parallel/test-tls-connect.js b/test/sequential/test-tls-connect.js
similarity index 100%
rename from test/parallel/test-tls-connect.js
rename to test/sequential/test-tls-connect.js
diff --git a/test/parallel/test-tls-lookup.js b/test/sequential/test-tls-lookup.js
similarity index 100%
rename from test/parallel/test-tls-lookup.js
rename to test/sequential/test-tls-lookup.js
From c97237bc104066ae1f3a8e5465dbc74a7fb4b297 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C3=ABl=20Zasso?=
Date: Thu, 5 Apr 2018 10:43:42 +0200
Subject: [PATCH 060/218] deps: cherry-pick a4bddba from upstream V8
Original commit message:
[Runtime] Use platform specific value for JSReceiver::HashMask
This allows us to remove the loop while calculating the hash value and
just use the HashMask as the mask for ComputeIntegerHash. This
previously overflowed on 32-bit systems failing the Smi::IsValid
check.
Bug: v8:6404
Change-Id: I84610a7592fa9d7ce4fa5cef7903bd50b8e8a4df
Reviewed-on: https://chromium-review.googlesource.com/702675
Reviewed-by: Adam Klein
Commit-Queue: Sathya Gunasekaran
Cr-Commit-Position: refs/heads/master@{#48319}
PR-URL: https://github.com/nodejs/node/pull/19824
Refs: https://github.com/v8/v8/commit/a4bddba0b0dac116d987eea28479dba14663cda0
Fixes: https://github.com/nodejs/node/issues/19769
Reviewed-By: Yang Guo
Reviewed-By: Gibson Fahnestock
---
deps/v8/include/v8-version.h | 2 +-
deps/v8/src/objects.cc | 9 ++-------
deps/v8/src/objects.h | 5 +++++
3 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h
index 25ce5d071e71c3..ce000d06c11659 100644
--- a/deps/v8/include/v8-version.h
+++ b/deps/v8/include/v8-version.h
@@ -11,7 +11,7 @@
#define V8_MAJOR_VERSION 6
#define V8_MINOR_VERSION 2
#define V8_BUILD_NUMBER 414
-#define V8_PATCH_LEVEL 50
+#define V8_PATCH_LEVEL 51
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
diff --git a/deps/v8/src/objects.cc b/deps/v8/src/objects.cc
index 28c1cd681ffd46..d9d00e058f4ee0 100644
--- a/deps/v8/src/objects.cc
+++ b/deps/v8/src/objects.cc
@@ -6368,13 +6368,8 @@ Smi* JSObject::GetOrCreateIdentityHash(Isolate* isolate) {
return Smi::cast(hash_obj);
}
- int masked_hash;
- // TODO(gsathya): Remove the loop and pass kHashMask directly to
- // GenerateIdentityHash.
- do {
- int hash = isolate->GenerateIdentityHash(Smi::kMaxValue);
- masked_hash = hash & JSReceiver::kHashMask;
- } while (masked_hash == PropertyArray::kNoHashSentinel);
+ int masked_hash = isolate->GenerateIdentityHash(JSReceiver::kHashMask);
+ DCHECK_NE(PropertyArray::kNoHashSentinel, masked_hash);
SetIdentityHash(masked_hash);
return Smi::FromInt(masked_hash);
diff --git a/deps/v8/src/objects.h b/deps/v8/src/objects.h
index f9987c2837c466..5456bfc47f6027 100644
--- a/deps/v8/src/objects.h
+++ b/deps/v8/src/objects.h
@@ -1954,8 +1954,13 @@ class PropertyArray : public HeapObject {
typedef BodyDescriptor BodyDescriptorWeak;
static const int kLengthMask = 0x3ff;
+#if V8_TARGET_ARCH_64_BIT
static const int kHashMask = 0x7ffffc00;
STATIC_ASSERT(kLengthMask + kHashMask == 0x7fffffff);
+#else
+ static const int kHashMask = 0x3ffffc00;
+ STATIC_ASSERT(kLengthMask + kHashMask == 0x3fffffff);
+#endif
static const int kMaxLength = kLengthMask;
STATIC_ASSERT(kMaxLength > kMaxNumberOfDescriptors);
From 09f5e252bfbeb2425a9692c25665dca97c1a61f4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C3=ABl=20Zasso?=
Date: Thu, 5 Apr 2018 10:43:58 +0200
Subject: [PATCH 061/218] deps: cherry-pick 7abdadc from upstream V8
Original commit message:
Sprinkle some DisallowHeapAllocation
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_chromium_rel_ng
Change-Id: I7d34ccddeea08f5935e360e8c36791365f27f89e
Reviewed-on: https://chromium-review.googlesource.com/647706
Reviewed-by: Michael Lippautz
Commit-Queue: Camillo Bruni
Cr-Commit-Position: refs/heads/master@{#47804}
PR-URL: https://github.com/nodejs/node/pull/19824
Refs: https://github.com/v8/v8/commit/7abdadca0e3e5a780647b8ade0c586c2e7583f9c
Fixes: https://github.com/nodejs/node/issues/19769
Reviewed-By: Yang Guo
Reviewed-By: Gibson Fahnestock
---
deps/v8/include/v8-version.h | 2 +-
deps/v8/src/api.cc | 1 +
deps/v8/src/objects.cc | 11 ++++++++++-
3 files changed, 12 insertions(+), 2 deletions(-)
diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h
index ce000d06c11659..f2a716cfdfe970 100644
--- a/deps/v8/include/v8-version.h
+++ b/deps/v8/include/v8-version.h
@@ -11,7 +11,7 @@
#define V8_MAJOR_VERSION 6
#define V8_MINOR_VERSION 2
#define V8_BUILD_NUMBER 414
-#define V8_PATCH_LEVEL 51
+#define V8_PATCH_LEVEL 52
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
diff --git a/deps/v8/src/api.cc b/deps/v8/src/api.cc
index 078796f5dbb4f2..76b095eb422712 100644
--- a/deps/v8/src/api.cc
+++ b/deps/v8/src/api.cc
@@ -5190,6 +5190,7 @@ Local v8::Object::CreationContext() {
int v8::Object::GetIdentityHash() {
+ i::DisallowHeapAllocation no_gc;
auto isolate = Utils::OpenHandle(this)->GetIsolate();
i::HandleScope scope(isolate);
auto self = Utils::OpenHandle(this);
diff --git a/deps/v8/src/objects.cc b/deps/v8/src/objects.cc
index d9d00e058f4ee0..b923864cb5f60e 100644
--- a/deps/v8/src/objects.cc
+++ b/deps/v8/src/objects.cc
@@ -2301,6 +2301,7 @@ namespace {
// objects. This avoids a double lookup in the cases where we know we will
// add the hash to the JSObject if it does not already exist.
Object* GetSimpleHash(Object* object) {
+ DisallowHeapAllocation no_gc;
// The object is either a Smi, a HeapNumber, a name, an odd-ball, a real JS
// object, or a Harmony proxy.
if (object->IsSmi()) {
@@ -2333,10 +2334,10 @@ Object* GetSimpleHash(Object* object) {
} // namespace
Object* Object::GetHash() {
+ DisallowHeapAllocation no_gc;
Object* hash = GetSimpleHash(this);
if (hash->IsSmi()) return hash;
- DisallowHeapAllocation no_gc;
DCHECK(IsJSReceiver());
JSReceiver* receiver = JSReceiver::cast(this);
Isolate* isolate = receiver->GetIsolate();
@@ -2345,10 +2346,12 @@ Object* Object::GetHash() {
// static
Smi* Object::GetOrCreateHash(Isolate* isolate, Object* key) {
+ DisallowHeapAllocation no_gc;
return key->GetOrCreateHash(isolate);
}
Smi* Object::GetOrCreateHash(Isolate* isolate) {
+ DisallowHeapAllocation no_gc;
Object* hash = GetSimpleHash(this);
if (hash->IsSmi()) return Smi::cast(hash);
@@ -6286,6 +6289,7 @@ Object* SetHashAndUpdateProperties(HeapObject* properties, int masked_hash) {
}
int GetIdentityHashHelper(Isolate* isolate, JSReceiver* object) {
+ DisallowHeapAllocation no_gc;
Object* properties = object->raw_properties_or_hash();
if (properties->IsSmi()) {
return Smi::ToInt(properties);
@@ -6312,6 +6316,7 @@ int GetIdentityHashHelper(Isolate* isolate, JSReceiver* object) {
} // namespace
void JSReceiver::SetIdentityHash(int masked_hash) {
+ DisallowHeapAllocation no_gc;
DCHECK_NE(PropertyArray::kNoHashSentinel, masked_hash);
DCHECK_EQ(masked_hash & JSReceiver::kHashMask, masked_hash);
@@ -6322,6 +6327,7 @@ void JSReceiver::SetIdentityHash(int masked_hash) {
}
void JSReceiver::SetProperties(HeapObject* properties) {
+ DisallowHeapAllocation no_gc;
Isolate* isolate = properties->GetIsolate();
int hash = GetIdentityHashHelper(isolate, this);
Object* new_properties = properties;
@@ -6337,6 +6343,7 @@ void JSReceiver::SetProperties(HeapObject* properties) {
template
Smi* GetOrCreateIdentityHashHelper(Isolate* isolate, ProxyType* proxy) {
+ DisallowHeapAllocation no_gc;
Object* maybe_hash = proxy->hash();
if (maybe_hash->IsSmi()) return Smi::cast(maybe_hash);
@@ -6346,6 +6353,7 @@ Smi* GetOrCreateIdentityHashHelper(Isolate* isolate, ProxyType* proxy) {
}
Object* JSObject::GetIdentityHash(Isolate* isolate) {
+ DisallowHeapAllocation no_gc;
if (IsJSGlobalProxy()) {
return JSGlobalProxy::cast(this)->hash();
}
@@ -6359,6 +6367,7 @@ Object* JSObject::GetIdentityHash(Isolate* isolate) {
}
Smi* JSObject::GetOrCreateIdentityHash(Isolate* isolate) {
+ DisallowHeapAllocation no_gc;
if (IsJSGlobalProxy()) {
return GetOrCreateIdentityHashHelper(isolate, JSGlobalProxy::cast(this));
}
From f12db24947c88b734e93abd0846d1fbc104a7190 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C3=ABl=20Zasso?=
Date: Thu, 5 Apr 2018 10:44:08 +0200
Subject: [PATCH 062/218] deps: cherry-pick a803fad from upstream V8
Original commit message:
Make sure the identity hash is uniform (at least in the lower bits).
In the current implementation of hash code for objects (identity hash),
we do not bother to shift the hash when we retrieve it from the
hash-length bitfield in a property array. (Even worse, we store shifted
value even if we do not have property array or inside dictionaries.)
That means that the hash-code for objects is always divisible by 1024.
Since our hash table uses a simple masking with (2^logsize - 1) to
obtain the bucket, we get terrible hash collisions - essentially, our
hash table degenerates to a linked list for fewer than 1024 elements.
This CL always shifts the hash code so that the value in the lowest
21 bits is uniformly distributed.
This results in big improvements on medium to large hash tables.
A program storing 1M elements into a WeakMap gets roughly
17x faster. A program retrieving 1M elements from a Map
improves even more dramatically (>100x).
const a = [];
for (let i = 0; i < 1e6; i++) a[i] = {};
const m = new Map();
console.time("Map.set");
for (let i = 0; i < 1e6; i++) {
m.set(a[i], i);
}
console.timeEnd("Map.set");
console.time("Map.get");
let s = 0;
for (let i = 0; i < 1e6; i++) {
s += m.get(a[i]);
}
console.timeEnd("Map.get");
const w = new WeakMap();
console.time("WeakMap.set");
for (let i = 0; i < 1e6; i++) {
w.set(a[i], i);
}
console.timeEnd("WeakMap.set");
Before the fix:
Map.set: 157.575000
Map.get: 28333.182000
WeakMap.set: 6923.826000
After the fix:
Map.set: 178.382000
Map.get: 185.930000
WeakMap.set: 409.529000
Note that Map does not suffer from the hash collision on insertion because
it uses chaining (insertion into linked list is fast regardless of size!), and
we cleverly avoid lookup in the hash table on update if the key does not have
identity hash yet. This is in contrast to the WeakMap, which uses
open-addressing, and deals with collisions on insertion.
Bug: v8:6916
Change-Id: Ic5497bd4501e3b767b3f4acb7efb4784cbb3a2e4
Reviewed-on: https://chromium-review.googlesource.com/713616
Reviewed-by: Benedikt Meurer
Commit-Queue: Benedikt Meurer
Cr-Commit-Position: refs/heads/master@{#48480}
PR-URL: https://github.com/nodejs/node/pull/19824
Refs: https://github.com/v8/v8/commit/a803fad068211ab6c445f485130dc52cbeadfd52
Fixes: https://github.com/nodejs/node/issues/19769
Reviewed-By: Yang Guo
Reviewed-By: Gibson Fahnestock
---
deps/v8/include/v8-version.h | 2 +-
deps/v8/src/code-stub-assembler.cc | 7 +++--
.../js-native-context-specialization.cc | 8 ++++--
deps/v8/src/ic/accessor-assembler.cc | 18 +++++++-----
deps/v8/src/objects-inl.h | 14 ++++------
deps/v8/src/objects.cc | 28 +++++++++----------
deps/v8/src/objects.h | 17 ++++-------
deps/v8/src/objects/dictionary.h | 10 ++++---
deps/v8/test/cctest/test-weakmaps.cc | 2 +-
9 files changed, 54 insertions(+), 52 deletions(-)
diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h
index f2a716cfdfe970..6d7eca8ab572ab 100644
--- a/deps/v8/include/v8-version.h
+++ b/deps/v8/include/v8-version.h
@@ -11,7 +11,7 @@
#define V8_MAJOR_VERSION 6
#define V8_MINOR_VERSION 2
#define V8_BUILD_NUMBER 414
-#define V8_PATCH_LEVEL 52
+#define V8_PATCH_LEVEL 53
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
diff --git a/deps/v8/src/code-stub-assembler.cc b/deps/v8/src/code-stub-assembler.cc
index 35261955db2576..915f507b12689c 100644
--- a/deps/v8/src/code-stub-assembler.cc
+++ b/deps/v8/src/code-stub-assembler.cc
@@ -1187,8 +1187,8 @@ TNode CodeStubAssembler::LoadHashForJSObject(
{
Node* length_and_hash_int32 = LoadAndUntagToWord32ObjectField(
properties_or_hash, PropertyArray::kLengthAndHashOffset);
- var_hash.Bind(Word32And(length_and_hash_int32,
- Int32Constant(PropertyArray::kHashMask)));
+ var_hash.Bind(
+ DecodeWord32(length_and_hash_int32));
Goto(&done);
}
@@ -2508,7 +2508,8 @@ void CodeStubAssembler::InitializePropertyArrayLength(Node* property_array,
CSA_ASSERT(
this,
IntPtrOrSmiLessThanOrEqual(
- length, IntPtrOrSmiConstant(PropertyArray::kMaxLength, mode), mode));
+ length, IntPtrOrSmiConstant(PropertyArray::LengthField::kMax, mode),
+ mode));
StoreObjectFieldNoWriteBarrier(
property_array, PropertyArray::kLengthAndHashOffset,
ParameterToTagged(length, mode), MachineRepresentation::kTaggedSigned);
diff --git a/deps/v8/src/compiler/js-native-context-specialization.cc b/deps/v8/src/compiler/js-native-context-specialization.cc
index dbe3fc9608216b..57d23589ff4f53 100644
--- a/deps/v8/src/compiler/js-native-context-specialization.cc
+++ b/deps/v8/src/compiler/js-native-context-specialization.cc
@@ -2255,14 +2255,18 @@ Node* JSNativeContextSpecialization::BuildExtendPropertiesBackingStore(
jsgraph()->SmiConstant(PropertyArray::kNoHashSentinel));
hash = graph()->NewNode(common()->TypeGuard(Type::SignedSmall()), hash,
control);
+ hash =
+ graph()->NewNode(simplified()->NumberShiftLeft(), hash,
+ jsgraph()->Constant(PropertyArray::HashField::kShift));
} else {
hash = effect = graph()->NewNode(
simplified()->LoadField(AccessBuilder::ForPropertyArrayLengthAndHash()),
properties, effect, control);
effect = graph()->NewNode(
common()->BeginRegion(RegionObservability::kNotObservable), effect);
- hash = graph()->NewNode(simplified()->NumberBitwiseAnd(), hash,
- jsgraph()->Constant(JSReceiver::kHashMask));
+ hash =
+ graph()->NewNode(simplified()->NumberBitwiseAnd(), hash,
+ jsgraph()->Constant(PropertyArray::HashField::kMask));
}
Node* new_length_and_hash = graph()->NewNode(
diff --git a/deps/v8/src/ic/accessor-assembler.cc b/deps/v8/src/ic/accessor-assembler.cc
index 1dee1303366e74..8985bad15e9f64 100644
--- a/deps/v8/src/ic/accessor-assembler.cc
+++ b/deps/v8/src/ic/accessor-assembler.cc
@@ -1091,7 +1091,7 @@ void AccessorAssembler::ExtendPropertiesBackingStore(Node* object,
// TODO(gsathya): Clean up the type conversions by creating smarter
// helpers that do the correct op based on the mode.
VARIABLE(var_properties, MachineRepresentation::kTaggedPointer);
- VARIABLE(var_hash, MachineRepresentation::kWord32);
+ VARIABLE(var_encoded_hash, MachineRepresentation::kWord32);
VARIABLE(var_length, ParameterRepresentation(mode));
Node* properties = LoadObjectField(object, JSObject::kPropertiesOrHashOffset);
@@ -1102,7 +1102,10 @@ void AccessorAssembler::ExtendPropertiesBackingStore(Node* object,
BIND(&if_smi_hash);
{
- var_hash.Bind(SmiToWord32(properties));
+ Node* hash = SmiToWord32(properties);
+ Node* encoded_hash =
+ Word32Shl(hash, Int32Constant(PropertyArray::HashField::kShift));
+ var_encoded_hash.Bind(encoded_hash);
var_length.Bind(IntPtrOrSmiConstant(0, mode));
var_properties.Bind(EmptyFixedArrayConstant());
Goto(&extend_store);
@@ -1112,10 +1115,11 @@ void AccessorAssembler::ExtendPropertiesBackingStore(Node* object,
{
Node* length_and_hash_int32 = LoadAndUntagToWord32ObjectField(
var_properties.value(), PropertyArray::kLengthAndHashOffset);
- var_hash.Bind(Word32And(length_and_hash_int32,
- Int32Constant(PropertyArray::kHashMask)));
- Node* length_intptr = ChangeInt32ToIntPtr(Word32And(
- length_and_hash_int32, Int32Constant(PropertyArray::kLengthMask)));
+ var_encoded_hash.Bind(Word32And(
+ length_and_hash_int32, Int32Constant(PropertyArray::HashField::kMask)));
+ Node* length_intptr = ChangeInt32ToIntPtr(
+ Word32And(length_and_hash_int32,
+ Int32Constant(PropertyArray::LengthField::kMask)));
Node* length = WordToParameter(length_intptr, mode);
var_length.Bind(length);
Goto(&extend_store);
@@ -1161,7 +1165,7 @@ void AccessorAssembler::ExtendPropertiesBackingStore(Node* object,
Node* new_capacity_int32 =
TruncateWordToWord32(ParameterToWord(new_capacity, mode));
Node* new_length_and_hash_int32 =
- Word32Or(var_hash.value(), new_capacity_int32);
+ Word32Or(var_encoded_hash.value(), new_capacity_int32);
StoreObjectField(new_properties, PropertyArray::kLengthAndHashOffset,
SmiFromWord32(new_length_and_hash_int32));
StoreObjectField(object, JSObject::kPropertiesOrHashOffset, new_properties);
diff --git a/deps/v8/src/objects-inl.h b/deps/v8/src/objects-inl.h
index 82b7eb05a6e7b4..91fd08a2dd58c8 100644
--- a/deps/v8/src/objects-inl.h
+++ b/deps/v8/src/objects-inl.h
@@ -2679,33 +2679,31 @@ SYNCHRONIZED_SMI_ACCESSORS(FixedArrayBase, length, kLengthOffset)
int PropertyArray::length() const {
Object* value_obj = READ_FIELD(this, kLengthAndHashOffset);
int value = Smi::ToInt(value_obj);
- return value & kLengthMask;
+ return LengthField::decode(value);
}
void PropertyArray::initialize_length(int len) {
SLOW_DCHECK(len >= 0);
- SLOW_DCHECK(len < kMaxLength);
+ SLOW_DCHECK(len < LengthField::kMax);
WRITE_FIELD(this, kLengthAndHashOffset, Smi::FromInt(len));
}
int PropertyArray::synchronized_length() const {
Object* value_obj = ACQUIRE_READ_FIELD(this, kLengthAndHashOffset);
int value = Smi::ToInt(value_obj);
- return value & kLengthMask;
+ return LengthField::decode(value);
}
int PropertyArray::Hash() const {
Object* value_obj = READ_FIELD(this, kLengthAndHashOffset);
int value = Smi::ToInt(value_obj);
- int hash = value & kHashMask;
- return hash;
+ return HashField::decode(value);
}
-void PropertyArray::SetHash(int masked_hash) {
- DCHECK_EQ(masked_hash & JSReceiver::kHashMask, masked_hash);
+void PropertyArray::SetHash(int hash) {
Object* value_obj = READ_FIELD(this, kLengthAndHashOffset);
int value = Smi::ToInt(value_obj);
- value = (value & kLengthMask) | masked_hash;
+ value = HashField::update(value, hash);
WRITE_FIELD(this, kLengthAndHashOffset, Smi::FromInt(value));
}
diff --git a/deps/v8/src/objects.cc b/deps/v8/src/objects.cc
index b923864cb5f60e..b2b23c1f68f216 100644
--- a/deps/v8/src/objects.cc
+++ b/deps/v8/src/objects.cc
@@ -6269,22 +6269,22 @@ Handle JSObject::NormalizeElements(
namespace {
-Object* SetHashAndUpdateProperties(HeapObject* properties, int masked_hash) {
- DCHECK_NE(PropertyArray::kNoHashSentinel, masked_hash);
- DCHECK_EQ(masked_hash & JSReceiver::kHashMask, masked_hash);
+Object* SetHashAndUpdateProperties(HeapObject* properties, int hash) {
+ DCHECK_NE(PropertyArray::kNoHashSentinel, hash);
+ DCHECK(PropertyArray::HashField::is_valid(hash));
if (properties == properties->GetHeap()->empty_fixed_array() ||
properties == properties->GetHeap()->empty_property_dictionary()) {
- return Smi::FromInt(masked_hash);
+ return Smi::FromInt(hash);
}
if (properties->IsPropertyArray()) {
- PropertyArray::cast(properties)->SetHash(masked_hash);
+ PropertyArray::cast(properties)->SetHash(hash);
return properties;
}
DCHECK(properties->IsDictionary());
- NameDictionary::cast(properties)->SetHash(masked_hash);
+ NameDictionary::cast(properties)->SetHash(hash);
return properties;
}
@@ -6315,14 +6315,14 @@ int GetIdentityHashHelper(Isolate* isolate, JSReceiver* object) {
}
} // namespace
-void JSReceiver::SetIdentityHash(int masked_hash) {
+void JSReceiver::SetIdentityHash(int hash) {
DisallowHeapAllocation no_gc;
- DCHECK_NE(PropertyArray::kNoHashSentinel, masked_hash);
- DCHECK_EQ(masked_hash & JSReceiver::kHashMask, masked_hash);
+ DCHECK_NE(PropertyArray::kNoHashSentinel, hash);
+ DCHECK(PropertyArray::HashField::is_valid(hash));
HeapObject* existing_properties = HeapObject::cast(raw_properties_or_hash());
Object* new_properties =
- SetHashAndUpdateProperties(existing_properties, masked_hash);
+ SetHashAndUpdateProperties(existing_properties, hash);
set_raw_properties_or_hash(new_properties);
}
@@ -6377,11 +6377,11 @@ Smi* JSObject::GetOrCreateIdentityHash(Isolate* isolate) {
return Smi::cast(hash_obj);
}
- int masked_hash = isolate->GenerateIdentityHash(JSReceiver::kHashMask);
- DCHECK_NE(PropertyArray::kNoHashSentinel, masked_hash);
+ int hash = isolate->GenerateIdentityHash(PropertyArray::HashField::kMax);
+ DCHECK_NE(PropertyArray::kNoHashSentinel, hash);
- SetIdentityHash(masked_hash);
- return Smi::FromInt(masked_hash);
+ SetIdentityHash(hash);
+ return Smi::FromInt(hash);
}
Object* JSProxy::GetIdentityHash() { return hash(); }
diff --git a/deps/v8/src/objects.h b/deps/v8/src/objects.h
index 5456bfc47f6027..00a8d0da02220e 100644
--- a/deps/v8/src/objects.h
+++ b/deps/v8/src/objects.h
@@ -1953,17 +1953,10 @@ class PropertyArray : public HeapObject {
// No weak fields.
typedef BodyDescriptor BodyDescriptorWeak;
- static const int kLengthMask = 0x3ff;
-#if V8_TARGET_ARCH_64_BIT
- static const int kHashMask = 0x7ffffc00;
- STATIC_ASSERT(kLengthMask + kHashMask == 0x7fffffff);
-#else
- static const int kHashMask = 0x3ffffc00;
- STATIC_ASSERT(kLengthMask + kHashMask == 0x3fffffff);
-#endif
-
- static const int kMaxLength = kLengthMask;
- STATIC_ASSERT(kMaxLength > kMaxNumberOfDescriptors);
+ static const int kLengthFieldSize = 10;
+ class LengthField : public BitField {};
+ class HashField : public BitField {};
static const int kNoHashSentinel = 0;
@@ -2190,7 +2183,7 @@ class JSReceiver: public HeapObject {
MUST_USE_RESULT static MaybeHandle GetOwnEntries(
Handle object, PropertyFilter filter);
- static const int kHashMask = PropertyArray::kHashMask;
+ static const int kHashMask = PropertyArray::HashField::kMask;
// Layout description.
static const int kPropertiesOrHashOffset = HeapObject::kHeaderSize;
diff --git a/deps/v8/src/objects/dictionary.h b/deps/v8/src/objects/dictionary.h
index a989c8fc8a2e53..09fdb9eb0764a2 100644
--- a/deps/v8/src/objects/dictionary.h
+++ b/deps/v8/src/objects/dictionary.h
@@ -138,14 +138,16 @@ class BaseNameDictionary : public Dictionary {
return Smi::ToInt(this->get(kNextEnumerationIndexIndex));
}
- void SetHash(int masked_hash) {
- DCHECK_EQ(masked_hash & JSReceiver::kHashMask, masked_hash);
- this->set(kObjectHashIndex, Smi::FromInt(masked_hash));
+ void SetHash(int hash) {
+ DCHECK(PropertyArray::HashField::is_valid(hash));
+ this->set(kObjectHashIndex, Smi::FromInt(hash));
}
int Hash() const {
Object* hash_obj = this->get(kObjectHashIndex);
- return Smi::ToInt(hash_obj);
+ int hash = Smi::ToInt(hash_obj);
+ DCHECK(PropertyArray::HashField::is_valid(hash));
+ return hash;
}
// Creates a new dictionary.
diff --git a/deps/v8/test/cctest/test-weakmaps.cc b/deps/v8/test/cctest/test-weakmaps.cc
index 13a0c538d9b82f..f645234144c092 100644
--- a/deps/v8/test/cctest/test-weakmaps.cc
+++ b/deps/v8/test/cctest/test-weakmaps.cc
@@ -191,7 +191,7 @@ TEST(Regress2060a) {
Handle object = factory->NewJSObject(function, TENURED);
CHECK(!heap->InNewSpace(*object));
CHECK(!first_page->Contains(object->address()));
- int32_t hash = object->GetOrCreateHash(isolate)->value();
+ int32_t hash = key->GetOrCreateHash(isolate)->value();
JSWeakCollection::Set(weakmap, key, object, hash);
}
}
From 2019b023a7184f07826e2a63f12859d0684ea3ec Mon Sep 17 00:00:00 2001
From: Anna Henningsen
Date: Sun, 29 Oct 2017 01:36:18 +0200
Subject: [PATCH 063/218] lib: refactor ES module loader for readability
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
PR-URL: https://github.com/nodejs/node/pull/16579
Backport-PR-URL: https://github.com/nodejs/node/pull/18085
Reviewed-By: Michaël Zasso
Reviewed-By: James M Snell
Reviewed-By: Colin Ihrig
---
doc/api/errors.md | 22 ++++++
lib/internal/errors.js | 3 +
lib/internal/loader/Loader.js | 45 ++++++++++--
lib/internal/loader/ModuleJob.js | 111 +++++++++++++++---------------
lib/internal/loader/ModuleWrap.js | 52 ++++++++------
5 files changed, 151 insertions(+), 82 deletions(-)
diff --git a/doc/api/errors.md b/doc/api/errors.md
index f2de6717a57ee2..e895accada72f2 100755
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -981,6 +981,28 @@ strict compliance with the API specification (which in some cases may accept
`func(undefined)` and `func()` are treated identically, and the
[`ERR_INVALID_ARG_TYPE`][] error code may be used instead.
+
+### ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK
+
+> Stability: 1 - Experimental
+
+Used when an [ES6 module][] loader hook specifies `format: 'dynamic` but does
+not provide a `dynamicInstantiate` hook.
+
+
+### ERR_MISSING_MODULE
+
+> Stability: 1 - Experimental
+
+Used when an [ES6 module][] cannot be resolved.
+
+
+### ERR_MODULE_RESOLUTION_LEGACY
+
+> Stability: 1 - Experimental
+
+Used when a failure occurs resolving imports in an [ES6 module][].
+
### ERR_NAPI_CONS_FUNCTION
diff --git a/lib/internal/errors.js b/lib/internal/errors.js
index 9a1bc0ee38d519..ea5526c795343c 100644
--- a/lib/internal/errors.js
+++ b/lib/internal/errors.js
@@ -257,6 +257,9 @@ E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected');
E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe');
E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks');
E('ERR_MISSING_ARGS', missingArgs);
+E('ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK',
+ 'The ES Module loader may not return a format of \'dynamic\' when no ' +
+ 'dynamicInstantiate function was provided');
E('ERR_MISSING_MODULE', 'Cannot find module %s');
E('ERR_MODULE_RESOLUTION_LEGACY', '%s not found by import in %s.' +
' Legacy behavior in require() would have found it at %s');
diff --git a/lib/internal/loader/Loader.js b/lib/internal/loader/Loader.js
index f2c7fa0cfffc47..49c8699771e819 100644
--- a/lib/internal/loader/Loader.js
+++ b/lib/internal/loader/Loader.js
@@ -10,7 +10,8 @@ const ModuleRequest = require('internal/loader/ModuleRequest');
const errors = require('internal/errors');
const debug = require('util').debuglog('esm');
-function getBase() {
+// Returns a file URL for the current working directory.
+function getURLStringForCwd() {
try {
return getURLFromFilePath(`${process.cwd()}/`).href;
} catch (e) {
@@ -23,22 +24,44 @@ function getBase() {
}
}
+/* A Loader instance is used as the main entry point for loading ES modules.
+ * Currently, this is a singleton -- there is only one used for loading
+ * the main module and everything in its dependency graph. */
class Loader {
- constructor(base = getBase()) {
- this.moduleMap = new ModuleMap();
+ constructor(base = getURLStringForCwd()) {
if (typeof base !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'base', 'string');
}
+
+ this.moduleMap = new ModuleMap();
this.base = base;
- this.resolver = ModuleRequest.resolve.bind(null);
+ // The resolver has the signature
+ // (specifier : string, parentURL : string, defaultResolve)
+ // -> Promise<{ url : string,
+ // format: anything in Loader.validFormats }>
+ // where defaultResolve is ModuleRequest.resolve (having the same
+ // signature itself).
+ // If `.format` on the returned value is 'dynamic', .dynamicInstantiate
+ // will be used as described below.
+ this.resolver = ModuleRequest.resolve;
+ // This hook is only called when resolve(...).format is 'dynamic' and has
+ // the signature
+ // (url : string) -> Promise<{ exports: { ... }, execute: function }>
+ // Where `exports` is an object whose property names define the exported
+ // names of the generated module. `execute` is a function that receives
+ // an object with the same keys as `exports`, whose values are get/set
+ // functions for the actual exported values.
this.dynamicInstantiate = undefined;
}
hook({ resolve = ModuleRequest.resolve, dynamicInstantiate }) {
+ // Use .bind() to avoid giving access to the Loader instance when it is
+ // called as this.resolver(...);
this.resolver = resolve.bind(null);
this.dynamicInstantiate = dynamicInstantiate;
}
+ // Typechecking wrapper around .resolver().
async resolve(specifier, parentURL = this.base) {
if (typeof parentURL !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
@@ -48,10 +71,11 @@ class Loader {
const { url, format } = await this.resolver(specifier, parentURL,
ModuleRequest.resolve);
- if (typeof format !== 'string') {
+ if (!Loader.validFormats.includes(format)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'format',
- ['esm', 'cjs', 'builtin', 'addon', 'json']);
+ Loader.validFormats);
}
+
if (typeof url !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'url', 'string');
}
@@ -72,14 +96,20 @@ class Loader {
return { url, format };
}
+ // May create a new ModuleJob instance if one did not already exist.
async getModuleJob(specifier, parentURL = this.base) {
const { url, format } = await this.resolve(specifier, parentURL);
let job = this.moduleMap.get(url);
if (job === undefined) {
let loaderInstance;
if (format === 'dynamic') {
+ const { dynamicInstantiate } = this;
+ if (typeof dynamicInstantiate !== 'function') {
+ throw new errors.Error('ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK');
+ }
+
loaderInstance = async (url) => {
- const { exports, execute } = await this.dynamicInstantiate(url);
+ const { exports, execute } = await dynamicInstantiate(url);
return createDynamicModule(exports, url, (reflect) => {
debug(`Loading custom loader ${url}`);
execute(reflect.exports);
@@ -100,5 +130,6 @@ class Loader {
return module.namespace();
}
}
+Loader.validFormats = ['esm', 'cjs', 'builtin', 'addon', 'json', 'dynamic'];
Object.setPrototypeOf(Loader.prototype, null);
module.exports = Loader;
diff --git a/lib/internal/loader/ModuleJob.js b/lib/internal/loader/ModuleJob.js
index 04d6111b87f1f6..77c89f6230e5de 100644
--- a/lib/internal/loader/ModuleJob.js
+++ b/lib/internal/loader/ModuleJob.js
@@ -1,27 +1,36 @@
'use strict';
+const { ModuleWrap } =
+ require('internal/process').internalBinding('module_wrap');
const { SafeSet, SafePromise } = require('internal/safe_globals');
+const assert = require('assert');
const resolvedPromise = SafePromise.resolve();
+const enableDebug = (process.env.NODE_DEBUG || '').match(/\besm\b/) ||
+ process.features.debug;
+
+/* A ModuleJob tracks the loading of a single Module, and the ModuleJobs of
+ * its dependencies, over time. */
class ModuleJob {
- /**
- * @param {module: ModuleWrap?, compiled: Promise} moduleProvider
- */
+ // `loader` is the Loader instance used for loading dependencies.
+ // `moduleProvider` is a function
constructor(loader, url, moduleProvider) {
this.loader = loader;
this.error = null;
this.hadError = false;
- // linked == promise for dependency jobs, with module populated,
- // module wrapper linked
- this.moduleProvider = moduleProvider;
- this.modulePromise = this.moduleProvider(url);
+ // This is a Promise<{ module, reflect }>, whose fields will be copied
+ // onto `this` by `link()` below once it has been resolved.
+ this.modulePromise = moduleProvider(url);
this.module = undefined;
this.reflect = undefined;
- const linked = async () => {
+
+ // Wait for the ModuleWrap instance being linked with all dependencies.
+ const link = async () => {
const dependencyJobs = [];
({ module: this.module,
reflect: this.reflect } = await this.modulePromise);
+ assert(this.module instanceof ModuleWrap);
this.module.link(async (dependencySpecifier) => {
const dependencyJobPromise =
this.loader.getModuleJob(dependencySpecifier, url);
@@ -29,63 +38,57 @@ class ModuleJob {
const dependencyJob = await dependencyJobPromise;
return (await dependencyJob.modulePromise).module;
});
+ if (enableDebug) {
+ // Make sure all dependencies are entered into the list synchronously.
+ Object.freeze(dependencyJobs);
+ }
return SafePromise.all(dependencyJobs);
};
- this.linked = linked();
+ // Promise for the list of all dependencyJobs.
+ this.linked = link();
// instantiated == deep dependency jobs wrappers instantiated,
// module wrapper instantiated
this.instantiated = undefined;
}
- instantiate() {
+ async instantiate() {
if (this.instantiated) {
return this.instantiated;
}
- return this.instantiated = new Promise(async (resolve, reject) => {
- const jobsInGraph = new SafeSet();
- let jobsReadyToInstantiate = 0;
- // (this must be sync for counter to work)
- const queueJob = (moduleJob) => {
- if (jobsInGraph.has(moduleJob)) {
- return;
- }
- jobsInGraph.add(moduleJob);
- moduleJob.linked.then((dependencyJobs) => {
- for (const dependencyJob of dependencyJobs) {
- queueJob(dependencyJob);
- }
- checkComplete();
- }, (e) => {
- if (!this.hadError) {
- this.error = e;
- this.hadError = true;
- }
- checkComplete();
- });
- };
- const checkComplete = () => {
- if (++jobsReadyToInstantiate === jobsInGraph.size) {
- // I believe we only throw once the whole tree is finished loading?
- // or should the error bail early, leaving entire tree to still load?
- if (this.hadError) {
- reject(this.error);
- } else {
- try {
- this.module.instantiate();
- for (const dependencyJob of jobsInGraph) {
- dependencyJob.instantiated = resolvedPromise;
- }
- resolve(this.module);
- } catch (e) {
- e.stack;
- reject(e);
- }
- }
- }
- };
- queueJob(this);
- });
+ return this.instantiated = this._instantiate();
+ }
+
+ // This method instantiates the module associated with this job and its
+ // entire dependency graph, i.e. creates all the module namespaces and the
+ // exported/imported variables.
+ async _instantiate() {
+ const jobsInGraph = new SafeSet();
+
+ const addJobsToDependencyGraph = async (moduleJob) => {
+ if (jobsInGraph.has(moduleJob)) {
+ return;
+ }
+ jobsInGraph.add(moduleJob);
+ const dependencyJobs = await moduleJob.linked;
+ return Promise.all(dependencyJobs.map(addJobsToDependencyGraph));
+ };
+ try {
+ await addJobsToDependencyGraph(this);
+ } catch (e) {
+ if (!this.hadError) {
+ this.error = e;
+ this.hadError = true;
+ }
+ throw e;
+ }
+ this.module.instantiate();
+ for (const dependencyJob of jobsInGraph) {
+ // Calling `this.module.instantiate()` instantiates not only the
+ // ModuleWrap in this module, but all modules in the graph.
+ dependencyJob.instantiated = resolvedPromise;
+ }
+ return this.module;
}
async run() {
diff --git a/lib/internal/loader/ModuleWrap.js b/lib/internal/loader/ModuleWrap.js
index c97b4888ea22ce..0ee05ca81ffbb9 100644
--- a/lib/internal/loader/ModuleWrap.js
+++ b/lib/internal/loader/ModuleWrap.js
@@ -11,39 +11,49 @@ const createDynamicModule = (exports, url = '', evaluate) => {
`creating ESM facade for ${url} with exports: ${ArrayJoin(exports, ', ')}`
);
const names = ArrayMap(exports, (name) => `${name}`);
- // sanitized ESM for reflection purposes
- const src = `export let executor;
- ${ArrayJoin(ArrayMap(names, (name) => `export let $${name}`), ';\n')}
- ;(() => [
- fn => executor = fn,
- { exports: { ${
- ArrayJoin(ArrayMap(names, (name) => `${name}: {
- get: () => $${name},
- set: v => $${name} = v
- }`), ',\n')
-} } }
- ]);
- `;
+ // Create two modules: One whose exports are get- and set-able ('reflective'),
+ // and one which re-exports all of these but additionally may
+ // run an executor function once everything is set up.
+ const src = `
+ export let executor;
+ ${ArrayJoin(ArrayMap(names, (name) => `export let $${name};`), '\n')}
+ /* This function is implicitly returned as the module's completion value */
+ (() => ({
+ setExecutor: fn => executor = fn,
+ reflect: {
+ exports: { ${
+ ArrayJoin(ArrayMap(names, (name) => `
+ ${name}: {
+ get: () => $${name},
+ set: v => $${name} = v
+ }`), ', \n')}
+ }
+ }
+ }));`;
const reflectiveModule = new ModuleWrap(src, `cjs-facade:${url}`);
reflectiveModule.instantiate();
- const [setExecutor, reflect] = reflectiveModule.evaluate()();
+ const { setExecutor, reflect } = reflectiveModule.evaluate()();
// public exposed ESM
- const reexports = `import { executor,
+ const reexports = `
+ import {
+ executor,
${ArrayMap(names, (name) => `$${name}`)}
} from "";
export {
${ArrayJoin(ArrayMap(names, (name) => `$${name} as ${name}`), ', ')}
}
- // add await to this later if top level await comes along
- typeof executor === "function" ? executor() : void 0;`;
+ if (typeof executor === "function") {
+ // add await to this later if top level await comes along
+ executor()
+ }`;
if (typeof evaluate === 'function') {
setExecutor(() => evaluate(reflect));
}
- const runner = new ModuleWrap(reexports, `${url}`);
- runner.link(async () => reflectiveModule);
- runner.instantiate();
+ const module = new ModuleWrap(reexports, `${url}`);
+ module.link(async () => reflectiveModule);
+ module.instantiate();
return {
- module: runner,
+ module,
reflect
};
};
From 9ac91b14de5df91b180ae98b1e682d9b2654bf9a Mon Sep 17 00:00:00 2001
From: Ruben Bridgewater
Date: Wed, 7 Mar 2018 19:15:25 +0100
Subject: [PATCH 064/218] src: fix util abort
This makes sure util.isRegExp and util.isDate will not abort in case
more than one argument is passed to the function.
PR-URL: https://github.com/nodejs/node/pull/19224
Reviewed-By: Gibson Fahnestock
---
src/node_util.cc | 2 --
test/parallel/test-util.js | 5 +++--
2 files changed, 3 insertions(+), 4 deletions(-)
diff --git a/src/node_util.cc b/src/node_util.cc
index a40401b71926b3..1e51fbfff4b6ae 100644
--- a/src/node_util.cc
+++ b/src/node_util.cc
@@ -36,7 +36,6 @@ using v8::Value;
#define V(_, ucname) \
static void ucname(const FunctionCallbackInfo& args) { \
- CHECK_EQ(1, args.Length()); \
args.GetReturnValue().Set(args[0]->ucname()); \
}
@@ -44,7 +43,6 @@ using v8::Value;
#undef V
static void IsAnyArrayBuffer(const FunctionCallbackInfo& args) {
- CHECK_EQ(1, args.Length());
args.GetReturnValue().Set(
args[0]->IsArrayBuffer() || args[0]->IsSharedArrayBuffer());
}
diff --git a/test/parallel/test-util.js b/test/parallel/test-util.js
index 3b2729c107b4b1..a4aec080a9a0ad 100644
--- a/test/parallel/test-util.js
+++ b/test/parallel/test-util.js
@@ -43,9 +43,10 @@ assert.strictEqual(false, util.isArray(Object.create(Array.prototype)));
// isRegExp
assert.strictEqual(true, util.isRegExp(/regexp/));
-assert.strictEqual(true, util.isRegExp(RegExp()));
+assert.strictEqual(true, util.isRegExp(RegExp(), 'foo'));
assert.strictEqual(true, util.isRegExp(new RegExp()));
assert.strictEqual(true, util.isRegExp(context('RegExp')()));
+assert.strictEqual(false, util.isRegExp());
assert.strictEqual(false, util.isRegExp({}));
assert.strictEqual(false, util.isRegExp([]));
assert.strictEqual(false, util.isRegExp(new Date()));
@@ -53,7 +54,7 @@ assert.strictEqual(false, util.isRegExp(Object.create(RegExp.prototype)));
// isDate
assert.strictEqual(true, util.isDate(new Date()));
-assert.strictEqual(true, util.isDate(new Date(0)));
+assert.strictEqual(true, util.isDate(new Date(0), 'foo'));
assert.strictEqual(true, util.isDate(new (context('Date'))()));
assert.strictEqual(false, util.isDate(Date()));
assert.strictEqual(false, util.isDate({}));
From 0071560eb4d2de8d38c3c5ed1b4334c950e011db Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?=
Date: Thu, 8 Feb 2018 19:43:05 +0100
Subject: [PATCH 065/218] doc: fix description of createDecipheriv
PR-URL: https://github.com/nodejs/node/pull/18651
Refs: https://github.com/nodejs/node/pull/12223
Reviewed-By: Ruben Bridgewater
Reviewed-By: Luigi Pinca
Reviewed-By: Tiancheng "Timothy" Gu
---
doc/api/crypto.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/doc/api/crypto.md b/doc/api/crypto.md
index 182a2197567494..afd133f1939ad5 100644
--- a/doc/api/crypto.md
+++ b/doc/api/crypto.md
@@ -1289,8 +1289,8 @@ recent OpenSSL releases, `openssl list-cipher-algorithms` will display the
available cipher algorithms.
The `key` is the raw key used by the `algorithm` and `iv` is an
-[initialization vector][]. Both arguments must be `'utf8'` encoded strings or
-[buffers][`Buffer`].
+[initialization vector][]. Both arguments must be `'utf8'` encoded strings,
+[Buffers][`Buffer`], `TypedArray`, or `DataView`s.
### crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])
- `algorithm` {string}
- `key` {string | Buffer | TypedArray | DataView}
- `iv` {string | Buffer | TypedArray | DataView}
From ab8edc9d4844aaf66dcbad409415ffcc59c0aebc Mon Sep 17 00:00:00 2001
From: Anatoli Papirovski
Date: Sun, 4 Feb 2018 16:49:00 -0500
Subject: [PATCH 067/218] test: fix flaky timers-block-eventloop test
Due to extensive reliance on timings and the fs module, this test
is currently inherently flaky. Refactor it to simply use setImmediate
and only one busy loop.
PR-URL: https://github.com/nodejs/node/pull/18567
Reviewed-By: Matteo Collina
Reviewed-By: Ruben Bridgewater
---
.../sequential/test-timers-block-eventloop.js | 28 ++++++++-----------
1 file changed, 11 insertions(+), 17 deletions(-)
diff --git a/test/sequential/test-timers-block-eventloop.js b/test/sequential/test-timers-block-eventloop.js
index f6426e454e0882..811216fcb29e7d 100644
--- a/test/sequential/test-timers-block-eventloop.js
+++ b/test/sequential/test-timers-block-eventloop.js
@@ -1,24 +1,18 @@
'use strict';
const common = require('../common');
-const fs = require('fs');
-const platformTimeout = common.platformTimeout;
+const assert = require('assert');
+let called = false;
const t1 = setInterval(() => {
- common.busyLoop(platformTimeout(12));
-}, platformTimeout(10));
-
-const t2 = setInterval(() => {
- common.busyLoop(platformTimeout(15));
-}, platformTimeout(10));
-
-const t3 =
- setTimeout(common.mustNotCall('eventloop blocked!'), platformTimeout(200));
-
-setTimeout(function() {
- fs.stat('/dev/nonexistent', () => {
+ assert(!called);
+ called = true;
+ setImmediate(common.mustCall(() => {
clearInterval(t1);
clearInterval(t2);
- clearTimeout(t3);
- });
-}, platformTimeout(50));
+ }));
+}, 10);
+
+const t2 = setInterval(() => {
+ common.busyLoop(20);
+}, 10);
From 86e3c89ea4e281e1aea2a6adec9a598c7c4939b0 Mon Sep 17 00:00:00 2001
From: Ruben Bridgewater
Date: Mon, 5 Feb 2018 19:49:50 +0100
Subject: [PATCH 068/218] benchmark: improve compare output
The current output uses JSON.stringify to escape the config values.
This switches to util.inspect to have a better readable output.
PR-URL: https://github.com/nodejs/node/pull/18597
Reviewed-By: James M Snell
Reviewed-By: Anatoli Papirovski
Reviewed-By: Andreas Madsen
Reviewed-By: Luigi Pinca
---
benchmark/compare.js | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/benchmark/compare.js b/benchmark/compare.js
index 6b51a70eb9a41b..e7866b60e36418 100644
--- a/benchmark/compare.js
+++ b/benchmark/compare.js
@@ -1,6 +1,7 @@
'use strict';
-const fork = require('child_process').fork;
+const { fork } = require('child_process');
+const { inspect } = require('util');
const path = require('path');
const CLI = require('./_cli.js');
const BenchmarkProgress = require('./_benchmark_progress.js');
@@ -76,7 +77,7 @@ if (showProgress) {
// Construct configuration string, " A=a, B=b, ..."
let conf = '';
for (const key of Object.keys(data.conf)) {
- conf += ` ${key}=${JSON.stringify(data.conf[key])}`;
+ conf += ` ${key}=${inspect(data.conf[key])}`;
}
conf = conf.slice(1);
// Escape quotes (") for correct csv formatting
From 9bce14172aae3c4e0d59121d552d08fb261ed657 Mon Sep 17 00:00:00 2001
From: Joyee Cheung
Date: Thu, 1 Feb 2018 22:39:51 +0800
Subject: [PATCH 069/218] build: do not suppress output in make doc-only
This helps to show the cause of errors in the CI.
PR-URL: https://github.com/nodejs/node/pull/18507
Reviewed-By: James M Snell
Reviewed-By: Gibson Fahnestock
Reviewed-By: Daniel Bevenius
Reviewed-By: Ruben Bridgewater
Reviewed-By: Colin Ihrig
---
Makefile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Makefile b/Makefile
index d0b481d03ab9f3..03a66fb4bbf00d 100644
--- a/Makefile
+++ b/Makefile
@@ -558,7 +558,7 @@ doc-only: $(apidoc_dirs) $(apiassets)
if [ ! -d doc/api/assets ]; then \
$(MAKE) tools/doc/node_modules/js-yaml/package.json; \
fi;
- @$(MAKE) -s $(apidocs_html) $(apidocs_json)
+ @$(MAKE) $(apidocs_html) $(apidocs_json)
doc: $(NODE_EXE) doc-only
From cbd698a5217353f0c68e4aca628936d8a8db181b Mon Sep 17 00:00:00 2001
From: cjihrig
Date: Thu, 1 Feb 2018 10:33:27 -0500
Subject: [PATCH 070/218] test: refactor test-http-abort-before-end
This test was added over six years ago, and the behavior
seems to have changed since then. When the test was originally
written, common.mustCall() did not exist. The only assertion
in this test was not actually executing. Instead of an 'error'
event being emitted as expected, an 'abort' event was emitted.
PR-URL: https://github.com/nodejs/node/pull/18508
Reviewed-By: Luigi Pinca
Reviewed-By: James M Snell
---
test/parallel/test-http-abort-before-end.js | 19 ++++++++-----------
1 file changed, 8 insertions(+), 11 deletions(-)
diff --git a/test/parallel/test-http-abort-before-end.js b/test/parallel/test-http-abort-before-end.js
index 37d1291b074127..5577f256ca2ec9 100644
--- a/test/parallel/test-http-abort-before-end.js
+++ b/test/parallel/test-http-abort-before-end.js
@@ -22,25 +22,22 @@
'use strict';
const common = require('../common');
const http = require('http');
-const assert = require('assert');
const server = http.createServer(common.mustNotCall());
-server.listen(0, function() {
+server.listen(0, common.mustCall(() => {
const req = http.request({
method: 'GET',
host: '127.0.0.1',
- port: this.address().port
+ port: server.address().port
});
- req.on('error', function(ex) {
- // https://github.com/joyent/node/issues/1399#issuecomment-2597359
- // abort() should emit an Error, not the net.Socket object
- assert(ex instanceof Error);
- });
+ req.on('abort', common.mustCall(() => {
+ server.close();
+ }));
+
+ req.on('error', common.mustNotCall());
req.abort();
req.end();
-
- server.close();
-});
+}));
From 1faae90b74b02bec5e449ed5494bd7abda03f44b Mon Sep 17 00:00:00 2001
From: Anatoli Papirovski
Date: Sun, 4 Feb 2018 13:43:21 -0500
Subject: [PATCH 071/218] readline: use Date.now() and move test to parallel
The readline module wants a truthy time while using Timer.now() doesn't
necessarily guarantee that early on in the process' life. It also
doesn't actually resolve the timing issues experienced in an earlier
issue. Instead, this PR fixes the related tests and moves them back
to parallel.
Refs: https://github.com/nodejs/node/issues/14674
PR-URL: https://github.com/nodejs/node/pull/18563
Reviewed-By: Anna Henningsen
Reviewed-By: Luigi Pinca
Reviewed-By: Ruben Bridgewater
---
lib/readline.js | 10 +-
test/parallel/test-readline-interface.js | 77 +++++++++++++++
test/sequential/test-readline-interface.js | 108 ---------------------
3 files changed, 81 insertions(+), 114 deletions(-)
delete mode 100644 test/sequential/test-readline-interface.js
diff --git a/lib/readline.js b/lib/readline.js
index 3df7af1df3a99d..d749e2c8f23f0f 100644
--- a/lib/readline.js
+++ b/lib/readline.js
@@ -47,8 +47,6 @@ const {
kClearScreenDown
} = CSI;
-const { now } = process.binding('timer_wrap').Timer;
-
const kHistorySize = 30;
const kMincrlfDelay = 100;
// \r\n, \n, or \r followed by something other than \n
@@ -400,7 +398,7 @@ Interface.prototype._normalWrite = function(b) {
}
var string = this._decoder.write(b);
if (this._sawReturnAt &&
- now() - this._sawReturnAt <= this.crlfDelay) {
+ Date.now() - this._sawReturnAt <= this.crlfDelay) {
string = string.replace(/^\n/, '');
this._sawReturnAt = 0;
}
@@ -413,7 +411,7 @@ Interface.prototype._normalWrite = function(b) {
this._line_buffer = null;
}
if (newPartContainsEnding) {
- this._sawReturnAt = string.endsWith('\r') ? now() : 0;
+ this._sawReturnAt = string.endsWith('\r') ? Date.now() : 0;
// got one or more newlines; process into "line" events
var lines = string.split(lineEnding);
@@ -908,14 +906,14 @@ Interface.prototype._ttyWrite = function(s, key) {
switch (key.name) {
case 'return': // carriage return, i.e. \r
- this._sawReturnAt = now();
+ this._sawReturnAt = Date.now();
this._line();
break;
case 'enter':
// When key interval > crlfDelay
if (this._sawReturnAt === 0 ||
- now() - this._sawReturnAt > this.crlfDelay) {
+ Date.now() - this._sawReturnAt > this.crlfDelay) {
this._line();
}
this._sawReturnAt = 0;
diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js
index f3fdd5044f4862..e58b7917bcb563 100644
--- a/test/parallel/test-readline-interface.js
+++ b/test/parallel/test-readline-interface.js
@@ -873,3 +873,80 @@ function isWarned(emitter) {
assert.strictEqual(rl._prompt, '$ ');
}
});
+
+// For the purposes of the following tests, we do not care about the exact
+// value of crlfDelay, only that the behaviour conforms to what's expected.
+// Setting it to Infinity allows the test to succeed even under extreme
+// CPU stress.
+const crlfDelay = Infinity;
+
+[ true, false ].forEach(function(terminal) {
+ // sending multiple newlines at once that does not end with a new line
+ // and a `end` event(last line is)
+
+ // \r\n should emit one line event, not two
+ {
+ const fi = new FakeInput();
+ const rli = new readline.Interface(
+ {
+ input: fi,
+ output: fi,
+ terminal: terminal,
+ crlfDelay
+ }
+ );
+ const expectedLines = ['foo', 'bar', 'baz', 'bat'];
+ let callCount = 0;
+ rli.on('line', function(line) {
+ assert.strictEqual(line, expectedLines[callCount]);
+ callCount++;
+ });
+ fi.emit('data', expectedLines.join('\r\n'));
+ assert.strictEqual(callCount, expectedLines.length - 1);
+ rli.close();
+ }
+
+ // \r\n should emit one line event when split across multiple writes.
+ {
+ const fi = new FakeInput();
+ const rli = new readline.Interface({
+ input: fi,
+ output: fi,
+ terminal: terminal,
+ crlfDelay
+ });
+ const expectedLines = ['foo', 'bar', 'baz', 'bat'];
+ let callCount = 0;
+ rli.on('line', function(line) {
+ assert.strictEqual(line, expectedLines[callCount]);
+ callCount++;
+ });
+ expectedLines.forEach(function(line) {
+ fi.emit('data', `${line}\r`);
+ fi.emit('data', '\n');
+ });
+ assert.strictEqual(callCount, expectedLines.length);
+ rli.close();
+ }
+
+ // Emit one line event when the delay between \r and \n is
+ // over the default crlfDelay but within the setting value.
+ {
+ const fi = new FakeInput();
+ const delay = 125;
+ const rli = new readline.Interface({
+ input: fi,
+ output: fi,
+ terminal: terminal,
+ crlfDelay
+ });
+ let callCount = 0;
+ rli.on('line', () => callCount++);
+ fi.emit('data', '\r');
+ setTimeout(common.mustCall(() => {
+ fi.emit('data', '\n');
+ assert.strictEqual(callCount, 1);
+ rli.close();
+ }), delay);
+ }
+});
diff --git a/test/sequential/test-readline-interface.js b/test/sequential/test-readline-interface.js
deleted file mode 100644
index 488dd8338da761..00000000000000
--- a/test/sequential/test-readline-interface.js
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// Flags: --expose_internals
-'use strict';
-const common = require('../common');
-
-// These test cases are in `sequential` rather than the analogous test file in
-// `parallel` because they become unreliable under load. The unreliability under
-// load was determined empirically when the test cases were in `parallel` by
-// running:
-// tools/test.py -j 96 --repeat 192 test/parallel/test-readline-interface.js
-
-const assert = require('assert');
-const readline = require('readline');
-const EventEmitter = require('events').EventEmitter;
-const inherits = require('util').inherits;
-
-function FakeInput() {
- EventEmitter.call(this);
-}
-inherits(FakeInput, EventEmitter);
-FakeInput.prototype.resume = () => {};
-FakeInput.prototype.pause = () => {};
-FakeInput.prototype.write = () => {};
-FakeInput.prototype.end = () => {};
-
-[ true, false ].forEach(function(terminal) {
- // sending multiple newlines at once that does not end with a new line
- // and a `end` event(last line is)
-
- // \r\n should emit one line event, not two
- {
- const fi = new FakeInput();
- const rli = new readline.Interface(
- { input: fi, output: fi, terminal: terminal }
- );
- const expectedLines = ['foo', 'bar', 'baz', 'bat'];
- let callCount = 0;
- rli.on('line', function(line) {
- assert.strictEqual(line, expectedLines[callCount]);
- callCount++;
- });
- fi.emit('data', expectedLines.join('\r\n'));
- assert.strictEqual(callCount, expectedLines.length - 1);
- rli.close();
- }
-
- // \r\n should emit one line event when split across multiple writes.
- {
- const fi = new FakeInput();
- const rli = new readline.Interface(
- { input: fi, output: fi, terminal: terminal }
- );
- const expectedLines = ['foo', 'bar', 'baz', 'bat'];
- let callCount = 0;
- rli.on('line', function(line) {
- assert.strictEqual(line, expectedLines[callCount]);
- callCount++;
- });
- expectedLines.forEach(function(line) {
- fi.emit('data', `${line}\r`);
- fi.emit('data', '\n');
- });
- assert.strictEqual(callCount, expectedLines.length);
- rli.close();
- }
-
- // Emit one line event when the delay between \r and \n is
- // over the default crlfDelay but within the setting value.
- {
- const fi = new FakeInput();
- const delay = 125;
- const crlfDelay = common.platformTimeout(1000);
- const rli = new readline.Interface({
- input: fi,
- output: fi,
- terminal: terminal,
- crlfDelay
- });
- let callCount = 0;
- rli.on('line', () => callCount++);
- fi.emit('data', '\r');
- setTimeout(common.mustCall(() => {
- fi.emit('data', '\n');
- assert.strictEqual(callCount, 1);
- rli.close();
- }), delay);
- }
-});
From 50bdf0ed78925665d6c1709f5f3e492739127917 Mon Sep 17 00:00:00 2001
From: "Tim O. Peters"
Date: Thu, 4 Jan 2018 11:17:01 +0100
Subject: [PATCH 072/218] doc: be more explicit in the sypnosis
Assuming less knowledge on the part of the reader, making it easier
to get start using Node.js.
PR-URL: https://github.com/nodejs/node/pull/17977
Fixes: https://github.com/nodejs/node/issues/17970,
Reviewed-By: Vse Mozhet Byt
Reviewed-By: Gireesh Punathil
Reviewed-By: Ruben Bridgewater
Reviewed-By: Jeremiah Senkpiel
---
doc/api/synopsis.md | 76 ++++++++++++++++++++++++++++++++++++++++-----
1 file changed, 68 insertions(+), 8 deletions(-)
diff --git a/doc/api/synopsis.md b/doc/api/synopsis.md
index ada2437387b7e2..508dde1ff483f8 100644
--- a/doc/api/synopsis.md
+++ b/doc/api/synopsis.md
@@ -9,9 +9,58 @@ Please see the [Command Line Options][] document for information about
different options and ways to run scripts with Node.js.
## Example
-
An example of a [web server][] written with Node.js which responds with
-`'Hello World'`:
+`'Hello World!'`:
+
+Commands displayed in this document are shown starting with `$` or `>`
+to replicate how they would appear in a user's terminal.
+Do not include the `$` and `>` character they are there to
+indicate the start of each command.
+
+There are many tutorials and examples that follow this
+convention: `$` or `>` for commands run as a regular user, and `#`
+for commands that should be executed as an administrator.
+
+Lines that don’t start with `$` or `>` character are typically showing
+the output of the previous command.
+
+Firstly, make sure to have downloaded and installed Node.js.
+See [this guide][] for further install information.
+
+Now, create an empty project folder called `projects`, navigate into it:
+Project folder can be named base on user's current project title but
+this example will use `projects` as the project folder.
+
+Linux and Mac:
+
+```console
+$ mkdir ~/projects
+$ cd ~/projects
+```
+
+Windows CMD:
+
+```console
+> mkdir %USERPROFILE%\projects
+> cd %USERPROFILE%\projects
+```
+
+Windows PowerShell:
+
+```console
+> mkdir $env:USERPROFILE\projects
+> cd $env:USERPROFILE\projects
+```
+
+Next, create a new source file in the `projects`
+ folder and call it `hello-world.js`.
+
+In Node.js it is considered good style to use
+hyphens (`-`) or underscores (`_`) to separate
+ multiple words in filenames.
+
+Open `hello-world.js` in any preferred text editor and
+paste in the following content.
```js
const http = require('http');
@@ -22,7 +71,7 @@ const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
- res.end('Hello World\n');
+ res.end('Hello World!\n');
});
server.listen(port, hostname, () => {
@@ -30,15 +79,26 @@ server.listen(port, hostname, () => {
});
```
-To run the server, put the code into a file called `example.js` and execute
-it with Node.js:
+Save the file, go back to the terminal window enter the following command:
-```txt
-$ node example.js
-Server running at http://127.0.0.1:3000/
+```console
+$ node hello-world.js
```
+An output like this should appear in the terminal to indicate Node.js
+server is running:
+
+ ```console
+ Server running at http://127.0.0.1:3000/
+ ````
+
+Now, open any preferred web browser and visit `http://127.0.0.1:3000`.
+
+If the browser displays the string `Hello, world!`, that indicates
+the server is working.
+
Many of the examples in the documentation can be run similarly.
[Command Line Options]: cli.html#cli_command_line_options
[web server]: http.html
+[this guide]: https://nodejs.org/en/download/package-manager/
From d4bccccf2305978d318de6d8950960e664bbdbe1 Mon Sep 17 00:00:00 2001
From: Shobhit Chittora
Date: Wed, 1 Nov 2017 01:31:02 +0530
Subject: [PATCH 073/218] tools: add fixer for prefer-assert-iferror.js
PR-URL: https://github.com/nodejs/node/pull/16648
Refs: https://github.com/nodejs/node/issues/16636
Reviewed-By: Anatoli Papirovski
Reviewed-By: Gibson Fahnestock
Reviewed-By: James M Snell
Reviewed-By: Ruben Bridgewater
---
.../test-eslint-prefer-assert-iferror.js | 14 +++++++----
tools/eslint-rules/prefer-assert-iferror.js | 23 +++++++++++++++++--
2 files changed, 31 insertions(+), 6 deletions(-)
diff --git a/test/parallel/test-eslint-prefer-assert-iferror.js b/test/parallel/test-eslint-prefer-assert-iferror.js
index 790207bc30cd43..6ecf92adbef51a 100644
--- a/test/parallel/test-eslint-prefer-assert-iferror.js
+++ b/test/parallel/test-eslint-prefer-assert-iferror.js
@@ -16,12 +16,18 @@ new RuleTester().run('prefer-assert-iferror', rule, {
],
invalid: [
{
- code: 'if (err) throw err;',
- errors: [{ message: 'Use assert.ifError(err) instead.' }]
+ code: 'require("assert");\n' +
+ 'if (err) throw err;',
+ errors: [{ message: 'Use assert.ifError(err) instead.' }],
+ output: 'require("assert");\n' +
+ 'assert.ifError(err);'
},
{
- code: 'if (error) { throw error; }',
- errors: [{ message: 'Use assert.ifError(error) instead.' }]
+ code: 'require("assert");\n' +
+ 'if (error) { throw error; }',
+ errors: [{ message: 'Use assert.ifError(error) instead.' }],
+ output: 'require("assert");\n' +
+ 'assert.ifError(error);'
}
]
});
diff --git a/tools/eslint-rules/prefer-assert-iferror.js b/tools/eslint-rules/prefer-assert-iferror.js
index e15287417693e0..399ee7403a6c88 100644
--- a/tools/eslint-rules/prefer-assert-iferror.js
+++ b/tools/eslint-rules/prefer-assert-iferror.js
@@ -5,9 +5,12 @@
'use strict';
+const utils = require('./rules-utils.js');
+
module.exports = {
create(context) {
const sourceCode = context.getSourceCode();
+ var assertImported = false;
function hasSameTokens(nodeA, nodeB) {
const aTokens = sourceCode.getTokens(nodeA);
@@ -20,8 +23,15 @@ module.exports = {
});
}
+ function checkAssertNode(node) {
+ if (utils.isRequired(node, ['assert'])) {
+ assertImported = true;
+ }
+ }
+
return {
- IfStatement(node) {
+ 'CallExpression': (node) => checkAssertNode(node),
+ 'IfStatement': (node) => {
const firstStatement = node.consequent.type === 'BlockStatement' ?
node.consequent.body[0] :
node.consequent;
@@ -30,10 +40,19 @@ module.exports = {
firstStatement.type === 'ThrowStatement' &&
hasSameTokens(node.test, firstStatement.argument)
) {
+ const argument = sourceCode.getText(node.test);
context.report({
node: firstStatement,
message: 'Use assert.ifError({{argument}}) instead.',
- data: { argument: sourceCode.getText(node.test) }
+ data: { argument },
+ fix: (fixer) => {
+ if (assertImported) {
+ return fixer.replaceText(
+ node,
+ `assert.ifError(${argument});`
+ );
+ }
+ }
});
}
}
From 1ea1970c3758eb53baae036138094adbb26e57f7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=99=88=E5=88=9A?=
Date: Fri, 2 Feb 2018 18:40:01 +0800
Subject: [PATCH 074/218] doc: modify the return value of request.write()
PR-URL: https://github.com/nodejs/node/pull/18526
Reviewed-By: Ruben Bridgewater
Reviewed-By: Luigi Pinca
Reviewed-By: James M Snell
---
doc/api/http.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/doc/api/http.md b/doc/api/http.md
index 49083e2193953c..7331d8bc5d969d 100644
--- a/doc/api/http.md
+++ b/doc/api/http.md
@@ -681,7 +681,9 @@ Defaults to `'utf8'`.
The `callback` argument is optional and will be called when this chunk of data
is flushed.
-Returns `request`.
+Returns `true` if the entire data was flushed successfully to the kernel
+buffer. Returns `false` if all or part of the data was queued in user memory.
+`'drain'` will be emitted when the buffer is free again.
## Class: http.Server
* `urlString` {string} The URL string to parse.
From b48ca0a140dc727c0c9d3d2ffb204a201745d2d5 Mon Sep 17 00:00:00 2001
From: BufoViridis <30531954+BufoViridis@users.noreply.github.com>
Date: Tue, 30 Jan 2018 19:43:50 +0200
Subject: [PATCH 085/218] src: fix crypto.pbkdf2 callback error argument
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Callbacks should always return `null` instead of `undefined` if no
error occurred.
PR-URL: https://github.com/nodejs/node/pull/18458
Reviewed-By: Ben Noordhuis
Reviewed-By: Tobias Nießen
Reviewed-By: Fedor Indutny
Reviewed-By: James M Snell
---
src/node_crypto.cc | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/node_crypto.cc b/src/node_crypto.cc
index 6b5958b35e7049..580d6a4f4d55bc 100644
--- a/src/node_crypto.cc
+++ b/src/node_crypto.cc
@@ -5421,7 +5421,7 @@ void PBKDF2Request::Work(uv_work_t* work_req) {
void PBKDF2Request::After(Local (*argv)[2]) {
if (success_) {
- (*argv)[0] = Undefined(env()->isolate());
+ (*argv)[0] = Null(env()->isolate());
(*argv)[1] = Buffer::New(env(), key_, keylen_).ToLocalChecked();
key_ = nullptr;
keylen_ = 0;
From 88d3028e22ff3cc2db522364aa6a693401cef06d Mon Sep 17 00:00:00 2001
From: Yang Guo
Date: Fri, 9 Feb 2018 14:23:42 +0100
Subject: [PATCH 086/218] build: no longer have v8-debug.h as dependency.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Ref: https://github.com/nodejs/node/issues/18643
PR-URL: https://github.com/nodejs/node/pull/18677
Refs: https://github.com/nodejs/node/issues/18643
Reviewed-By: Ben Noordhuis
Reviewed-By: Colin Ihrig
Reviewed-By: Ruben Bridgewater
Reviewed-By: James M Snell
Reviewed-By: Tobias Nießen
---
node.gyp | 1 -
1 file changed, 1 deletion(-)
diff --git a/node.gyp b/node.gyp
index 04b090cbd37ec4..ee4157567f5a31 100644
--- a/node.gyp
+++ b/node.gyp
@@ -364,7 +364,6 @@
'src/util-inl.h',
'deps/http_parser/http_parser.h',
'deps/v8/include/v8.h',
- 'deps/v8/include/v8-debug.h',
# javascript files to make for an even more pleasant IDE experience
'<@(library_files)',
# node.gyp is added to the project by default.
From b8f2acd2e863719c483e36dc5ea60affbe0156ff Mon Sep 17 00:00:00 2001
From: Matheus Marchini
Date: Mon, 12 Feb 2018 12:43:11 -0500
Subject: [PATCH 087/218] doc: add mmarchini to collaborators
PR-URL: https://github.com/nodejs/node/pull/18740
Reviewed-By: Joyee Cheung
Reviewed-By: Matteo Collina
Reviewed-By: Ruben Bridgewater
Reviewed-By: Richard Lau
---
README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/README.md b/README.md
index f0451582584532..5ba9d5491d666b 100644
--- a/README.md
+++ b/README.md
@@ -426,6 +426,8 @@ For more information about the governance of the Node.js project, see
**Mikeal Rogers** <mikeal.rogers@gmail.com>
* [misterdjules](https://github.com/misterdjules) -
**Julien Gilli** <jgilli@nodejs.org>
+* [mmarchini](https://github.com/mmarchini) -
+**Matheus Marchini** <matheus@sthima.com>
* [mscdex](https://github.com/mscdex) -
**Brian White** <mscdex@mscdex.net>
* [MylesBorins](https://github.com/MylesBorins) -
From f4ddaaec0ed0b5a7eb8a9b648ffc12db9df5e144 Mon Sep 17 00:00:00 2001
From: Myles Borins
Date: Tue, 13 Feb 2018 02:09:44 -0500
Subject: [PATCH 088/218] doc: move Fedor to TSC Emeritus
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
In a conversation Fedor requested that this PR be made. They plan
to continue working on core as a Collaborator. It is this committers
belief that if Fedor would like to join the TSC again in the future
there is no reason that could not be made possible.
Thanks for all the hard work!
PR-URL: https://github.com/nodejs/node/pull/18752
Reviewed-By: Gireesh Punathil
Reviewed-By: Fedor Indutny
Reviewed-By: Yuta Hiroto
Reviewed-By: Ruben Bridgewater
Reviewed-By: Colin Ihrig
Reviewed-By: James M Snell
Reviewed-By: Anatoli Papirovski
Reviewed-By: Ali Ijaz Sheikh
Reviewed-By: Matteo Collina
Reviewed-By: Сковорода Никита Андреевич
Reviewed-By: Rich Trott
Reviewed-By: Jon Moss
Reviewed-By: Tobias Nießen
Reviewed-By: Joyee Cheung
Reviewed-By: Sakthipriyan Vairamani
Reviewed-By: Michael Dawson
Reviewed-By: Tiancheng "Timothy" Gu
Reviewed-By: Evan Lucas
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 5ba9d5491d666b..e537407c8685bd 100644
--- a/README.md
+++ b/README.md
@@ -246,8 +246,6 @@ For more information about the governance of the Node.js project, see
**Jeremiah Senkpiel** <fishrock123@rocketmail.com>
* [gibfahn](https://github.com/gibfahn) -
**Gibson Fahnestock** <gibfahn@gmail.com> (he/him)
-* [indutny](https://github.com/indutny) -
-**Fedor Indutny** <fedor.indutny@gmail.com>
* [jasnell](https://github.com/jasnell) -
**James M Snell** <jasnell@gmail.com> (he/him)
* [joyeecheung](https://github.com/joyeecheung) -
@@ -277,6 +275,8 @@ For more information about the governance of the Node.js project, see
**Ben Noordhuis** <info@bnoordhuis.nl>
* [chrisdickinson](https://github.com/chrisdickinson) -
**Chris Dickinson** <christopher.s.dickinson@gmail.com>
+* [indutny](https://github.com/indutny) -
+**Fedor Indutny** <fedor.indutny@gmail.com>
* [isaacs](https://github.com/isaacs) -
**Isaac Z. Schlueter** <i@izs.me>
* [joshgav](https://github.com/joshgav) -
From 9129bc4fde61df5df0447262e756eb8e1168dbcc Mon Sep 17 00:00:00 2001
From: Aaron Bieber
Date: Sat, 3 Feb 2018 09:52:29 -0700
Subject: [PATCH 089/218] lib: set process.execPath on OpenBSD
PR-URL: https://github.com/nodejs/node/pull/18543
Reviewed-By: Luigi Pinca
Reviewed-By: James M Snell
---
lib/internal/bootstrap_node.js | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/lib/internal/bootstrap_node.js b/lib/internal/bootstrap_node.js
index cc2b5ff3daa3ff..6b7ac044f638af 100644
--- a/lib/internal/bootstrap_node.js
+++ b/lib/internal/bootstrap_node.js
@@ -71,6 +71,13 @@
// URL::ToObject() method is used.
NativeModule.require('internal/url');
+ // On OpenBSD process.execPath will be relative unless we
+ // get the full path before process.execPath is used.
+ if (process.platform === 'openbsd') {
+ const { realpathSync } = NativeModule.require('fs');
+ process.execPath = realpathSync.native(process.execPath);
+ }
+
Object.defineProperty(process, 'argv0', {
enumerable: true,
configurable: false,
From 9236332cc3488e6477602d46c5842d585f8de3c1 Mon Sep 17 00:00:00 2001
From: Aaron Bieber
Date: Sat, 3 Feb 2018 09:53:57 -0700
Subject: [PATCH 090/218] test: update a few tests to work on OpenBSD
PR-URL: https://github.com/nodejs/node/pull/18543
Reviewed-By: Luigi Pinca
Reviewed-By: James M Snell
---
test/common/index.js | 1 +
test/parallel/test-child-process-exec-timeout.js | 11 +++++++++--
test/parallel/test-fs-utimes.js | 4 ++--
test/parallel/test-http-dns-error.js | 8 ++++++--
test/parallel/test-net-dns-error.js | 8 ++++++--
test/parallel/test-setproctitle.js | 2 +-
test/sequential/test-module-loading.js | 12 +++++++++---
7 files changed, 34 insertions(+), 12 deletions(-)
diff --git a/test/common/index.js b/test/common/index.js
index 85857f753e3454..80ba48d25a1710 100644
--- a/test/common/index.js
+++ b/test/common/index.js
@@ -45,6 +45,7 @@ exports.isLinuxPPCBE = (process.platform === 'linux') &&
(os.endianness() === 'BE');
exports.isSunOS = process.platform === 'sunos';
exports.isFreeBSD = process.platform === 'freebsd';
+exports.isOpenBSD = process.platform === 'openbsd';
exports.isLinux = process.platform === 'linux';
exports.isOSX = process.platform === 'darwin';
diff --git a/test/parallel/test-child-process-exec-timeout.js b/test/parallel/test-child-process-exec-timeout.js
index ed25d9bff825a9..e08aff908522f2 100644
--- a/test/parallel/test-child-process-exec-timeout.js
+++ b/test/parallel/test-child-process-exec-timeout.js
@@ -16,15 +16,22 @@ const cmd = `"${process.execPath}" "${__filename}" child`;
// Test the case where a timeout is set, and it expires.
cp.exec(cmd, { timeout: 1 }, common.mustCall((err, stdout, stderr) => {
+ let sigterm = 'SIGTERM';
assert.strictEqual(err.killed, true);
- assert.strictEqual(err.code, null);
+ // TODO OpenBSD returns a null signal and 143 for code
+ if (common.isOpenBSD) {
+ assert.strictEqual(err.code, 143);
+ sigterm = null;
+ } else {
+ assert.strictEqual(err.code, null);
+ }
// At least starting with Darwin Kernel Version 16.4.0, sending a SIGTERM to a
// process that is still starting up kills it with SIGKILL instead of SIGTERM.
// See: https://github.com/libuv/libuv/issues/1226
if (common.isOSX)
assert.ok(err.signal === 'SIGTERM' || err.signal === 'SIGKILL');
else
- assert.strictEqual(err.signal, 'SIGTERM');
+ assert.strictEqual(err.signal, sigterm);
assert.strictEqual(err.cmd, cmd);
assert.strictEqual(stdout.trim(), '');
assert.strictEqual(stderr.trim(), '');
diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js
index 103b4640961937..3dc0bb59def6a2 100644
--- a/test/parallel/test-fs-utimes.js
+++ b/test/parallel/test-fs-utimes.js
@@ -172,8 +172,8 @@ process.on('exit', function() {
const path = `${tmpdir.path}/test-utimes-precision`;
fs.writeFileSync(path, '');
-// test Y2K38 for all platforms [except 'arm', and 'SunOS']
-if (!process.arch.includes('arm') && !common.isSunOS) {
+// test Y2K38 for all platforms [except 'arm', 'OpenBSD' and 'SunOS']
+if (!process.arch.includes('arm') && !common.isOpenBSD && !common.isSunOS) {
// because 2 ** 31 doesn't look right
// eslint-disable-next-line space-infix-ops
const Y2K38_mtime = 2**31;
diff --git a/test/parallel/test-http-dns-error.js b/test/parallel/test-http-dns-error.js
index 900cf40e6b209b..06a15c89fb46b3 100644
--- a/test/parallel/test-http-dns-error.js
+++ b/test/parallel/test-http-dns-error.js
@@ -32,6 +32,10 @@ const https = require('https');
const host = '*'.repeat(256);
const MAX_TRIES = 5;
+let errCode = 'ENOTFOUND';
+if (common.isOpenBSD)
+ errCode = 'EAI_FAIL';
+
function tryGet(mod, tries) {
// Bad host name should not throw an uncatchable exception.
// Ensure that there is time to attach an error listener.
@@ -41,7 +45,7 @@ function tryGet(mod, tries) {
tryGet(mod, ++tries);
return;
}
- assert.strictEqual(err.code, 'ENOTFOUND');
+ assert.strictEqual(err.code, errCode);
}));
// http.get() called req1.end() for us
}
@@ -57,7 +61,7 @@ function tryRequest(mod, tries) {
tryRequest(mod, ++tries);
return;
}
- assert.strictEqual(err.code, 'ENOTFOUND');
+ assert.strictEqual(err.code, errCode);
}));
req.end();
}
diff --git a/test/parallel/test-net-dns-error.js b/test/parallel/test-net-dns-error.js
index beebcd8cb9cf44..a5ae415592fed4 100644
--- a/test/parallel/test-net-dns-error.js
+++ b/test/parallel/test-net-dns-error.js
@@ -27,17 +27,21 @@ const net = require('net');
const host = '*'.repeat(256);
+let errCode = 'ENOTFOUND';
+if (common.isOpenBSD)
+ errCode = 'EAI_FAIL';
+
function do_not_call() {
throw new Error('This function should not have been called.');
}
const socket = net.connect(42, host, do_not_call);
socket.on('error', common.mustCall(function(err) {
- assert.strictEqual(err.code, 'ENOTFOUND');
+ assert.strictEqual(err.code, errCode);
}));
socket.on('lookup', function(err, ip, type) {
assert(err instanceof Error);
- assert.strictEqual(err.code, 'ENOTFOUND');
+ assert.strictEqual(err.code, errCode);
assert.strictEqual(ip, undefined);
assert.strictEqual(type, undefined);
});
diff --git a/test/parallel/test-setproctitle.js b/test/parallel/test-setproctitle.js
index 4bb88c4ba06922..1ab6bff6a30848 100644
--- a/test/parallel/test-setproctitle.js
+++ b/test/parallel/test-setproctitle.js
@@ -34,7 +34,7 @@ exec(cmd, common.mustCall((error, stdout, stderr) => {
assert.strictEqual(stderr, '');
// freebsd always add ' (procname)' to the process title
- if (common.isFreeBSD)
+ if (common.isFreeBSD || common.isOpenBSD)
title += ` (${path.basename(process.execPath)})`;
// omitting trailing whitespace and \n
diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js
index 8b097142698e6f..3d0de954c58e8a 100644
--- a/test/sequential/test-module-loading.js
+++ b/test/sequential/test-module-loading.js
@@ -20,7 +20,7 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
-require('../common');
+const common = require('../common');
const assert = require('assert');
const path = require('path');
const fs = require('fs');
@@ -197,7 +197,10 @@ try {
require(`${loadOrder}file3`);
} catch (e) {
// Not a real .node module, but we know we require'd the right thing.
- assert.ok(/file3\.node/.test(e.message.replace(backslash, '/')));
+ if (common.isOpenBSD) // OpenBSD errors with non-ELF object error
+ assert.ok(/File not an ELF object/.test(e.message.replace(backslash, '/')));
+ else
+ assert.ok(/file3\.node/.test(e.message.replace(backslash, '/')));
}
assert.strictEqual(require(`${loadOrder}file4`).file4, 'file4.reg', msg);
assert.strictEqual(require(`${loadOrder}file5`).file5, 'file5.reg2', msg);
@@ -205,7 +208,10 @@ try {
try {
require(`${loadOrder}file7`);
} catch (e) {
- assert.ok(/file7\/index\.node/.test(e.message.replace(backslash, '/')));
+ if (common.isOpenBSD)
+ assert.ok(/File not an ELF object/.test(e.message.replace(backslash, '/')));
+ else
+ assert.ok(/file7\/index\.node/.test(e.message.replace(backslash, '/')));
}
assert.strictEqual(require(`${loadOrder}file8`).file8, 'file8/index.reg',
msg);
From ab005592beaac499b20bb1a056d9d69b40ba0320 Mon Sep 17 00:00:00 2001
From: Ali Ijaz Sheikh
Date: Mon, 22 Jan 2018 12:19:05 -0800
Subject: [PATCH 091/218] deps: V8: backport 76c3ac5 from upstream
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
This fixes a bug in the CPU profiler where some ticks were attributed
to the wrong file.
Original commit message:
[cpu-profiler] Fix script name when recording inlining info
Use the script name from the shared function info to create an
inline entry. Otherwise functions are attributed to the wrong file
in the CpuProfileNode.
See https://github.com/GoogleCloudPlatform/cloud-profiler-nodejs/issues/89
Bug: v8:7203, v8:7241
Change-Id: I8ea31943741770e6611275a9c93375922b934547
Reviewed-on: https://chromium-review.googlesource.com/848093
Reviewed-by: Jaroslav Sevcik
Commit-Queue: Franziska Hinkelmann