From bac9ba4f8a1ad4da956e4be47b57e8fd43ebce0f Mon Sep 17 00:00:00 2001 From: Rongjian Zhang Date: Thu, 6 May 2021 14:41:55 +0800 Subject: [PATCH] dgram: extract cluster lazy loading method to make it testable PR-URL: https://github.com/nodejs/node/pull/38563 Refs: https://coverage.nodejs.org/coverage-26e318a321a872bc/lib/dgram.js.html#L202 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Darshan Sen Reviewed-By: James M Snell Reviewed-By: Rich Trott --- lib/dgram.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/lib/dgram.js b/lib/dgram.js index d7cecc5ba9d552..21654f66712be0 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -85,7 +85,11 @@ const RECV_BUFFER = true; const SEND_BUFFER = false; // Lazily loaded -let cluster = null; +let _cluster = null; +function lazyLoadCluster() { + if (!_cluster) _cluster = require('cluster'); + return _cluster; +} const errnoException = errors.errnoException; const exceptionWithHostPort = errors.exceptionWithHostPort; @@ -200,8 +204,7 @@ function bufferSize(self, size, buffer) { // Query master process to get the server handle and utilize it. function bindServerHandle(self, options, errCb) { - if (!cluster) - cluster = require('cluster'); + const cluster = lazyLoadCluster(); const state = self[kStateSymbol]; cluster._getServer(self, options, (err, handle) => { @@ -262,8 +265,7 @@ Socket.prototype.bind = function(port_, address_ /* , callback */) { const exclusive = !!port.exclusive; const state = this[kStateSymbol]; - if (!cluster) - cluster = require('cluster'); + const cluster = lazyLoadCluster(); if (cluster.isWorker && !exclusive) { bindServerHandle(this, { @@ -325,8 +327,7 @@ Socket.prototype.bind = function(port_, address_ /* , callback */) { return; } - if (!cluster) - cluster = require('cluster'); + const cluster = lazyLoadCluster(); let flags = 0; if (state.reuseAddr)