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 ...
随机推荐
- keynote 代码高亮
brew install highlight (同时会安装 Lua 和 Boost) highlight -K 18 -s Vampire -u 'utf-8' -O rtf test.html | ...
- 使用jemeter手工编写注册、登陆脚本 运用 fiddler (二)
接着上一篇讲 我们需要添加关联来获取我们想要的动态值 如果做过自动化测试的人都知道 不管是注册或者登陆是时候都会有一个 类似于动态码的一个东西 只有这个东西验证成功 我们才能注册 或者 登陆 那 ...
- BZOJ:4873: [Shoi2017]寿司餐厅
4873: [Shoi2017]寿司餐厅 首先很开心在膜你赛的时候做了出来. 看到数据范围,看到不能dp,看到贡献去重后计算,咦,流? 那就容易了,转最大权闭合子图,每个区间建一个点,取了就一定要取他 ...
- hdu_1045Fire Net(二分图匹配)
hdu_1045Fire Net(二分图匹配) 标签: 图论 二分图匹配 题目链接 Fire Net Time Limit: 2000/1000 MS (Java/Others) Memory Lim ...
- 在vue-cli项目中使用echarts
这个示例使用 vue-cli 脚手架搭建 安装echarts依赖 npm install echarts -S 或者使用国内的淘宝镜像: 安装 npm install -g cnpm --regist ...
- Kubernetes存储之Persistent Volumes简介
简介 管理存储和管理计算有着明显的不同.PersistentVolume子系统给用户和管理员提供了一套API,从而抽象出存储是如何提供和消耗的细节.在这里,我们介绍两种新的API资源:Persiste ...
- sizeof与strlen的不同
sizeof操作符的结果类型是size_t,它在头文件中typedef为unsigned int类型. 该类型保证能容纳实现所建立的最大对象的字节大小. sizeof是算符,strlen是函数. si ...
- oracle数据泵备份与恢复库
假如 导出库的用户名是tiger,密码是1 导入到用户名是scott,密码是1 备份库 expdp tiger/1@orcl dumpfile=expdp.dmp DIRECTORY=dpdata ...
- light oj 1184 Marriage Media
题目: You run a marriage media. You take some profiles for men and women, and your task is to arrange ...
- 【ELK_Log4net】.net Core重写一个TcpAppender
最近再搞ELK,三个工具部署完毕,想再继承上log4net.没想到.net core版Log4net竟然没有直接Tcp发送消息的appender.醉了.log4net 1.RemotingAppend ...