Search code examples
javascriptc#serializationv8clearscript

How do I serialize compiled V8Script in Clearscript?


I am using ClearScript to compile some JavaScript and then I would like to serialize it to store it in SQL. But it is marked as not Serializable, what should I do?

V8ScriptEngine engine = new V8ScriptEngine();
V8Script compiled = engine.Compile("var a = 'test'");
using (MemoryStream ms = new MemoryStream())
{
    new BinaryFormatter().Serialize(ms, compiled);
    string compiledString = Convert.ToBase64String(ms.ToArray());
}

I get this error:

Additional information: Type 'Microsoft.ClearScript.V8.V8ScriptImpl' in Assembly 'ClearScriptV8-32, Version=5.4.6.0, Culture=neutral, PublicKeyToken=935d0c957da47c73' is not marked as serializable.

Solution

  • A V8 compiled script is tied to the isolate instance that created it, so it makes no sense to serialize it. You can't reuse it in a different process, nor even with another isolate in the same process. There's more information here and here.