How to call from TypeScript a JS function from other file in Node.js

I have TypeScript that is running on Node.js

TypeScript code will fetch by http several js files (lets call them ‘fileA.js’, ‘fileB.js’ and so on)

Each file will have function called ‘Foo(inputparam)’. Name of the function and number of params will be the same for all fetched JS files.

How to call this functions from TypeScript?

Notes:

  • I cannot embed these JS files to node.js in compilation time.
  • I can change the content of JS files (I am creating them, but they should be created in a separate from TS place).
  • I can change JavaScript files to TypeScript files if it will be easier to use.
  • TypeScript cannot know the names of the JS files before the fetch. Node.js will be a static application, while list of JS files will be changed during runtime

Answer

You’ll first need to attach your new js files to the html:

const script = document.createElement('script')
script.innerHTML = '...your js content...';

document.body.appendChild(script);

after that, the functions will be available in window context:

(<any>window).yourFunctionName('parameters');
// or
(<any>window)[funcName](params);

one note: this is potentially very unsafe if you do not trust the script source (!).

[EDIT] i overread the “node.js” part:

// pass your loaded script to eval:
eval('function foo(param) {console.log(param)}')

// function becomes available in global scope:
global['foo']('param')