Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically loading a javascript file from a non-installed node package

It is currently an idea to build a command line tool which makes my work easier. The command line tool is installed globally with npm install -g name_of_ci.
Another module which is e.g. on my second harddisk D:/ is of course not installed.
Now I want to execute name_of_ci in this folder. Then I read the folder structure and search for special javascript files.
These must then be imported into name_of_ci dynamically.
Of course the dependencies have to be resolved as well.
The folder node_modules is present because for the condition of my tool is that all dependencies are installed.
If I now use import() for this task it is not possible. There I get only an error message that it does not find the module: Cannot find module ‘./dist/test/Test.js’.
But of course the file exists in this path.
What are the possibilities to dynamically load a javascript file with its dependencies?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import() is the correct tool, you’re just not providing the correct path. You have to provide a path that’s relative to the script doing the import(). It sounds like that’s your name_of_ci tool, which is installed globally, so ./dist/test/Test.js will not be a path to the file from that tool’s script. That looks like a path relative to the current directory instead.

You may need to use an absolute path, perhaps retrieved by converting the relative path to an absolute one via path.resolve:

const mod = await import(path.resolve(pathRelativeToCurrentDirectory));
// ...

That will need to be tweaked, of course, but fundamentally it should work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading