6

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
Andrew Russell
  • 26,924
  • 7
  • 58
  • 104
Daniel X Moore
  • 14,637
  • 17
  • 80
  • 92

5 Answers5

4

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();
Daniel X Moore
  • 14,637
  • 17
  • 80
  • 92
2

Personally I use:

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

Compact and just works.

RandomGuy
  • 648
  • 6
  • 21
0

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();
SAL
  • 1,218
  • 1
  • 14
  • 34
0

The syntax has changed. When using Jint 3.0.0-beta use the Execute method instead of Run.

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

Engine js = new Engine();

js.Execute(script);
object result = js.Execute("return status;");
Console.WriteLine(result);
Console.ReadKey();
RainMoose
  • 61
  • 4
0

Try

 using(FileStream fs = new FileStream("test.js", FileMode.Open))
 {
    JintEngine js = JintEngine.Load(fs);
    object result = js.Run("return status;");
    Console.WriteLine(result);
 }
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • System.Runtime.Serialization.SerializationException was unhandled Message=The input stream is not a valid binary format. The starting contents (in bytes) are: 73-74-61-74-75-73-20-3D-20-22-74-65-73-74-22-3B-0D ... Source=mscorlib StackTrace: at System.Runtime.Serialization.Formatters.Binary.SerializationHeaderRecord.Read(__BinaryParser input) at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadSerializationHeaderRecord() – Daniel X Moore Aug 14 '11 at 19:53
  • @Daniel, I'm not sure but the point is `Run()` expects a script to execute and not a file name; Try reading the contents of the file manually into a string (`File.ReadAllText()`) and then try calling `Run()` with the string. – Bala R Aug 14 '11 at 19:58