From 79dc6291dc6f5fc69268a20de912c6d19ae96364 Mon Sep 17 00:00:00 2001 From: wandalen Date: Mon, 17 Apr 2017 06:02:37 +0300 Subject: [PATCH] console: take care of console set undefined case If global.console write undefined would come earlier than global.console read then lazy read in get would happen, despite write was done. This commit fix the problem. Fixes: https://github.com/nodejs/node/issues/11805 --- lib/internal/bootstrap_node.js | 9 +++++++- .../parallel/test-console-assing-undefined.js | 21 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-console-assing-undefined.js diff --git a/lib/internal/bootstrap_node.js b/lib/internal/bootstrap_node.js index 2a01daa0a61990..5ee664396defce 100644 --- a/lib/internal/bootstrap_node.js +++ b/lib/internal/bootstrap_node.js @@ -272,6 +272,7 @@ configurable: true, enumerable: false, get: function() { + NativeModule.require('console').log( 'console get' ); if (!console) { console = (originalConsole === undefined) ? NativeModule.require('console') : @@ -286,7 +287,13 @@ return console; }, set: function(customConsole) { - console = customConsole; + NativeModule.require('console').log( 'console set' ); + Object.defineProperty(global, 'console', { + configurable: true, + writable: true, + enumerable: false, + value: console + }); } }); setupInspectorCommandLineAPI(); diff --git a/test/parallel/test-console-assing-undefined.js b/test/parallel/test-console-assing-undefined.js new file mode 100644 index 00000000000000..6a67dc57e8b204 --- /dev/null +++ b/test/parallel/test-console-assing-undefined.js @@ -0,0 +1,21 @@ +'use strict'; + +// Should be above require, because code in require read console +// what we are trying to avoid +// set should be earlier than get + +global.console = undefined; + +// Initially, the `console` variable is `undefined`, since console will be +// lazily loaded in the getter. + +const common = require('../common'); +const assert = require('assert'); + +// global.console's getter is called +// Since the `console` cache variable is `undefined` and therefore false-y, +// the getter still calls NativeModule.require() and returns the object +// obtained from it, instead of returning `undefined` as expected. + +assert.strictEqual(global.console, undefined, 'first read'); +assert.strictEqual(global.console, undefined, 'second read');