Incorporating external JavaScript libraries in Jint

I'm currently working on a new feature that requires the execution of user-defined, anonymous JavaScript functions retrieved from a database on the server side within an ASP.Net application environment.

For this purpose, I am exploring the use of Jint (latest version from NuGet). So far, I have successfully executed functions that perform basic operations and return values without any issues, as shown 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 main query is whether Jint supports the execution of JavaScript functions that utilize third-party libraries such as lodash. If so, how can I integrate the Jint engine with these third-party libraries?

As an illustration, consider the execution of the following JavaScript function:

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

    }

Thank you in advance for your assistance.

Answer №1

After some investigation, I believe I have solved the problem at hand. It turns out that integrating a third party library is similar to executing a custom function. All you need to do is read the library from a file (which is a project resource) and then call the execute function on the Jint engine. Take a look at the code snippet below;

 private void ImportLibrary(Engine jint, string file)
    {
        const string prefix = "JintApp.Lib."; //This is the location within the project where libraries such as lodash are stored

        var assembly = Assembly.GetExecutingAssembly();
        var scriptPath = prefix + file; //file represents 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);
                }
            }
        }

    }

This function can be utilized to add any third party libraries that are required.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one elevate the properties of each item's sub-structure to the root level in an array containing object items?

I am working with an array containing objects, each with a specific structure... [{ user: { /* ... more (nested) user data ... */ }, vacation: { id: 'idValue', name: 'nameValue', startDate: 'dateValue', }, }, ...

Struggling with flipping div functionality in IE9 on flipping content demo

I recently developed a flipping div using transitions and 3D transforms based on the Flipping Content Demo 1 from . While this works smoothly on most browsers, unfortunately IE 9 does not support transitions and 3D transforms. In order to address this iss ...

What is the best way to immediately update the state in a React functional component?

Having recently started learning React, I find myself struggling to understand the lifecycle of a functional component. Let's consider a scenario where I have multiple checkboxes labeled as: checkbox, a, b, c, and d, each corresponding to values a, b, ...

Utilizing custom filters to navigate through nested ng-repeats

My goal is to achieve a specific behavior by using custom filters. I am working on creating a unified search bar that will display entire group names with all failing students, as well as group names with only the matching students. If you want to see the ...

What is the best way to create a React text box that exclusively accepts numeric values or remains empty, and automatically displays the number keypad on mobile devices?

While there are numerous similar questions on StackOverflow, none of them fully address all of my requirements in a single solution. Any assistance would be greatly appreciated. The Issue at Hand Within my React application, I am in need of a text box tha ...

What is the best way to consistently and frequently invoke a REST API in Angular 8 using RxJS?

I have developed a REST API that retrieves a list of values. My goal is to immediately invoke this API to fetch values and store them in a component's member variable. Subsequently, I plan to refresh the data every five minutes. Upon conducting some ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

The list marquee in HTML, JS, and CSS is not being properly rendered on

I recently made changes to a code that showcases a marquee scrolling a basic HTML list. Check it out here: I am facing 3 issues that I am struggling to resolve: JS: I want the marquee to continuously show text re-entering from the right just after it ...

Creating a 24-hour bar chart using Flot Javascript, showcasing data points at each hour mark

I am attempting to create a 24-hour bar graph using Flot Charts, with a value corresponding to each hour. It seems that Flot utilizes epoch time for hour values. However, after running the code below, I encounter an issue where the chart does not display a ...

Can the name of the Grunt task target be utilized within attributes?

I have implemented the grunt-replace task to make some content changes in the index.html file. However, I am looking for a way to avoid repeating code unnecessarily. The code snippet below is just an example of what I am trying to accomplish: replace: { ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see an ...

Task containing an ongoing while loop

Can someone help me with my TPL C# learning? I am facing an issue where an infinite while loop inside a task terminates without any error. Is there something wrong with my code? Here's a snippet: class Work2 { public void DoWork() { L ...

JQuery UI Autocomplete - Issue with loading data object

I've been attempting to implement autocomplete with JQuery UI, but I'm encountering difficulties when passing in a label & value object. var individuals = []; var test = new Array(); var dataObject = jQuery.parseJSON(data) ...

Creating a new image by extracting a specific HTML div tag that contains an image and its layers

I currently have a div element that includes an image element along with multiple other div elements containing small text displayed above the image. I am looking to save the image along with its content to a new image file. Any suggestions or ideas are ...

What is preventing the value from changing in auth.guard?

I am encountering an issue with the variable loggined, which I modify using the logTog() method. When I call this method, a request is made to a service where the current result is passed to auth.guard. However, in the console, it displays "undefined". Can ...

The function $.getJSON() seems to be non-responsive

I've been struggling to solve this issue for quite some time now. The users.json file that I am using can be found in the "JSON" folder alongside the other files. The alert("Before") is functioning properly, but I'm facing difficulty with getting ...

How do I implement the use of "lengthMenu: [10, 25, 50]," within an if/else statement effectively?

Could someone help me with defining 2 different configuration lines for a datatable using if-else statements? I've tried writing the code but it doesn't seem to be working as expected. if(role === 1) { lengthMenu: [10, 25, 50], } else ...

Tests are not visible to jasmine-node

Currently, I am utilizing jasmine-node and running it with the following command: node.exe path/to/jasmine_node --verbose path/to/my_file.js Despite successfully invoking Jasmine-node and receiving an error for incorrect paths, it appears that no tests a ...

What advantages does incorporating "function() 'use strict'" into each individual file provide?

As I dive into revamping an older AngularJS 1.3 project, one striking observation is the consistent pattern of starting each AngularJS code file with: (function () { 'use strict'; angular.module('app').factory('Employees', ...

Finding the complete object based on its index

Hey there, I'm looking to access a specific object in my JSON data by using an index. Can anyone guide me on how to do this? Here's a snippet of my JSON data: [{ "rec": ["act1","act2","act3"], "rec2": ["act11","act23","act4"] }] I'm ai ...