This is a C# .NET Core project that shows usage of ClearScript V8 and Jint engines to run JavaScript code, using also other JavaScript libraries (as Node.js @hapi/formula etc).
Code is MIT licensed as ClearScript.
Highlights:
- starting from some barebone code that mimic the functionality of require/CommonJs and his explanation I adapted it for this project (myrequire.js) to use real and virtual fs, to append the
./lib
search path and the.js
extension when missing, etc - implemented optional use of Base64 encoded zip files to store an entire folder of Js files and libraries in a single C# string. Working tests and assets provided.
- built a virtual filesystem (using simply a dictionary inside the scripting context) to intercept requests of files stored in memory
- wrote a simple JavaScript filesystem API layer that calls Node.js and C# methods to be able to read/write a file without worrying if the script is executed in memory or against a real fs, from ClearScript or Node. For security purposes the C# code doesn't allow any writing in the real filesystem above the
scriptsPath
When possible I used TypeScript, to allow debug/static typing.
Interesting files in the core library:
- JavaScript code runner
- scripting context implementing the virtual filesystem (
InMemoryFs
dictionary) and the methods called by the JavaScript custom filesystem API layerReadFile
,AppendFile
,DeleteFile
andExists
. For security purposes no writing is allowed in the real filesystem above thescriptsPath
- object to store the JavaScript scripts in memory (plain text, Base64 encoded text file or Zip file)
Interesting JavaScript files:
- main JavaScript file used to test
require
, filesystem and external libraries - custom require
- custom filesystem API layer
- flag file generated for testing purposes and sample library to test exports
- other files in the lib folder are external JavaScript libraries, adapted for execution with ES5 engines if needed
Interesting tests files:
- tests of InMemoryFiles (Zip) and JavaScript stored in a real filesystem; tested ES6 code with ClearScript and ES5 with Jint
- tests of Main.js script with both ClearScript and Node.js exe. Node.js exe path can be set in TestSettings