From e0f35dc50d32f6106063fd6d7517e12faa7f91cf Mon Sep 17 00:00:00 2001 From: madflowe Date: Thu, 6 May 2021 18:01:59 +0200 Subject: [PATCH] allow preloading modules without referencing by filename --- start.js | 6 +++--- test/start.test.js | 18 ++++++++++++++++++ util.js | 17 ++++++++++------- 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/start.js b/start.js index 13a05b77..5ffe7264 100755 --- a/start.js +++ b/start.js @@ -14,7 +14,7 @@ const watch = require('./lib/watch') const parseArgs = require('./args') const { exit, - requirePath, + requireModule, requireFastifyForModule, requireServerPluginFromPath, showHelpForCommand @@ -72,7 +72,7 @@ async function runFastify (args) { /* This check ensures we ignore `-r ""`, trailing `-r`, or * other silly things the user might (inadvertently) be doing. */ - requirePath(module) + requireModule(module) } }) } catch (e) { @@ -94,7 +94,7 @@ async function runFastify (args) { let logger if (opts.loggingModule) { try { - logger = requirePath(opts.loggingModule) + logger = requireModule(opts.loggingModule) } catch (e) { module.exports.stop(e) } diff --git a/test/start.test.js b/test/start.test.js index 6fe7b31e..74777999 100644 --- a/test/start.test.js +++ b/test/start.test.js @@ -821,6 +821,24 @@ test('should support custom logger configuration', async t => { t.pass('server closed') }) +test('preloading a built-in module works', async t => { + t.plan(1) + + const argv = ['-r', 'path', './examples/plugin.js'] + const fastify = await start.start(argv) + await fastify.close() + t.pass('server closed') +}) + +test('preloading a module in node_modules works', async t => { + t.plan(1) + + const argv = ['-r', 'tap', './examples/plugin.js'] + const fastify = await start.start(argv) + await fastify.close() + t.pass('server closed') +}) + test('should throw on logger configuration module not found', async t => { t.plan(2) diff --git a/util.js b/util.js index 885d00ca..28d024d2 100644 --- a/util.js +++ b/util.js @@ -19,12 +19,15 @@ function exit (message) { process.exit() } -function requirePath (filePath) { - const moduleFilePath = path.resolve(filePath) - const moduleFileExtension = path.extname(filePath) - const modulePath = moduleFilePath.split(moduleFileExtension)[0] - const module = require(modulePath) - return module +function requireModule (moduleName) { + if (fs.existsSync(moduleName)) { + const moduleFilePath = path.resolve(moduleName) + const moduleFileExtension = path.extname(moduleName) + const modulePath = moduleFilePath.split(moduleFileExtension)[0] + return require(modulePath) + } else { + return require(moduleName) + } } function requireFastifyForModule (modulePath) { @@ -95,4 +98,4 @@ function showHelpForCommand (commandName) { } } -module.exports = { exit, requirePath, requireFastifyForModule, showHelpForCommand, requireServerPluginFromPath } +module.exports = { exit, requireModule, requireFastifyForModule, showHelpForCommand, requireServerPluginFromPath }