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的一些使用方法,希望能够帮到大家!
Node.js调用C#代码的更多相关文章
- 使用Node.js调用阿里云短信的发送以及接收
为了使用Node.js调用阿里云短信服务,我自己写了个npm包, 目前实现了: 使用Node.js调用阿里云短信服务,发送短信: 使用Node.js调用阿里云短信服务以及MNS服务,接收用户上行短信 ...
- windows下node.js调用bat
node.js调用bat需要用到Child Processes模块 因为bat是文件,所以需要使用execFile方法 如果指定了cwd,它会切换bat执行的目录,类似cd的功能,如果未指定默认为 ...
- [转]Asp.Net调用前台js调用后台代码分享
1.C#前台js调用后台代码 前台js <script type="text/javascript" language="javascript"> ...
- Node.js调用百度地图Web服务API的Geocoding接口进行点位反地理信息编码
(从我的新浪博客上搬来的,做了一些修改.) 最近迷上了node.js以及JavaScript.现在接到一个活,要解析一个出租车点位数据的地理信息.于是就想到使用Node.js调用百度地图API进行解析 ...
- asp.net调用前台js调用后台代码分享
asp.net调用前台js调用后台代码分享 C#前台js调用后台代码前台js<script type="text/javascript" language="jav ...
- 记录一次用宝塔部署微信小程序Node.js后端接口代码的详细过程
一直忙着写毕设,上一次写博客还是元旦,大半年过去了.... 后面会不断分享各种新项目的源码与技术.欢迎关注一起学习哈! 记录一次部署微信小程序Node.js后端接口代码的详细过程,使用宝塔来部署. 我 ...
- 解决Node.js调用fs.renameSync报错的问题(Error: EXDEV, cross-device link not permitted)
2014-08-23 今天开始学习Node.js,在写一个文件上传的功能时候,调用fs.renameSync方法错误 出错代码所在如下: function upload(response,reques ...
- $ npm install opencv ? 你试试?! 在windows环境下,使用node.js调用opencv攻略
博主之前写过一篇文章<html5与EmguCV前后端实现——人脸识别篇>,叙述的是opencv和C#的故事.最近在公司服务器上更新了一套nodejs环境,早就听闻npm上有opencv模块 ...
- ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例)
此解决方案原理: 1.在ViewController.h中声明方法和成员变量,以及webView的委托: // // ViewController.h // JS_IOS_01 // // Cr ...
随机推荐
- 从头开始基于Maven搭建SpringMVC+Mybatis项目(2)
接上文内容,本节介绍Maven的聚合和继承. 从头阅读传送门 互联网时代,软件正在变得越来越复杂,开发人员通常会对软件划分模块,以获得清晰的设计.良好的分工及更高的可重用性.Maven的聚合特性能把多 ...
- JavaScript判断对象是否含有某个属性
两种方式,但稍有区别 1,in 运算符 1 2 3 var obj = {name:'jack'}; alert('name' in obj); // --> true alert('toStr ...
- “玲珑杯”ACM比赛 Round #13 题解&源码
A 题目链接:http://www.ifrog.cc/acm/problem/1111 分析:容易发现本题就是排序不等式, 将A数组与B数组分别排序之后, 答案即N∑i=1Ai×Bi 此题有坑,反正据 ...
- Codeforces 833D Red-black Cobweb【树分治】
D. Red-black Cobweb time limit per test:6 seconds memory limit per test:256 megabytes input:standard ...
- Is It A Tree?(并查集)(dfs也可以解决)
Is It A Tree? Time Limit:1000MS Memory Limit:10000KB 64bit IO Format:%I64d & %I64u Submi ...
- SSH防爆破脚本
github地址:https://github.com/demonxian3/LittleScript/blob/master/SSHprotecter.sh 使用方法: 1.给足脚本权限,chmod ...
- chrome浏览器使用技巧
在学校的时候一直在用firefox火狐浏览器,听一个学长说使用chrome浏览器在面试的时候有加分,而且还跟我说了一些chrome浏览器的使用技巧,最后从火狐浏览器转到谷歌浏览器,就一直在使用谷歌浏览 ...
- 根据父节点parentid查询节点信息
---恢复内容开始--- SELECT * from tb3 where pid in(select id from tb1 where parentId ='ce2a98d7a04c4bf6a38 ...
- DOM解析原理示意
DOM解析原理示意
- java序列化反序列化深入探究
When---什么时候需要序列化和反序列化: 简单的写一个hello world程序,用不到序列化和反序列化.写一个排序算法也用不到序列化和反序列化.但是当你想要将一个对象进行持久化写入文件,或者你想 ...