Posts Tagged ‘ NodeJS ’

Node.JS would really benefit from LibFFI

Having recently built a simple LDAP library that required a bit of C++, I think Node would really benefit from LibFFI bindings.

LibFFI allows C functions to be called dynamically at runtime from another language. There are LibFFI bindings for Python (ctypes), Ruby (Ruby-FFI) and Java (JNA), amongst others.

If FFI bindings existing for Node, you’d be able to call native C functions without ever leaving the comfort of JavaScript. Apart from making the code a lot simpler, it also avoids the need for a build step (nothing to compile), and hide the complexities of working with threads in C++.

Here’s how it would work…

Step 1: Write some JavaScript that bindings to a native library and exports C functions as JavaScript.

var ffi = require('ffi'); //
var ldap = ffi.createLibrary('ldap', { // load libldap.so
  // exporting these functions
  // (C function name, [C arg types], C return type)
  open: ffi.exportAsync('ldap_open',
    [ffi.string, ffi.string], ffi.pointer),
  simpleBind: ffi.exportAsync('ldap_simple_bind_s',
    [ffi.pointer, ffi.string, ffi.password], ffi.int),
  unbind: ffi.exportAsync('ldap_unbind',
    [ffi.pointer], ffi.integer)
});

Yes, this looks messy, but it’s a lot less painful than doing it in C++.

Step 2: Call your native libraries through the JavaScript bindings.

ldap.open('somehost', 389,
  function(err, ldap) {
    if (!err) {
      ldap.simpleBind(ldap, someUserName, somePassword, 
        function(err, result) {
          if (!err) {
            print('Authentication result = ' + result);
            ldap.unbind(ldap);
          }
        }
      });
    }
  });

The native functions would still execute asynchronously in a background thread, so as not to tie up the main Node event loop. The usage pattern is the same as the rest of Node.

Writing the code still involves a basic knowledge of C, in that you need to read the documentation for native libraries and understand what it means. But you’d write all your code in JavaScript and avoid the hassle of the build system and platform specific linking.

There’s a lot of native libraries out there – this would open up a lot of doors.

Who’s going to take a crack at it?

Follow

Get every new post delivered to your Inbox.