preveen-stack / nodejs

0 stars 0 forks source link

dynamic loading of modules #9

Open preveen-stack opened 2 months ago

preveen-stack commented 2 months ago

sh-3.2$ cat dynamic_import.js // dynamicImportExample.js

// Using dynamic import to load the math module console.log("dynamically importing ./math.mjs"); import('./math.mjs') .then((mathModule) => { // Now you can use the functions from the loaded module const result1 = mathModule.add(5, 3); const result2 = mathModule.subtract(10, 4);

console.log('Addition result: 5, 3 -> ', result1);
console.log('Subtraction result: 10, 4 -> ', result2);

}) .catch((error) => { console.error('Dynamic import error:', error); });

sh-3.2$ node dynamic_import.js dynamically importing ./math.mjs Addition result: 5, 3 -> 8 Subtraction result: 10, 4 -> 6