簡體   English   中英

使用Jint的第三方js庫

[英]Using third party js libraries with Jint

我正在開發一個功能,其中從數據庫檢索的用戶定義的,匿名的,javascript函數需要在ASP.Net應用程序的上下文中執行服務器端。

我正在為此目的評估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; " +
               "}";

    }

非常感謝提前。

我想我已經弄明白了。 它與執行自定義功能沒有什么不同。 您只需從文件(項目資源)中讀取第三方庫並在Jint引擎上調用execute。 見下文;

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

    }

我們可以為需要添加的所有第三方庫調用此函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM