funcster

Function serialization and deserialization

npm install funcster
14 downloads in the last day
55 downloads in the last week
91 downloads in the last month

funcster

This library contains utilities for serializing and deserializing functions. It provides recursive traversal to discover both serialized and unserialized functions nested within objects and arrays. This is particularly useful for embedding functions into JSON objects.

Installation

npm install funcster

Function reference

serialize(function, [marker])

serialize(function() { return "Hello world!" });
// -> { __js_function: 'function() { return "Hello world!" }' }

deepSerialize(root, [marker])

lib = {
  moduleA: {
    functions: {
      helloWorld: function() { return "Hello world!" }
    }
  },
  moduleB: {
    functions: {
      goodbyeWorld: function() { return "Goodbye world!" }
    }
  },
};

funcster.deepSerialize(lib);

// -> {
//      moduleA: {
//        functions: {
//          helloWorld: { __js_function: 'function() { return "Hello world!" }' }
//        }
//      },
//      moduleB: {
//        functions: {
//          goodbyeWorld: { __js_function: 'function() { return "Goodbye world!" }' }
//        }
//      },
//    }

deepDeserialize(root, [marker, [moduleOpts]])

serializedLib = {
  moduleA: {
    functions: {
      helloWorld: { __js_function: 'function() { return "Hello world!" }' }
    }
  },
  moduleB: {
    functions: {
      goodbyeWorld: { __js_function: 'function() { return "Goodbye world!" }' }
    }
  },
};

deserializedLib = funcster.deepDeserialize(serializedLib);
deserializedLib.moduleA.functions.helloWorld(); // -> Hello world!
deserializedLib.moduleB.functions.goodbyeWorld(); // -> Hello world!

Available options:

globals (object)

This option injects objects from the host context into the function evaluation context. The key is the name of the object inside the function evaluation context, and the value is the object in the host context.

deserializedLib = funcster.deepDeserialize(serializedLib, {
  globals: { foo: true }
});

requires (object)

This option injects require-able modules into the function evaluation context. These modules will be re-required in the host context, generating distinct module objects to those that might already exist. This is a safer method of granting serialized functions access to common libraries.

deserializedLib = funcster.deepDeserialize(serializedLib, {
  requires: { _: 'underscore' }
});
npm loves you