【问题标题】:Using third party js libraries with Jint在 Jint 中使用第三方 js 库
【发布时间】:2016-07-18 08:07:00
【问题描述】:

我正在开发一项功能,其中需要在 ASP.Net 应用程序的上下文中在服务器端执行从数据库中检索的用户定义、匿名、javascript 函数。

我正在为此目的评估 Jint(来自 NuGet 的最新版本)。我已经能够运行执行基本操作并返回值的函数,而不会出现以下问题。

    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;" +
               "}";
    }

我的问题是 Jint 是否有助于执行使用第三方库(如 lodash)的 javascript 函数?如果是这样,我将如何让 Jint 引擎意识到它(即第三方库)?

一个例子是执行以下函数。

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

    }

非常感谢。

【问题讨论】:

    标签: javascript .net jint


    【解决方案1】:

    我想我已经弄清楚了。执行自定义函数没有什么不同。您只需从文件(项目资源)中读取第三方库并在 Jint 引擎上调用执行。见下文;

     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);
                    }
                }
            }
    
        }
    

    我们可以为所有需要添加的第三方库调用这个函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      相关资源
      最近更新 更多