javascript – 是否可以创建一个使用c库进行monetdb连接的node.js模块?

我试图连接monetdb与node.js.我有一个简单的(20行)c程序,可以使用mapi库查询moentdb.

我可以使用这些库为node.js构建一些东西(模块/插件),它使用这些库并连接到monetdb吗?

(使用odbc是一种选择,但它有其自身的缺点.)

Update1:
node-ffi非常棒.我能够很容易地创建一个fetch表程序. (例如,我添加了我的工作代码.)

所以,如果我有3个选项
1. ODBC
2. node-ffi
3.一个c程序,用于获取数据库数据并通过套接字侦听来自node.js的连接

性能方面,这是更好的实现选择,如果我没有多少时间为node.js开发插件

var ffi = require("ffi");
var libmylibrary = ffi.Library('/usr/local/lib/libmapi.so',{
    "mapi_connect":["int",["string",'int',"string","string"]],"mapi_query":['int',["int","mapi_fetch_row":["int",["int"]],"mapi_fetch_field":["string","int"]]
});


var res = libmylibrary.mapi_connect("localhost",50000,"monetdb","sql","demo");
console.log(res);
var ret=libmylibrary.mapi_query(res,"select * from table");
while(libmylibrary.mapi_fetch_row(ret)){
    console.log(libmylibrary.mapi_fetch_field(ret,0));
    console.log(libmylibrary.mapi_fetch_field(ret,1));
}

更新2:
以上代码不建议用于生产用途……它不使用node.js的异步功能,因此请将其用于婴儿步骤

最佳答案
虽然FFI可以轻松调用本机代码,但实际上您不应该将它用于您必须经常执行的操作,例如调用数据库库.来自文档:

There is non-trivial overhead associated with FFI calls. Comparing a hard-coded binding version of strtoul() to an FFI version of strtoul() shows that the native hard-coded binding is orders of magnitude faster. So don’t just use the C version of a function just because it’s faster. There’s a significant cost in FFI calls,so make them worth it.

换句话说,FFI有效,但速度很慢.如果您只是需要打几个电话,这很好,但如果您需要频繁拨打电话,这是非常糟糕的消息.

你需要做的是写一个addon.插件是C模块,为C和C库提供粘合剂. (仅仅因为你必须在C中编写插件并不意味着你不能从插件调用纯C代码!)

节点docs提供了大量可以帮助您入门的示例.如果你正在使用Windows,here’s some tips来设置VS.

如果对C库的调用是阻塞的,则需要使它们异步. libuv provides a thread pool you can do the work on.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...