您可以使用Jering.Javascript.NodeJS从 c# 调用 javascript 函数, Jering.Javascript.NodeJS是我组织的一个开源库:
string javascriptModule = @"
module.exports = (callback, x, y) => { // Module must export a function that takes a callback as its first parameter
var result = x + y; // Your javascript logic
callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";
// Invoke javascript
int result = await StaticNodeJSService.InvokeFromStringAsync<int>(javascriptModule, args: new object[] { 3, 5 });
// result == 8
Assert.Equal(8, result);
该库也支持直接从 .js 文件调用。假设您的文件C:/My/Directory/exampleModule.js
包含:
module.exports = (callback, message) => callback(null, message);
您可以调用导出的函数:
string result = await StaticNodeJSService.InvokeFromFileAsync<string>("C:/My/Directory/exampleModule.js", args: new[] { "test" });
// result == "test"
Assert.Equal("test", result);