1

The content of the .js file is different depending on the settings on the server and the variables provided by the client(s).

I have managed to send a dynamically generated string as a file using Express' res.type(".js") and res.send(file_as_string). I create this string by appending a stringified object behind "var name_of_an_object = " using JSON.stringify().

This works in most cases, but not for functions. Functions, whether within an object or not, magically morph into {} (empty objects). I just need a way to make the functions into strings that are immediately readable by the client when it has loaded the .js file.

Since I get a feeling there has to be a more robust way of doing this, I would love to know about it. If there isn't, I would like to know as well. Andy ideas?

I thank you in advance.

  • I would rethink the design if you have to send dynamically defined functions to the client. Rather, just have the defined functions available and use data to run them or not. If you must use function, just don't use `JSON.stringify` -- JSON is a text format for passing data, not functionality, and so is a poor fit for this purpose. You should be able to call `.toString()` on a function to get its source code, as long as it's not a native function. – Heretic Monkey May 12 '20 at 15:08
  • Does this answer your question? [How can I serialize a function in JavaScript?](https://stackoverflow.com/questions/7395686/how-can-i-serialize-a-function-in-javascript) – Heretic Monkey May 12 '20 at 15:10
  • This looks promising. I am going to have a look at it and see if it's the solution which might take a while, but I'll come back here if it is. I do think I have a valid reason for this architecture. Thank you for the help. – Global Rationality May 12 '20 at 15:22

0 Answers0