简体   繁体   English

使用Jint的第三方js库

[英]Using third party js libraries with Jint

I'm working on a feature where user defined, anonymous, javascript functions retrieved from a database need to be executed server side in the context of ASP.Net application. 我正在开发一个功能,其中从数据库检索的用户定义的,匿名的,javascript函数需要在ASP.Net应用程序的上下文中执行服务器端。

I'm evaluating Jint for this purpose (Latest version from NuGet). 我正在为此目的评估Jint(NuGet的最新版本)。 I have been able to run functions that do basic operations and return values without an issue as below. 我已经能够运行执行基本操作的函数并返回值,而不会出现如下问题。

    public void Do()
    {
        var jint = new Engine();
        var add = jint.Execute(@"var f = " + GetJsFunction()).GetValue("f");
        var value = add.Invoke(5, 4);
        Console.Write("Result: " + value);
    }

    private string GetJsFunction()
    {
        return "function (x,y) {" +
               "    return x+y;" +
               "}";
    }

My question is whether Jint facilitates the execution of javascript functions which uses third party libraries like lodash? 我的问题是Jint是否有助于执行使用第三方库如lodash的javascript函数? If so, how would I go about making the Jint engine aware of it (ie third party library)? 如果是这样,我将如何让Jint引擎知道它(即第三方库)?

An example would be the execution of following function. 一个例子是执行以下功能。

  private string GetFunction()
    {
        return "function (valueJson) { " +
               "   var value = JSON.parse(valueJson);" +
               "   var poi = _.find(value,{'Name' : 'Mike'});" +
               "   return poi; " +
               "}";

    }

Thanks a lot in advance. 非常感谢提前。

I think I have figured this out. 我想我已经弄明白了。 It's no different to executing a custom function. 它与执行自定义功能没有什么不同。 You just read the third party library from a file (project resource) and invoke execute on Jint engine. 您只需从文件(项目资源)中读取第三方库并在Jint引擎上调用execute。 See below; 见下文;

 private void ImportLibrary(Engine jint, string file)
    {
        const string prefix = "JintApp.Lib."; //Project location where libraries like lodash are located

        var assembly = Assembly.GetExecutingAssembly();
        var scriptPath = prefix + file; //file is the name of the library file
        using (var stream = assembly.GetManifestResourceStream(scriptPath))
        {
            if (stream != null)
            {
                using (var sr = new StreamReader(stream))
                {
                    var source = sr.ReadToEnd();
                    jint.Execute(source);
                }
            }
        }

    }

We can call this function for all the third party libraries that needs to be added. 我们可以为需要添加的所有第三方库调用此函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM