From c74b44a96a8a8e06f88dd672320592ac27d5c25a Mon Sep 17 00:00:00 2001 From: "JiaLi.Passion" Date: Tue, 25 Jul 2017 09:20:38 +0900 Subject: [PATCH] fix(console): console.log in nodejs should run in root Zone --- lib/node/node.ts | 18 +++++++++++++++++ test/node/console.spec.ts | 41 +++++++++++++++++++++++++++++++++++++++ test/node_tests.ts | 1 + 3 files changed, 60 insertions(+) create mode 100644 test/node/console.spec.ts diff --git a/lib/node/node.ts b/lib/node/node.ts index a6e660135..ad96fff9f 100644 --- a/lib/node/node.ts +++ b/lib/node/node.ts @@ -134,3 +134,21 @@ Zone.__load_patch('crypto', (global: any, Zone: ZoneType, api: _ZonePrivate) => }); } }); + +Zone.__load_patch('console', (global: any, Zone: ZoneType, api: _ZonePrivate) => { + const consoleMethods = + ['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace']; + consoleMethods.forEach((m: string) => { + const originalMethod = (console as any)[Zone.__symbol__(m)] = (console as any)[m]; + if (originalMethod) { + (console as any)[m] = function() { + const args = Array.prototype.slice.call(arguments); + if (Zone.current === Zone.root) { + return originalMethod.apply(this, args); + } else { + return Zone.root.run(originalMethod, this, args); + } + }; + } + }); +}); diff --git a/test/node/console.spec.ts b/test/node/console.spec.ts new file mode 100644 index 000000000..846d220ba --- /dev/null +++ b/test/node/console.spec.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ +describe('node console', () => { + const log: string[] = []; + const zone = Zone.current.fork({ + name: 'console', + onScheduleTask: function( + delegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) { + log.push(task.source); + return delegate.scheduleTask(targetZone, task); + } + }); + + beforeEach(() => { + log.length = 0; + }); + + it('console methods should run in root zone', () => { + zone.run(() => { + console.log('test'); + console.warn('test'); + console.error('test'); + console.info('test'); + console.trace('test'); + try { + console.assert(false, 'test'); + } catch (error) { + } + console.dir('.'); + console.time('start'); + console.timeEnd('start'); + console.debug && console.debug('test'); + }); + expect(log).toEqual([]); + }); +}); \ No newline at end of file diff --git a/test/node_tests.ts b/test/node_tests.ts index 258f62eee..f674f198a 100644 --- a/test/node_tests.ts +++ b/test/node_tests.ts @@ -12,6 +12,7 @@ import './node/process.spec'; import './node/Error.spec'; import './node/crypto.spec'; import './node/http.spec'; +import './node/console.spec'; // before test bluebird, must run npm install bluebird first. // then remove the comment below