Node.js调用C#代码

时间:2023-03-08 23:30:37
Node.js调用C#代码

在Node.js的项目中假如我们想去调用已经用C#写的dll库该怎么办呢?在这种情况下Edge.js是一个不错的选择,Edge.js是一款在GitHub上开源的技术,它允许Node.js和.NET core在同一个进程内相互调用,并且支持Windows,MacOS和Linux。本地可以通过npm直接安装Edge.js,地址:https://www.npmjs.com/package/edge#windows,上面有关于它的详细介绍,里面有好多的使用情况,下文主要简单介绍其中的一种使用方法来让Node.js调用C#的dll库。

1. 安装Edge.js

npm install edge

2. Edge.js使用方法

var clrMethod = edge.func({
assemblyFile: '', //程序集dll的名称
typeName: '', //类名,如果不指定,默认会找’Startup‘ 类
methodName: '' //方法名,方法必须是 Func<object,Task<object>> 且async ,如果不指定,默认会找'Invoke'方法});

3. 编写C#(NodeTest.dll)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace NodeTest
{
public class Startup
{
public async Task<object> Invoke(string parameter)
{
var _strResult = "the input is illegal";
if (!string.IsNullOrEmpty(parameter) && parameter.Contains(","))
{
var a = ;
var b = ;
if (int.TryParse(parameter.Split(',')[], out a) && int.TryParse(parameter.Split(',')[], out b))
{
_strResult = (a + b).ToString();
}
}
return _strResult;
}
}
}

4. Node.js调用dll

首先我们先编写dotnetFunction.js文件,这个文件中我们用于加载dll

const edge = require('edge')
const path = require('path')
const fs = require('fs') var dllPath = path.join(__dirname, 'dotnetclass/NodeTest/NodeTest/bin/Debug/NodeTest.dll') var dotnetFunction = null if (fs.existsSync(dllPath)) {
// 1. use defalut mode
dotnetFunction = edge.func(dllPath)
}
else {
console.log('dll path does not exist')
} exports.add = function (parameter) {
if (dotnetFunction !== null) {
return dotnetFunction(parameter, true)
} else {
return 'dotnetFunction is null'
}
}

下面我们在nodeDotNetTest.js中来使用dotnetFunction.js中的方法

const dotnet = require('./dotnetFunction.js')

var stringAdd = '1,6'
var result = dotnet.add(stringAdd)
console.log('result : ', result)

在命令行输入

node nodeDotNetTest.js

得到结果

result : 7

以上就是Node.js使用Edge.js调用C# dll的一个简单例子了。但是在平时的使用中遇到的情况往往复杂的多,比如C#代码往往注册了一些事件,这些事件被触发了以后需要通知Node.js做一些逻辑处理,这就涉及到C#调用Node.js了,在Edge.js中有C#调用js代码的功能,但是是在C#代码中嵌入js代码,并没有看到如何去调用Node中的指定方法,所以我觉得不合适,也许是我没有看到,如果有小伙伴发现请告诉我纠正。那我采用的方法就是在C#代码中新建一个队列,事件被触发了后就向这个队列中加消息,在Node.js中我们设置一个定时器不断的去从这个队列中拿数据,根据拿到的数据进行分析再进行逻辑处理,下面就是这种方法的小例子,在这里调用C# dll时我会指定对应的程序集名称、类名以及方法名。

5. 编写C#代码,Message类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace NodeTest
{
public class Message
{
static Queue<string> _queue = new Queue<string>(); public async Task<object> Init(string parameter)
{
if (_queue != default(Queue<string>))
{
for (int i = ; i < ; i++)
{
_queue.Enqueue(i.ToString());
}
return "success";
}
else
{
return "fail";
}
} public async Task<object> Get(string parameter)
{
if (_queue.Count() > )
{
return _queue.Dequeue();
}
else
{
return string.Empty;
}
}
}
}

6. 编写dotnetFunction.js

const edge = require('edge')
const path = require('path')
const fs = require('fs') var dllPath = path.join(__dirname, 'dotnetclass/NodeTest/NodeTest/bin/Debug/NodeTest.dll') var dotnetFunction = null var dotnetInitFunction = null if (fs.existsSync(dllPath)) { dotnetInitFunction = edge.func({
assemblyFile: dllPath,
typeName: 'NodeTest.Message',
methodName: 'Init'
}) dotnetFunction = edge.func({
assemblyFile: dllPath,
typeName: 'NodeTest.Message',
methodName: 'Get'
})
}
else {
console.log('dll path does not exist')
} exports.init = function () {
if (dotnetInitFunction !== null) {
return dotnetInitFunction("", true)
} else {
return 'dotnetInitFunction is null'
}
} exports.getmessage = function () {
if (dotnetFunction !== null) {
return dotnetFunction("", true)
} else {
return 'dotnetFunctionis null'
}
}

7. 编写nodeDotNetTest.js

const dotnet = require('./dotnetFunction.js')

var initresult = dotnet.init()
console.log('init result : ', initresult) var getmessage = function () {
var message = dotnet.getmessage()
if (message != undefined && message !== null && message !== '') {
console.log('message : ', message)
}
} setInterval(getmessage, 100)

8. 命令行输入

node nodeDotNetTest.js

得到结果

init result :  success
message : 0
message : 1
message : 2
message : 3
message : 4
message : 5
message : 6
message : 7
message : 8
message : 9

可以看到,完全可以从队列中取到消息,只要能拿到消息,我们的在Node.js中就能做对应的处理。以上就是关于Edge.js的一些使用方法,希望能够帮到大家!