%PDF- %PDF-
Direktori : /proc/self/root/usr/src/node-v0.10.4/doc/api/ |
Current File : //proc/self/root/usr/src/node-v0.10.4/doc/api/addons.json |
{ "source": "doc/api/addons.markdown", "modules": [ { "textRaw": "Addons", "name": "addons", "desc": "<p>Addons are dynamically linked shared objects. They can provide glue to C and\nC++ libraries. The API (at the moment) is rather complex, involving\nknowledge of several libraries:\n\n</p>\n<ul>\n<li><p>V8 JavaScript, a C++ library. Used for interfacing with JavaScript:\ncreating objects, calling functions, etc. Documented mostly in the\n<code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node source\ntree), which is also available\n<a href=\"http://izs.me/v8-docs/main.html\">online</a>.</p>\n</li>\n<li><p><a href=\"https://github.com/joyent/libuv\">libuv</a>, C event loop library.\nAnytime one needs to wait for a file descriptor to become readable,\nwait for a timer, or wait for a signal to be received one will need\nto interface with libuv. That is, if you perform any I/O, libuv will\nneed to be used.</p>\n</li>\n<li><p>Internal Node libraries. Most importantly is the <code>node::ObjectWrap</code>\nclass which you will likely want to derive from.</p>\n</li>\n<li><p>Others. Look in <code>deps/</code> for what else is available.</p>\n</li>\n</ul>\n<p>Node statically compiles all its dependencies into the executable.\nWhen compiling your module, you don't need to worry about linking to\nany of these libraries.\n\n</p>\n<p>All of the following examples are available for\n<a href=\"https://github.com/rvagg/node-addon-examples\">download</a> and may be\nused as a starting-point for your own Addon.\n\n</p>\n", "modules": [ { "textRaw": "Hello world", "name": "hello_world", "desc": "<p>To get started let's make a small Addon which is the C++ equivalent of\nthe following JavaScript code:\n\n</p>\n<pre><code>module.exports.hello = function() { return 'world'; };</code></pre>\n<p>First we create a file <code>hello.cc</code>:\n\n</p>\n<pre><code>#include <node.h>\n#include <v8.h>\n\nusing namespace v8;\n\nHandle<Value> Method(const Arguments& args) {\n HandleScope scope;\n return scope.Close(String::New("world"));\n}\n\nvoid init(Handle<Object> exports) {\n exports->Set(String::NewSymbol("hello"),\n FunctionTemplate::New(Method)->GetFunction());\n}\n\nNODE_MODULE(hello, init)</code></pre>\n<p>Note that all Node addons must export an initialization function:\n\n</p>\n<pre><code>void Initialize (Handle<Object> exports);\nNODE_MODULE(module_name, Initialize)</code></pre>\n<p>There is no semi-colon after <code>NODE_MODULE</code> as it's not a function (see <code>node.h</code>).\n\n</p>\n<p>The <code>module_name</code> needs to match the filename of the final binary (minus the\n.node suffix).\n\n</p>\n<p>The source code needs to be built into <code>hello.node</code>, the binary Addon. To\ndo this we create a file called <code>binding.gyp</code> which describes the configuration\nto build your module in a JSON-like format. This file gets compiled by\n<a href=\"https://github.com/TooTallNate/node-gyp\">node-gyp</a>.\n\n</p>\n<pre><code>{\n "targets": [\n {\n "target_name": "hello",\n "sources": [ "hello.cc" ]\n }\n ]\n}</code></pre>\n<p>The next step is to generate the appropriate project build files for the\ncurrent platform. Use <code>node-gyp configure</code> for that.\n\n</p>\n<p>Now you will have either a <code>Makefile</code> (on Unix platforms) or a <code>vcxproj</code> file\n(on Windows) in the <code>build/</code> directory. Next invoke the <code>node-gyp build</code>\ncommand.\n\n</p>\n<p>Now you have your compiled <code>.node</code> bindings file! The compiled bindings end up\nin <code>build/Release/</code>.\n\n</p>\n<p>You can now use the binary addon in a Node project <code>hello.js</code> by pointing <code>require</code> to\nthe recently built <code>hello.node</code> module:\n\n</p>\n<pre><code>var addon = require('./build/Release/hello');\n\nconsole.log(addon.hello()); // 'world'</code></pre>\n<p>Please see patterns below for further information or\n</p>\n<p><a href=\"https://github.com/arturadib/node-qt\">https://github.com/arturadib/node-qt</a> for an example in production.\n\n\n</p>\n", "type": "module", "displayName": "Hello world" }, { "textRaw": "Addon patterns", "name": "addon_patterns", "desc": "<p>Below are some addon patterns to help you get started. Consult the online\n<a href=\"http://izs.me/v8-docs/main.html\">v8 reference</a> for help with the various v8\ncalls, and v8's <a href=\"http://code.google.com/apis/v8/embed.html\">Embedder's Guide</a>\nfor an explanation of several concepts used such as handles, scopes,\nfunction templates, etc.\n\n</p>\n<p>In order to use these examples you need to compile them using <code>node-gyp</code>.\nCreate the following <code>binding.gyp</code> file:\n\n</p>\n<pre><code>{\n "targets": [\n {\n "target_name": "addon",\n "sources": [ "addon.cc" ]\n }\n ]\n}</code></pre>\n<p>In cases where there is more than one <code>.cc</code> file, simply add the file name to the\n<code>sources</code> array, e.g.:\n\n</p>\n<pre><code>"sources": ["addon.cc", "myexample.cc"]</code></pre>\n<p>Now that you have your <code>binding.gyp</code> ready, you can configure and build the\naddon:\n\n</p>\n<pre><code>$ node-gyp configure build</code></pre>\n", "modules": [ { "textRaw": "Function arguments", "name": "function_arguments", "desc": "<p>The following pattern illustrates how to read arguments from JavaScript\nfunction calls and return a result. This is the main and only needed source\n<code>addon.cc</code>:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> Add(const Arguments& args) {\n HandleScope scope;\n\n if (args.Length() < 2) {\n ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));\n return scope.Close(Undefined());\n }\n\n if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n ThrowException(Exception::TypeError(String::New("Wrong arguments")));\n return scope.Close(Undefined());\n }\n\n Local<Number> num = Number::New(args[0]->NumberValue() +\n args[1]->NumberValue());\n return scope.Close(num);\n}\n\nvoid Init(Handle<Object> exports) {\n exports->Set(String::NewSymbol("add"),\n FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)</code></pre>\n<p>You can test it with the following JavaScript snippet:\n\n</p>\n<pre><code>var addon = require('./build/Release/addon');\n\nconsole.log( 'This should be eight:', addon.add(3,5) );</code></pre>\n", "type": "module", "displayName": "Function arguments" }, { "textRaw": "Callbacks", "name": "callbacks", "desc": "<p>You can pass JavaScript functions to a C++ function and execute them from\nthere. Here's <code>addon.cc</code>:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> RunCallback(const Arguments& args) {\n HandleScope scope;\n\n Local<Function> cb = Local<Function>::Cast(args[0]);\n const unsigned argc = 1;\n Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };\n cb->Call(Context::GetCurrent()->Global(), argc, argv);\n\n return scope.Close(Undefined());\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n module->Set(String::NewSymbol("exports"),\n FunctionTemplate::New(RunCallback)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)</code></pre>\n<p>Note that this example uses a two-argument form of <code>Init()</code> that receives\nthe full <code>module</code> object as the second argument. This allows the addon\nto completely overwrite <code>exports</code> with a single function instead of\nadding the function as a property of <code>exports</code>.\n\n</p>\n<p>To test it run the following JavaScript snippet:\n\n</p>\n<pre><code>var addon = require('./build/Release/addon');\n\naddon(function(msg){\n console.log(msg); // 'hello world'\n});</code></pre>\n", "type": "module", "displayName": "Callbacks" }, { "textRaw": "Object factory", "name": "object_factory", "desc": "<p>You can create and return new objects from within a C++ function with this\n<code>addon.cc</code> pattern, which returns an object with property <code>msg</code> that echoes\nthe string passed to <code>createObject()</code>:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n HandleScope scope;\n\n Local<Object> obj = Object::New();\n obj->Set(String::NewSymbol("msg"), args[0]->ToString());\n\n return scope.Close(obj);\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n module->Set(String::NewSymbol("exports"),\n FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)</code></pre>\n<p>To test it in JavaScript:\n\n</p>\n<pre><code>var addon = require('./build/Release/addon');\n\nvar obj1 = addon('hello');\nvar obj2 = addon('world');\nconsole.log(obj1.msg+' '+obj2.msg); // 'hello world'</code></pre>\n", "type": "module", "displayName": "Object factory" }, { "textRaw": "Function factory", "name": "function_factory", "desc": "<p>This pattern illustrates how to create and return a JavaScript function that\nwraps a C++ function:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> MyFunction(const Arguments& args) {\n HandleScope scope;\n return scope.Close(String::New("hello world"));\n}\n\nHandle<Value> CreateFunction(const Arguments& args) {\n HandleScope scope;\n\n Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);\n Local<Function> fn = tpl->GetFunction();\n fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous\n\n return scope.Close(fn);\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n module->Set(String::NewSymbol("exports"),\n FunctionTemplate::New(CreateFunction)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)</code></pre>\n<p>To test:\n\n</p>\n<pre><code>var addon = require('./build/Release/addon');\n\nvar fn = addon();\nconsole.log(fn()); // 'hello world'</code></pre>\n", "type": "module", "displayName": "Function factory" }, { "textRaw": "Wrapping C++ objects", "name": "wrapping_c++_objects", "desc": "<p>Here we will create a wrapper for a C++ object/class <code>MyObject</code> that can be\ninstantiated in JavaScript through the <code>new</code> operator. First prepare the main\nmodule <code>addon.cc</code>:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nvoid InitAll(Handle<Object> exports) {\n MyObject::Init(exports);\n}\n\nNODE_MODULE(addon, InitAll)</code></pre>\n<p>Then in <code>myobject.h</code> make your wrapper inherit from <code>node::ObjectWrap</code>:\n\n</p>\n<pre><code>#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n static void Init(v8::Handle<v8::Object> exports);\n\n private:\n MyObject();\n ~MyObject();\n\n static v8::Handle<v8::Value> New(const v8::Arguments& args);\n static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n double counter_;\n};\n\n#endif</code></pre>\n<p>And in <code>myobject.cc</code> implement the various methods that you want to expose.\nHere we expose the method <code>plusOne</code> by adding it to the constructor's\nprototype:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nvoid MyObject::Init(Handle<Object> exports) {\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n tpl->SetClassName(String::NewSymbol("MyObject"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n // Prototype\n tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n FunctionTemplate::New(PlusOne)->GetFunction());\n\n Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());\n exports->Set(String::NewSymbol("MyObject"), constructor);\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj = new MyObject();\n obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n obj->Wrap(args.This());\n\n return args.This();\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n obj->counter_ += 1;\n\n return scope.Close(Number::New(obj->counter_));\n}</code></pre>\n<p>Test it with:\n\n</p>\n<pre><code>var addon = require('./build/Release/addon');\n\nvar obj = new addon.MyObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13</code></pre>\n", "type": "module", "displayName": "Wrapping C++ objects" }, { "textRaw": "Factory of wrapped objects", "name": "factory_of_wrapped_objects", "desc": "<p>This is useful when you want to be able to create native objects without\nexplicitly instantiating them with the <code>new</code> operator in JavaScript, e.g.\n\n</p>\n<pre><code>var obj = addon.createObject();\n// instead of:\n// var obj = new addon.Object();</code></pre>\n<p>Let's register our <code>createObject</code> method in <code>addon.cc</code>:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n HandleScope scope;\n return scope.Close(MyObject::NewInstance(args));\n}\n\nvoid InitAll(Handle<Object> exports, Handle<Object> module) {\n MyObject::Init();\n\n module->Set(String::NewSymbol("exports"),\n FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)</code></pre>\n<p>In <code>myobject.h</code> we now introduce the static method <code>NewInstance</code> that takes\ncare of instantiating the object (i.e. it does the job of <code>new</code> in JavaScript):\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n static void Init();\n static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n\n private:\n MyObject();\n ~MyObject();\n\n static v8::Persistent<v8::Function> constructor;\n static v8::Handle<v8::Value> New(const v8::Arguments& args);\n static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n double counter_;\n};\n\n#endif</code></pre>\n<p>The implementation is similar to the above in <code>myobject.cc</code>:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nPersistent<Function> MyObject::constructor;\n\nvoid MyObject::Init() {\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n tpl->SetClassName(String::NewSymbol("MyObject"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n // Prototype\n tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n FunctionTemplate::New(PlusOne)->GetFunction());\n\n constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj = new MyObject();\n obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n obj->Wrap(args.This());\n\n return args.This();\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n HandleScope scope;\n\n const unsigned argc = 1;\n Handle<Value> argv[argc] = { args[0] };\n Local<Object> instance = constructor->NewInstance(argc, argv);\n\n return scope.Close(instance);\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n obj->counter_ += 1;\n\n return scope.Close(Number::New(obj->counter_));\n}</code></pre>\n<p>Test it with:\n\n</p>\n<pre><code>var createObject = require('./build/Release/addon');\n\nvar obj = createObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13\n\nvar obj2 = createObject(20);\nconsole.log( obj2.plusOne() ); // 21\nconsole.log( obj2.plusOne() ); // 22\nconsole.log( obj2.plusOne() ); // 23</code></pre>\n", "type": "module", "displayName": "Factory of wrapped objects" }, { "textRaw": "Passing wrapped objects around", "name": "passing_wrapped_objects_around", "desc": "<p>In addition to wrapping and returning C++ objects, you can pass them around\nby unwrapping them with Node's <code>node::ObjectWrap::Unwrap</code> helper function.\nIn the following <code>addon.cc</code> we introduce a function <code>add()</code> that can take on two\n<code>MyObject</code> objects:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n HandleScope scope;\n return scope.Close(MyObject::NewInstance(args));\n}\n\nHandle<Value> Add(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n args[0]->ToObject());\n MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n args[1]->ToObject());\n\n double sum = obj1->Val() + obj2->Val();\n return scope.Close(Number::New(sum));\n}\n\nvoid InitAll(Handle<Object> exports) {\n MyObject::Init();\n\n exports->Set(String::NewSymbol("createObject"),\n FunctionTemplate::New(CreateObject)->GetFunction());\n\n exports->Set(String::NewSymbol("add"),\n FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)</code></pre>\n<p>To make things interesting we introduce a public method in <code>myobject.h</code> so we\ncan probe private values after unwrapping the object:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n static void Init();\n static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n double Val() const { return val_; }\n\n private:\n MyObject();\n ~MyObject();\n\n static v8::Persistent<v8::Function> constructor;\n static v8::Handle<v8::Value> New(const v8::Arguments& args);\n double val_;\n};\n\n#endif</code></pre>\n<p>The implementation of <code>myobject.cc</code> is similar as before:\n\n</p>\n<pre><code>#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nPersistent<Function> MyObject::constructor;\n\nvoid MyObject::Init() {\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n tpl->SetClassName(String::NewSymbol("MyObject"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj = new MyObject();\n obj->val_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n obj->Wrap(args.This());\n\n return args.This();\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n HandleScope scope;\n\n const unsigned argc = 1;\n Handle<Value> argv[argc] = { args[0] };\n Local<Object> instance = constructor->NewInstance(argc, argv);\n\n return scope.Close(instance);\n}</code></pre>\n<p>Test it with:\n\n</p>\n<pre><code>var addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject(10);\nvar obj2 = addon.createObject(20);\nvar result = addon.add(obj1, obj2);\n\nconsole.log(result); // 30</code></pre>\n", "type": "module", "displayName": "Passing wrapped objects around" } ], "type": "module", "displayName": "Addon patterns" } ], "type": "module", "displayName": "Addons" } ] }