How do I load a JavaScript file with Jint in C#?

2019-01-15 02:15发布

I want to load a JavaScript file using Jint, but I can't seem to figure it out. The documentation said I could do something like engine.run(file1), but it doesn't appear to be loading any files. Do I need to do something special with the file name?

Here's my JavaScript file:

// test.js
status = "test";

Here's my C#

JintEngine js = new JintEngine();
js.Run("test.js");
object result = js.Run("return status;");
Console.WriteLine(result);
Console.ReadKey();

If I put in code manually in Run it works.

object result = js.Run("return 2 * 21;"); // prints 42

4条回答
Ridiculous、
2楼-- · 2019-01-15 02:59

I found a workaround by manually loading the file into text myself, instead of loading it by name as mentioned here: http://jint.codeplex.com/discussions/265939

        StreamReader streamReader = new StreamReader("test.js");
        string script = streamReader.ReadToEnd();
        streamReader.Close();

        JintEngine js = new JintEngine();

        js.Run(script);
        object result = js.Run("return status;");
        Console.WriteLine(result);
        Console.ReadKey();
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-15 03:01

Personally I use:

js.Run(new StreamReader("test.js"));

Compact and just works.

查看更多
太酷不给撩
4楼-- · 2019-01-15 03:06

Even more succinctly (using your code)

JintEngine js = new JintEngine();
string jstr = System.IO.File.ReadAllText(test.js);
js.Run(jstr);
object result = js.Run("return status;");
Console.WriteLine(result);
Console.ReadKey();
查看更多
做自己的国王
5楼-- · 2019-01-15 03:16

Try

 using(FileStream fs = new FileStream("test.js", FileMode.Open))
 {
    JintEngine js = JintEngine.Load(fs);
    object result = js.Run("return status;");
    Console.WriteLine(result);
 }
查看更多
登录 后发表回答