20

I'm trying to access a particular native Windows API call from within a node.js application. I believe that the best way to do this is to create a native extension / addon to node that I can require in my node.js application and call from the JavaScript.

Where can I find resources on how to actually compile this sort of executable? I can find instructions on how to write it, but all the build instructions seem to be for Linux. I'm fine with compiling through g++ on mingw, I don't need to use Visual Studio. Also, where do I find the header files that I need in order to compile the extension?

Timothy Armstrong
  • 1,982
  • 2
  • 16
  • 19

2 Answers2

27

I think node-ffi will help you. It's simple and it's works.

npm install ffi
var FFI = require('ffi');

function TEXT(text){
   return new Buffer(text, 'ucs2').toString('binary');
}

var user32 = new FFI.Library('user32', {
   'MessageBoxW': [
      'int32', [ 'int32', 'string', 'string', 'int32' ]
   ]
});

var OK_or_Cancel = user32.MessageBoxW(
   0, TEXT('I am Node.JS!'), TEXT('Hello, World!'), 1
);
Willem Mulder
  • 12,974
  • 3
  • 37
  • 62
Vadim Baryshev
  • 25,689
  • 4
  • 56
  • 48
  • Cool, I've never seen this project before. – JP Richardson Mar 08 '12 at 21:51
  • 6
    Important to note: *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 **5x** 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.* In other words, this is fine for occasional calls to a native API, but if you're going to be making a lot of native calls, you're going to have to write your own addon to avoid the significant overhead of node-ffi. – josh3736 Mar 11 '12 at 21:53
  • Why do i see Chinese characters as output? – Dimitrios Filippou Dec 15 '17 at 17:44
14

This is now out of date. Today, use nan and node-gyp to write and build native modules that work across platforms.


I've gone through this pain myself. Here's a guide that helped me get it working. (PDF) Remember that since Node is now officially supported on Windows, Visual Studio is the recommended build tool for Node on Windows.

Basically:

  • Download and build the Node source code. (See PDF)
  • Create a new VC++ Win32 solution in VS, selecting DLL as the application type in the wizard that follows. Make sure ATL/MFC is unchecked.
  • Write your addon. As an example, here's one I wrote that gets Windows' current DNS settings. Specifically, the project's settings file (vcxproj) will be of interest since one of the toughest parts is getting all the library references/include paths set up. You might want to borrow my config and replace D:\node\ with the location of your Node repo.
josh3736
  • 139,160
  • 33
  • 216
  • 263