1

We can load javascript into the browser with javascript through dynamically created <script> tags and we can load javascript in node with the require method.

The code loaded in these methods can contain fully functional objects with methods in addition to properties.

Is it possible to save javascript code into a file that can then be loaded as mentioned above?

E.g., where dump_to_file is the functionality i am looking for,

var target_object = {foo : "bar", say_foo : function(){ console.log(this.foo) }  
target_object.say_foo(); // "bar"
dump_to_file("path/to/file.js", target_object)

and later, where load_from_file is a utility defined in the first paragraph,

var target_object = load_from_file("path/to/file.js");
target_object.say_foo(); // "bar"
Ulad Kasach
  • 11,558
  • 11
  • 61
  • 87
  • That is completely impossible; what if it references live objects? (eg, a socket) – SLaks Mar 08 '18 at 21:26
  • @SLaks I am not familiar with sockets so I can not comment on that precisely. I am curious as to why Python can accomplish this however (e.g., the `pickle` library) while JS can not. I am confident that Python supports the creation of sockets as well. – Ulad Kasach Mar 08 '18 at 21:34
  • What happens if you pickle an active HTTP response? – SLaks Mar 08 '18 at 21:34
  • Are you asking about how to save a state? – NotARobot Mar 08 '18 at 21:34
  • The general problem is that there is no good way to serialize a function. – SLaks Mar 08 '18 at 21:35
  • You should use JSON. – SLaks Mar 08 '18 at 21:35
  • @BrokenRobot not only a state but an arbitrary object with methods as well. – Ulad Kasach Mar 08 '18 at 21:36
  • @SLaks JSON does not support storing methods / functions – Ulad Kasach Mar 08 '18 at 21:37
  • Yes; you shouldn't do that. That's generally a bad idea; you should separate your code & data. For example, what if you change a function? – SLaks Mar 08 '18 at 21:40
  • adding functions dynamically scares me but i guess you could store the guts in a json object and then call it using new Function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function – NotARobot Mar 08 '18 at 21:42
  • For explanatory reasons you can do `var stringCode = "console.log('test')"` and then `new Function(stringCode)`. We use this way to load dynamic code from a database and run. Check [Is there a way to create a function from a string with javascript?](https://stackoverflow.com/questions/7650071/is-there-a-way-to-create-a-function-from-a-string-with-javascript) – Stamos Mar 08 '18 at 21:46
  • @SLaks - the purpose would be to cache functional objects to use on the client side - so functions changing would be something thought through before using this "cache". ( the goal is similar to what webpack and browserify do - but with the source objects being loaded into a js context already). P.S., thanks for your feedback. – Ulad Kasach Mar 08 '18 at 22:10
  • @BrokenRobot thank you for the reference. I will keep that in mind but don't think it will solve everything i'm looking for. – Ulad Kasach Mar 08 '18 at 22:12

1 Answers1

0

I hope this is what you are looking for:

    let fs = require("fs");
    //   JSON.stringify() features with extra capabilities
    // - Wraps funcs
    // - upon execution, it expose an object, target, into the scope
    var bundle = function(obj) {
      var type = typeof obj;
      if (type === "string") return "'" + obj + "'";
      if (type === "boolean" || type === "number") return obj;
      if (type === "function") return obj.toString();
      var returnValue = [];
      for (var prop in obj) {
        returnValue.push(prop + ": " + bundle(obj[prop]));
      }
      return "{" + returnValue.join(",") + "}";
    };
    
    var target = {
      foo: "bar",
      say_foo: function() {
        console.log(this.foo);
      }
    };
    
    console.log(bundle(target));
    
    var returnValue = "var target = " + bundle(target);
    fs.writeFileSync("target.js", returnValue);

And have a look at Template Literals in javascript these ES2015 features help to generate code very efficiently and painless. Styled components which uses this feature is one of the best example of it.

suchcodemuchwow
  • 848
  • 2
  • 9
  • 27