Node.js Manual & Documentation


Table Of Contents


Addons 扩展插件

Addons are dynamically linked shared objects. They can provide glue to C and C++ libraries. The API (at the moment) is rather complex, involving knowledge of several libraries:

扩展插件(Addons)是动态链接的共享对象,这些对象提供了使用C/C++类库的能力。由于涉及了多个类库导致了这类API目前比较繁杂,主要包括下述几个主要类库:

Node statically compiles all its dependencies into the executable. When compiling your module, you don't need to worry about linking to any of these libraries.

Node已将所有依赖关系静态地编译成可执行文件,因此我们在编译自己的组件时不需要担心和这些类库的链接问题。

To get started let's make a small Addon which does the following except in C++:

让我们着手编写一个Addon的小例子,来达到如下模块同样的效果:

exports.hello = 'world';

To get started we create a file hello.cc:

首先我们需要创建一个hello.cc文件:

#include <v8.h>

using namespace v8;

extern "C" void
init (Handle<Object> target)
{
  HandleScope scope;
  target->Set(String::New("hello"), String::New("world"));
}

This source code needs to be built into hello.node, the binary Addon. To do this we create a file called wscript which is python code and looks like this:

这些源码会编译成一个二进制的Addon文件hello.node。为此我们用python编写如下的名为wscript的文件:

srcdir = '.'
blddir = 'build'
VERSION = '0.0.1'

def set_options(opt):
  opt.tool_options('compiler_cxx')

def configure(conf):
  conf.check_tool('compiler_cxx')
  conf.check_tool('node_addon')

def build(bld):
  obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
  obj.target = 'hello'
  obj.source = 'hello.cc'

Running node-waf configure build will create a file build/default/hello.node which is our Addon.

运行node-waf configure build,我们就创建了一个Addon实例build/default/hello.node

node-waf is just WAF, the python-based build system. node-waf is provided for the ease of users.

node-waf就是WAF,,一种基于python的编译系统,而node-waf更加易于使用。

All Node addons must export a function called init with this signature:

另外,在Node中任何的Addon必须使用输出一个如下声明的init函数:

extern 'C' void init (Handle<Object> target)

For the moment, that is all the documentation on addons. Please see http://github.com/ry/node_postgres for a real example.

目前关于addon的所有文档就是这些。另外,在http://github.com/ry/node_postgres中还提供了一个Addon的实例。