0

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
1
  • eval is probably your best bet, but it is very dangerous and you'd lose all typing. The other option is to use child_process.spawn to execute the js script, and retrieve the output from stdout. You wont have reference passing, only string passing though. Commented Mar 4, 2021 at 16:30

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

This is not a web page. This is a server side Node.js application.
@VladislavKurkotov fixed my answer for node.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.