From 71a272f0a64c61cbbd3e180f39ad45a0568d8d9c Mon Sep 17 00:00:00 2001 From: Nick O'Leary Date: Thu, 9 Jun 2022 22:11:48 -0500 Subject: [PATCH] Fix ESM module loading in Function node Fixes #3627 --- .../@node-red/registry/lib/externalModules.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/node_modules/@node-red/registry/lib/externalModules.js b/packages/node_modules/@node-red/registry/lib/externalModules.js index ca1e4bfd8..b61392d9b 100644 --- a/packages/node_modules/@node-red/registry/lib/externalModules.js +++ b/packages/node_modules/@node-red/registry/lib/externalModules.js @@ -11,6 +11,7 @@ const exec = require("@node-red/util").exec; const log = require("@node-red/util").log; const hooks = require("@node-red/util").hooks; const url = require("url"); +const { createRequire } = require("module"); const BUILTIN_MODULES = require('module').builtinModules; @@ -139,10 +140,15 @@ function importModule(module) { } const externalModuleDir = getInstallDir(); const moduleDir = path.join(externalModuleDir,"node_modules",module); + // To handle both CJS and ESM we need to resolve the module to the + // specific file that is loaded when the module is required/imported + // As this won't be on the natural module search path, we use createRequire + // to access the module + const modulePath = createRequire(moduleDir).resolve(module) // Import needs the full path to the module's main .js file // It also needs to be a file:// url for Windows - const moduleFile = url.pathToFileURL(require.resolve(moduleDir)); - return import(moduleFile); + const moduleUrl = url.pathToFileURL(modulePath); + return import(moduleUrl); } function parseModuleName(module) {