Building node.js Windows C/C++ Addons

From wiki.gpii
Jump to: navigation, search

This page explains how to build node.js C/C++ addons that use the Windows API. We will not be using node-gyp, but Microsoft Visual C++ instead.

A Simple Addon

Here is the source code for a simple addon that uses Windows API. Our goal is to build it.

#include "stdafx.h"
#pragma comment(lib, "node")
#include <node.h>
#include <v8.h>
#include <Windows.h>

using namespace v8;

Handle<Value> sayHi(const Arguments& args) {
    HandleScope scope;
    MessageBoxW(NULL, TEXT("You have been greeted!"), TEXT("Attention!"), MB_OK);
    return scope.Close(String::New("Bye, bye! Come again!"));
}

extern "C" void NODE_EXTERN init (Handle<Object> target) {
    HandleScope scope;
    target->Set(String::NewSymbol("sayHi"), FunctionTemplate::New(sayHi)->GetFunction());
}

Building the Addon

This section covers the necessary steps to build your native C/C++ Windows addon.

Prerequisites

Visual C++

You must download and install Visual C++ 2010 Express - download link

Python

You must download and install Python 2.x - download link

  • NB: Python 3.x wont do. Version 2.7.3 is fine.

Node.js

  1. Download node.js source code - http://nodejs.org/download/
  2. Run the vcbuild.bat file - this is a long process
    • NB: You must have installed VC++ and Python already and the Python installation path must be in the PATH environment variable
  3. When the process finishes you should have node.lib into either Debug or Release directories

Creating a VC++ Project

  1. Open Visual C++ and select File -> New -> Project -> Win32 Project
  2. In the wizard click Next, select DLL as application type and then Finish

Writing the code

  1. Paste the code above in your project's main file (the one with the same name as your project)
  2. Referencing node.lib - you must either:
    • At line 2 (#pragma comment(lib, "node")) specify the full path to your node.lib file
    • Go to Project -> Properties -> Configuration Properties -> VC++ Directories -> Include Directories -> <Edit...> and add your node.lib location
  3. Including node.h and v8.h
    • Similar to node.lib - follow the above steps
    • node.h location: .\src\node.h (assuming you are in the node source folder)
    • v8.h location: .\deps\v8\include\v8.h

Building the addon

  1. Hit F7 - you should get a .dll file in your project's Debug directory
  2. Rename it as .node
    • NB: You might want to go to Project -> Properties -> Configuration Properties -> General and set Target Extension to .node
  3. Try using the addon within node via require - when invoking the sayHi method, a message box should appear