nodejs / node-addon-examples Goto Github PK
View Code? Open in Web Editor NEWNode.js C++ addon examples from http://nodejs.org/docs/latest/api/addons.html
License: Other
Node.js C++ addon examples from http://nodejs.org/docs/latest/api/addons.html
License: Other
Hey guys - I've been struggling to combine example 3 with example 6. In JavaScript, I'd like the usage to be something like:
var myObj = new MyObject(function() { console.log("hello world" });
myObj.doSomething(); // invoke the callback passed in the ctor
I've tried:
Persistent<Function>
Local<Function>
from the ctor args listLocal<Function>
, e.g. New(isolate, this->myPersistent)
I'm having trouble with 4. I can't seem to figure out the correct way to rehydrate a callback from a Persistent in a way where it can actually be invoked. When trying 4, I receive what I assume is a seg fault as the node process immediately terminates. I must be doing something wrong but I can't find a snippet anywhere that demonstrates how to do this properly.
Any help would be greatly appreciated.
@rvagg @eljefedelrodeodeljefe Is this repository something that should be maintained? Or archived? Seems to be pretty dormant.
Hello,
I was trying to compile example 7 with NAN but it fails and gives the following error:
(node) v8::ObjectTemplate::Set() with non-primitive values is deprecated
(node) and will stop working in the next major release.
On node v9.4.0, node-gyp v3.6.2, [email protected], example 7_factory_wrap compiles but then coredumps.
If prototype is not set to a new one
tpl->PrototypeTemplate()->Set(Nan::New("plusOne").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(PlusOne)->GetFunction());
but only has the method added to it, as in 6_object_wrap
Nan::SetPrototypeMethod(tpl, "plusOne", PlusOne);
It works. But I assume the point was to demonstrate how the prototype can be created, so I didn't send a PR.
I am now testing for echo function,
for code
napi_value Method(napi_env env, napi_callback_info args)
{
// napi_value str;
napi_status status;
cout << "inside method!" << endl;
size_t argc = 0;
napi_value argv[1];
status = napi_get_cb_info(env, args, &argc, argv, nullptr, nullptr);
if (status != napi_ok)
{
napi_throw_error(env, NULL, "Error Get Parameters!");
return nullptr;
}
cout << "before argc!" << endl;
if (argc < 1)
{
cout << "" << endl;
return nullptr;
}
size_t strlen;
status = napi_get_value_string_utf8(env, argv[0], NULL, 0, &strlen);
if (status != napi_ok)
{
napi_throw_error(env, NULL, "Error Get String Length!");
return nullptr;
}
// status = napi_create_string_utf8(env, argv[0], NAPI_AUTO_LENGTH, res);
// if (status != napi_ok)
// {
// napi_throw_error(env, NULL, "Error Get String!");
// return nullptr;
// }
return nullptr;
}
and
status = napi_set_named_property(env, exports, "echo", fn);
and
echo('hello!')
,
I got:
inside method!
before argc!
before get string!
�"�d2
1) hello
0 passing (11ms)
1 failing
1) crypto
hello:
Error: Error Get String Length!
at Context.it (tests/1-test.js:4:24)
The hello world example works for me with node 0.12, but fails with iojs 1.4.3 on Windows 8 x64.
I removed node 0.12 and verified nodejs folder was completely removed from Program Files. I then installed iojs 1.4.3 and get the following in a shell window on asking the versions.
$ node -v
v1.4.3
$ npm -v
2.6.1
I ran npm cache clean, and deleted any old .node_gyp folders in my profile to ensure there were no remnants of node 0.12. I then updated 'nan' to the latest version by npm uninstall --save nan, npm install --save nan. There were no errors from nod_gyp, but on running npm test, I get the following error.
Error: Module did not self-register.
at Error (native)
at Module.load (module.js:339:32)
at Function.Module._load (module.js:294:12)
at Module.require (module.js:349:17)
at require (module.js:368:17)
at bindings (C:\Users\philip\Desktop\node-addon-examples\1_hello_world\nan\node_modules\bindings\bindings.s:76:44)
at Object.<anonymous> (C:\Users\philip\Desktop\node-addon-examples\1_hello_world\nan\hello.js:1:94)
at Module._compile (module.js:444:26)
at Object.Module._extensions..js (module.js:462:10)
at Module.load (module.js:339:32)
npm ERR! Test failed. See above for more details.
When this failed with "nan", I then tried the node_0.12 folder version that doesn't use the nan macros, but it shows the same behaviour.
Should the Hello World example work with iojs on WIndows x64, or have I perhas got some setting or old version of a library lurking not cleared?
thanks,
--philip
NanScope(); for example does not compile
not just select one or two.
In the comments for the async_pi_estimate starting at line 11, there is a part that states "It is not safe to access JS engine data structure..."
My use case is that I have a node-addon-api based addon that receives 2 pixel buffers and compares them for differences and then does labeling and blobbing. I will be adding more features to it that will most likely cause it to increase its time to process. My current implementation is synchronous/blocking and I am going to attempt to convert to async.
Any advice or guidance would be appreciated. Thanks.
Trying to follow the hello world example, I get stopped at Step 5:
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | darwin | x64
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
CXX(target) Release/obj.target/hello/hello.o
../hello.cc:7:26: error: no member named 'New' in 'v8::String'
NanReturnValue(String::New("world"));
~~~~~~~~^
../node_modules/nan/nan.h:401:81: note: expanded from macro 'NanReturnValue'
# define NanReturnValue(value) return args.GetReturnValue().Set(_NanEnsureLocal(value))
^
../hello.cc:11:16: warning: 'NanSymbol' is deprecated [-Wdeprecated-declarations]
exports->Set(NanSymbol("hello"), FunctionTemplate::New(Method)->GetFunction());
^
../node_modules/nan/nan.h:499:51: note: 'NanSymbol' has been explicitly marked deprecated here
NAN_DEPRECATED NAN_INLINE v8::Local<v8::String> NanSymbol(
^
../hello.cc:11:58: error: cannot initialize a parameter of type 'v8::Isolate *' with an lvalue of type 'void
(const v8::FunctionCallbackInfo<v8::Value> &)'
exports->Set(NanSymbol("hello"), FunctionTemplate::New(Method)->GetFunction());
^~~~~~
/Users/arthurakay/.node-gyp/0.12.0/deps/v8/include/v8.h:3456:16: note: passing argument to parameter
'isolate' here
Isolate* isolate,
^
1 warning and 2 errors generated.
make: *** [Release/obj.target/hello/hello.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/node-gyp/lib/build.js:269:23)
gyp ERR! stack at ChildProcess.emit (events.js:110:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:1067:12)
gyp ERR! System Darwin 14.1.0
gyp ERR! command "node" "/usr/local/bin/node-gyp" "build"
gyp ERR! cwd /Users/arthurakay/www/node_addons/quark
gyp ERR! node -v v0.12.0
gyp ERR! node-gyp -v v1.0.3
gyp ERR! not ok
While I'm fairly experienced in Node.js, I'm an absolute noob in V8 and NAN. I would guess this is a Node version problem, but I was hoping someone might help clear things up for me. Thanks!
Mac OS X 10.10.2, other versions (node, etc) in the callstack above.
I have a question about Persistent, in the sixth example
void MyObject::Init(Handle<Object> target) {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
FunctionTemplate::New(PlusOne)->GetFunction());
Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
target->Set(String::NewSymbol("MyObject"), constructor);
}
why the constructor need to be defined as Persistent Handler instead of Local handler? I have tried to use Local and it also work.
I cannot find any information on how to create an ObjectWrap and pass it as an argument to a Local. I have a persistent callback registered and need to call it with a new instance of an ObjectWrap. I could do this by calling the (JS) constructor and pass it (JS) arguments which returns a new instance, but I want to avoid this round tripping.
Basically: how to create an ObjectWrap and get a Local out of it so that I can pass it as an argument to a JS function?
An example that calls a callback asynchronously would be very valuable.
I imagine getting async behaviour correct is what most addon developers are going to be worried about, i.e. not blocking the Node event loop.
I at least really don't know where to start with it.
why async_work example was removed?
I checked out 1_hello_world
on the v0.11 branch, but the example doesn't compile (Windows 7, VS 2012).
Check out the following screenshot and error list:
Error 1 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 2 error C2143: syntax error : missing ',' before '&'
Error 3 error C2039: 'Close' : is not a member of 'v8::HandleScope'
Error 4 error C2039: 'New' : is not a member of 'v8::String'
Error 5 error C3861: 'New': identifier not found
Error 6 error C2039: 'NewSymbol' : is not a member of 'v8::String'
Error 7 error C2664: 'v8::FunctionTemplate::New' : cannot convert parameter 1 from 'v8::Handle<T> (__cdecl *)(const int)' to 'v8::Isolate *' c:\users\mmaedler\documents\visual studio
Error 8 error C2227: left of '->GetFunction' must point to class/struct/union/generic type
Error 9 error C3861: 'NewSymbol': identifier not found
Is there anything I'm missing? The other examples for node-v0.10.31 did compile fine. All I could figure out is, that Arguments
seems to be a member of the namespace v8::internals
now.
P.S. It does indeed compile against node-v0.11.3. But I need my module to run with v0.11.13. Is this possible?
Thanks in advance
Can examples of composition and inheritance of wrapped objects be added? I think one could potentially figure it out with the current examples, but I'm not able to figure it out.
class BasicClass { int IntValue; };
class BasicComposition
{
int foo;
BasicClass bc;
};
class BasicInheritance : BasicClass
{
double yValue;
};
class InheritanceAndComposition : BasicInheritance
{
std::string strValue;
BasicComposition bcValue;
};
// Export all classes to JS
One should be able to instantiate and use each C++ class in JavaScript (e.g. create an instance of BasicClass
independent of instances of BasicComposition
).
It seems to me that only the case of BasicClass
has an example in 6_object_wrap. The other cases with inheritance and composition of classes extending ObjectWrap<T>
do not appear to exist. Inheritance might be covered in inherits_from_event_emitter, but it is not clear to me what is going on in that example.
I'm hoping someone with more experience with node-addon-api can provide these types of examples. It would greatly assist me in defining more complex relationships in Napi.
Can anyone add how to wrap properties on 6_object_wrap, I have tried Nan::SetAccessor,But it has 2 methods, and invoke the wrong function.
Thanks.
with release of NAN 2.x, nodejs version must be >= 0.10.29, so i think it is beneficial to keep examples for both of the versions of nan, would you consider to put back nan_1.x alone with nan_2.x if I will make another pull request?
for example ubuntu trusty comes with 0.10.25
http://packages.ubuntu.com/search?keywords=nodejs&searchon=names&suite=trusty§ion=all
Hi there! Maybe this is not really necessary. But I think I am kind of stuck in there. And it's really hard to find an example of this.
Just a suggestion :)
where
echo('abc')
will produce
abc
Hey!
This is more like something I am stuck at.
I have a library with header files, and I want to make bindings for that library. Yet, I can not change the already existing classes. So, I am looking for a way to wrap these existing classes into a nodejs module.
Currently, I am waiting for some peeps to respond. But it would still be awesome if that would be added here, as it is quite a usual case.
Kind regards, Ingwie! ^^
I'm in the process of updating node to v8 3.17. This requires a few API changes to these examples. You can track the bug here: nodejs/node-v0.x-archive#5077
Don't have the commit up yet with the changes to api docs, but will soon.
how to extend a wrap?
I know that there is
tpl->Inherit (parent)
but how to solve the question of unwarp, to get the correct object?
Dinamic?* w = ObjectWrap::Unwrap<Dinamic?>(args.This());
(sorry for my English)
In the object wrap examples for node 0.12 there is no HandleScope in the Init function, but you use a Local handle. Is this a bug or on purpose? Great examples by the way, very instructive!
void MyObject::Init(Handle<Object> exports) {
Isolate* isolate = Isolate::GetCurrent();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
In the "6_object_wrap_example/node-addon-api", I tried to test what would happen when calling the constructor without arguments and I noticed that the actual exception thrown ("A number was expected") is different from the one in the code ("Number expected").
According to node-addon-api docs, when C++ exceptions are disabled you need to return immediately after calling ThrowAsJavaScriptException. So I would expect something like:
if (length <= 0 || !info[0].IsNumber()) {
Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
return;
}
I think that the exception thrown is not the one from line 28 of myobject.cc, but another one thrown automatically when trying to convert the parameter to a number.
I tried to move one step further (following this tutorial) and unwrapping a Javascript object, and I get a segmentation fault when using the constructor without arguments because the code is not stopping after reaching the line with ThrowAsJavaScriptException.
Hi,
I upgraded all but 7_factory_wrap & 8_passing_wrapped. Get the
Assertion `handle->InternalFieldCount() > 0' failed.
For the rest I can provide patch files. The changes are for V8 and node master branches as of today.
All of the Addon examples are out of date. We need v4, v5 and soon v6 examples. The most recent appear to be v0.12
The example should also illustrate the use of napi_make_callback
.
Hi,
Is it possible to add another example showing how to emit events from the c++ land?
Here's an example done by bnoordhuis 2 years ago. Maybe you could rewrite it for v0.10 and v0.11?
The basic idea is to expose a c++ class which inherits from ObjectWrap and internally calls to the emit
function and in the js code inherit from EventEmitter.
Is NAN still the state of the art way to create Node.js addons? Looking at a repo like this:
https://github.com/nodejs/node-addon-examples/tree/master/1_hello_world
it looks like NAPI has overtaken NAN, or?
this info should go in the readme, telling users which one is the most recent version to use?
CXX(target) Debug/obj.target/addon/addon.o
In file included from ../addon.cc:1:0:
../node_modules/nan/nan.h:481:19: error: ‘NanNew’ declared as an ‘inline’ variable
v8::String::ExternalAsciiStringResource *resource) {
^
../node_modules/nan/nan.h:481:19: error: ‘v8::Local<v8::String> NanNew’ redeclared as different kind of symbol
../node_modules/nan/nan.h:475:36: error: previous declaration of ‘v8::Local<v8::String> NanNew(v8::String::ExternalStringResource*)’
NAN_INLINE v8::Local<v8::String> NanNew(
^
../node_modules/nan/nan.h:481:7: error: ‘ExternalAsciiStringResource’ is not a member of ‘v8::String’
v8::String::ExternalAsciiStringResource *resource) {
^
../node_modules/nan/nan.h:481:48: error: ‘resource’ was not declared in this scope
v8::String::ExternalAsciiStringResource *resource) {
^
../node_modules/nan/nan.h: In function ‘bool _NanGetExternalParts(v8::Handle<v8::Value>, const char**, size_t*)’:
../node_modules/nan/nan.h:2103:12: error: ‘class v8::String’ has no member named ‘IsExternalAscii’
if (str->IsExternalAscii()) {
^
../node_modules/nan/nan.h:2104:11: error: ‘ExternalAsciiStringResource’ in ‘class v8::String’ does not name a type
const v8::String::ExternalAsciiStringResource* ext;
^
../node_modules/nan/nan.h:2105:5: error: ‘ext’ was not declared in this scope
ext = str->GetExternalAsciiStringResource();
^
../node_modules/nan/nan.h:2105:16: error: ‘class v8::String’ has no member named ‘GetExternalAsciiStringResource’
ext = str->GetExternalAsciiStringResource();
^
make: *** [Debug/obj.target/addon/addon.o] Error 1
I'm trying to make async promise and I use AsyncWorker for it. But I think callback function is odd here
Do I do something wrong?
Napi::Value EmptyCallback(const Napi::CallbackInfo& info)
{
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
return env.Undefined();
}
class SumWorker : public Napi::AsyncWorker {
public:
SumWorker(Napi::Function& callback, Napi::Promise::Deferred deferred, int num1, int num2)
: Napi::AsyncWorker(callback), deferred(deferred), num1(num1), num2(num2), sum(0)) {}
~SumWorker() {}
void Execute () {
sum = num1 + num2;
}
void OnError() {
Napi::HandleScope scope(Env());
deferred.Reject(Napi::Error::New(Env(), "Something wrong"));
// Call empty function
Callback().Call({});
}
void OnOK() {
Napi::HandleScope scope(Env());
deferred.Resolve(Napi::Number::New(sum));
// Call empty function
Callback().Call({});
}
private:
Napi::Promise::Deferred deferred;
int num1;
int num2;
int sum;
};
Napi::Value CallPromise(const Napi::CallbackInfo& info)
{
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int num1 = info[0].As<Napi::Number>();
int num2 = info[1].As<Napi::Number>();
Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(info.Env());
Napi::Function callback = Napi::Function::New(env, EmptyCallback);
SumWorker* worker = new SumWorker(callback, deferred, num1, num2);
worker->Queue();
return deferred.Promise();
}
user1@ubuntu:~/node-addon-examples/2_function_arguments/node_0.10$ npm install
[email protected] install /home/user1/node-addon-examples/2_function_arguments/node_0.10
node-gyp rebuild
make: Entering directory /home/user1/node-addon-examples/2_function_arguments/node_0.10/build' CXX(target) Release/obj.target/addon/addon.o ../addon.cc:5:16: error: ‘FunctionCallbackInfo’ in namespace ‘v8’ does not name a type ../addon.cc:5:20: error: ISO C++ forbids declaration of ‘parameter’ with no type [-fpermissive] ../addon.cc:5:40: error: expected ‘,’ or ‘...’ before ‘<’ token ../addon.cc: In function ‘void Add(int)’: ../addon.cc:7:28: error: no matching function for call to ‘v8::HandleScope::HandleScope(v8::Isolate*&)’ ../addon.cc:7:28: note: candidates are: /home/user1/.node-gyp/0.10.40/deps/v8/include/v8.h:473:3: note: v8::HandleScope::HandleScope(const v8::HandleScope&) /home/user1/.node-gyp/0.10.40/deps/v8/include/v8.h:473:3: note: no known conversion for argument 1 from ‘v8::Isolate*’ to ‘const v8::HandleScope&’ /home/user1/.node-gyp/0.10.40/deps/v8/include/v8.h:448:3: note: v8::HandleScope::HandleScope() /home/user1/.node-gyp/0.10.40/deps/v8/include/v8.h:448:3: note: candidate expects 0 arguments, 1 provided ../addon.cc:9:7: error: ‘args’ was not declared in this scope ../addon.cc:14:8: error: ‘args’ was not declared in this scope ../addon.cc:19:17: error: ‘args’ was not declared in this scope ../addon.cc: In function ‘void Init(v8::Handle<v8::Object>)’: ../addon.cc:28:32: error: invalid conversion from ‘void (*)(int)’ to ‘v8::InvocationCallback {aka v8::Handle<v8::Value> (*)(const v8::Arguments&)}’ [-fpermissive] /home/user1/.node-gyp/0.10.40/deps/v8/include/v8.h:2259:34: error: initializing argument 1 of ‘static v8::Local<v8::FunctionTemplate> v8::FunctionTemplate::New(v8::InvocationCallback, v8::Handle<v8::Value>, v8::Handle<v8::Signature>)’ [-fpermissive] make: *** [Release/obj.target/addon/addon.o] Error 1 make: Leaving directory
/home/user1/node-addon-examples/2_function_arguments/node_0.10/build'
gyp ERR! build error
gyp ERR! stack Error: make
failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/home/user1/.nvm/v0.10.40/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23)
gyp ERR! stack at ChildProcess.emit (events.js:98:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:820:12)
gyp ERR! System Linux 3.2.0-29-generic
gyp ERR! command "node" "/home/user1/.nvm/v0.10.40/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/user1/node-addon-examples/2_function_arguments/node_0.10
gyp ERR! node -v v0.10.40
gyp ERR! node-gyp -v v1.0.1
gyp ERR! not ok
npm ERR! [email protected] install: node-gyp rebuild
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the function_arguments package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get their info via:
npm ERR! npm owner ls function_arguments
npm ERR! There is likely additional logging output above.
npm ERR! System Linux 3.2.0-29-generic
npm ERR! command "/home/user1/.nvm/v0.10.40/bin/node" "/home/user1/.nvm/v0.10.40/bin/npm" "install"
npm ERR! cwd /home/user1/node-addon-examples/2_function_arguments/node_0.10
npm ERR! node -v v0.10.40
npm ERR! npm -v 1.4.28
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/user1/node-addon-examples/2_function_arguments/node_0.10/npm-debug.log
npm ERR! not ok code 0
I've had success cross compiling modules, but I got the following error when trying to do so with the Hello World example code.
$ node hello.js
module.js:356
Module._extensions[extension](this, filename);
^
Error: /node/addon/hello/build/Release/hello.node: wrong ELF class: ELFCLASS32
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/node/addon/hello/hello.js:1:75)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
I built with
$ node-gyp --arch arm rebuild
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | linux | x64
gyp info spawn python
gyp info spawn args [ '/usr/local/lib/node_modules/node-gyp/gyp/gyp',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'make',
gyp info spawn args '-I',
gyp info spawn args '/node/addon/hello/build/config.gypi',
gyp info spawn args '-I',
gyp info spawn args '/usr/local/lib/node_modules/node-gyp/addon.gypi',
gyp info spawn args '-I',
gyp info spawn args '/home/ubuntu/.node-gyp/0.10.0/common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=/home/ubuntu/.node-gyp/0.10.0',
gyp info spawn args '-Dmodule_root_dir=/node/addon/hello',
gyp info spawn args '--depth=.',
gyp info spawn args '--generator-output',
gyp info spawn args 'build',
gyp info spawn args '-Goutput_dir=.' ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
make: Entering directory `/node/addon/hello/build'
CXX(target) Release/obj.target/hello/hello.o
SOLINK_MODULE(target) Release/obj.target/hello.node
COPY Release/hello.node
make: Leaving directory `/node/addon/hello/build'
gyp info ok
To my eye, that looks ok. As a test, ran 'file' on the node binary:
file hello.node
hello.node: ELF 32-bit LSB shared object, ARM, version 1 (SYSV), dynamically linked, not stripped
Which looks good.
Any suggestions?
This may be a silly question and it may be the wrong place for it, but I think it's probably the best place for it nonetheless.
I've gone through the examples, and a variety of libraries like libxml, I generally see that the entire .cc file must be essentially re-written to look like v8 cpp. I'm curious if there isn't a way, or if maybe it's somehow implied already and I'm just not seeing it, that someone could work less invasively, without destroying the original cpp source. For example
my-addon/
-- original-src/
-- -- hello.h
-- -- hello.cc
-- src/
-- -- hello_node.cc
-- binding.gyp
Where hello.cc is some library that has absolutely no v8 code in it, but can then be included & wrapped in hello_node.cc. So for example, hello.cc would compile into some library that exported a function hello
that outputs "world", you would then write all the v8 wrapper code in hello_node.cc. Right now, it looks like the idea is to go into hello.cc and rewrite the function hello
in a v8-compatible manner.
Is this something that just can't be done, or that would require specific circumstances?
Thanks!
I transfer the image buffer data from js to cpp, using Local value = args[0]->ToObject();
But after that I don't know how to use the data in cpp.
I hope to convert that to cv Mat type.
If someone know about it, please give me an advice.
Thank you.
I've have problem building node-gyp after the second example.
I'm working on mac Mavericks
$4_object_factory git:(master) node-gyp rebuild
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | darwin | x64
gyp info spawn python
gyp info spawn args [ '/usr/local/lib/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'make',
gyp info spawn args '-I',
gyp info spawn args '/Users/lijung/Documents/school/node-addon-examples/4_object_factory/build/config.gypi',
gyp info spawn args '-I',
gyp info spawn args '/usr/local/lib/node_modules/node-gyp/addon.gypi',
gyp info spawn args '-I',
gyp info spawn args '/Users/lijung/.node-gyp/0.8.5/common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=/Users/lijung/.node-gyp/0.8.5',
gyp info spawn args '-Dmodule_root_dir=/Users/lijung/Documents/school/node-addon-examples/4_object_factory',
gyp info spawn args '--depth=.',
gyp info spawn args '--generator-output',
gyp info spawn args 'build',
gyp info spawn args '-Goutput_dir=.' ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
CXX(target) Release/obj.target/addon/addon.o
../addon.cc:1:9: warning: 'BUILDING_NODE_EXTENSION' macro redefined
#define BUILDING_NODE_EXTENSION
^
<command line>:4:9: note: previous definition is here
#define BUILDING_NODE_EXTENSION 1
^
../addon.cc:20:20: error: cannot initialize a member subobject of type 'void (*)(v8::Handle<v8::Object>)' with an lvalue of type
'void (Handle<v8::Object>, Handle<v8::Object>)': different number of parameters (1 vs 2)
NODE_MODULE(addon, Init)
^~~~
/Users/lijung/.node-gyp/0.8.5/src/node.h:235:7: note: expanded from macro 'NODE_MODULE'
regfunc, \
^
1 warning and 1 error generated.
make: *** [Release/obj.target/addon/addon.o] Error 1
The examples were updated to nan 2 but the readme's still use the old syntax? I can change the readme but I think the content has to be rewritten in to those parts as they mean different things now.
Hi,
I have been working with Node addon and everything was working great until today when I started getting issues in node-gyp build. my addon compiles successfully but hangs forever and doesn't create .node file. the last line I see in console is SOLINK_MODULE(target) Release/obj.target/something.node. It simply hangs there for ever.
I did lot of search online but couldn't find any help.
Thanks
https://github.com/rvagg/node-addon-examples/blob/master/9_async_work/async.cc#L68
Javascript numbers are represented using 64 bits, then isn't it better to just call to NumberValue() which returns a double or IntegerValue which returns int64_t?
How to create utf8 string from a argument
I have installed the latest nan. Is NanScope
removed?
nodejs/node#13512 seems to indicate that we should have such an example.
Recreating Issue #60
Issue was closed by reporter who cannot remember what the fix was.
Node v5.0.0
nan v2.0.0 & v2.7.0
[email protected]
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
make: Entering directory '/home/peter/repos/node-struct/hello-world/build'
CXX(target) Release/obj.target/hello/hello.o
../hello.cc: In function ‘Nan::NAN_METHOD_RETURN_TYPE Method(Nan::NAN_METHOD_ARGS_TYPE)’:
../hello.cc:6:12: error: ‘NanScope’ was not declared in this scope
NanScope();
^
../hello.cc:7:18: error: ‘New’ is not a member of ‘v8::String’
NanReturnValue(String::New("world"));
^
../hello.cc:7:38: error: ‘NanReturnValue’ was not declared in this scope
NanReturnValue(String::New("world"));
^
../hello.cc: In function ‘void Init(v8::Handle<v8::Object>)’:
../hello.cc:11:33: error: ‘NanSymbol’ was not declared in this scope
exports->Set(NanSymbol("hello"), FunctionTemplate::New(Method)->GetFunction());
^
../hello.cc:11:64: error: no matching function for call to ‘v8::FunctionTemplate::New(Nan::NAN_METHOD_RETURN_TYPE (&)(Nan::NAN_METHOD_ARGS_TYPE))’
exports->Set(NanSymbol("hello"), FunctionTemplate::New(Method)->GetFunction());
^
In file included from /home/peter/.node-gyp/5.0.0/include/node/node.h:42:0,
from ../node_modules/nan/nan.h:49,
from ../hello.cc:1:
/home/peter/.node-gyp/5.0.0/include/node/v8.h:4348:34: note: candidate: static v8::Local<v8::FunctionTemplate> v8::FunctionTemplate::New(v8::Isolate*, v8::FunctionCallback, v8::Local<v8::Value>, v8::Local<v8::Signature>, int)
static Local<FunctionTemplate> New(
^
/home/peter/.node-gyp/5.0.0/include/node/v8.h:4348:34: note: no known conversion for argument 1 from ‘Nan::NAN_METHOD_RETURN_TYPE(Nan::NAN_METHOD_ARGS_TYPE) {aka void(const Nan::FunctionCallbackInfo<v8::Value>&)}’ to ‘v8::Isolate*’
hello.target.mk:96: recipe for target 'Release/obj.target/hello/hello.o' failed
make: *** [Release/obj.target/hello/hello.o] Error 1
make: Leaving directory '/home/peter/repos/node-struct/hello-world/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/home/peter/.nvm/v5.0.0/lib/node_modules/node-gyp/lib/build.js:258:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 4.2.0-42-generic
gyp ERR! command "/home/peter/.nvm/v5.0.0/bin/node" "/home/peter/.nvm/v5.0.0/bin/node-gyp" "build"
gyp ERR! cwd /home/peter/repos/node-struct/hello-world
gyp ERR! node -v v5.0.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
I have a byte array of an image in nodejs and i want to pass it in a C function for further processing .
If i am passing it as string then the array is not passed correctly. Can you tell me how can i pass it?
I am totally new to addons and node-gyp
in the 1_hello_world example
sudo node-gyp configure # works
but
sudo node-gyp build # fails
failing with these messages
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | linux | x64
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
make: Entering directory '/home/oleg/WebstormProjects/oresoftware/replace-line/build'
CXX(target) Release/obj.target/hello/hello.o
../hello.cc: In function ‘Nan::NAN_METHOD_RETURN_TYPE Method(Nan::NAN_METHOD_ARGS_TYPE)’:
../hello.cc:6:12: error: ‘NanScope’ was not declared in this scope
NanScope();
^
../hello.cc:7:18: error: ‘New’ is not a member of ‘v8::String’
NanReturnValue(String::New("world"));
^
../hello.cc:7:38: error: ‘NanReturnValue’ was not declared in this scope
NanReturnValue(String::New("world"));
^
../hello.cc: In function ‘void Init(v8::Handle<v8::Object>)’:
../hello.cc:11:33: error: ‘NanSymbol’ was not declared in this scope
exports->Set(NanSymbol("hello"), FunctionTemplate::New(Method)->GetFunction());
^
../hello.cc:11:64: error: no matching function for call to ‘v8::FunctionTemplate::New(Nan::NAN_METHOD_RETURN_TYPE (&)(Nan::NAN_METHOD_ARGS_TYPE))’
exports->Set(NanSymbol("hello"), FunctionTemplate::New(Method)->GetFunction());
^
In file included from /home/oleg/.node-gyp/4.2.6/include/node/node.h:42:0,
from ../node_modules/nan/nan.h:47,
from ../hello.cc:1:
/home/oleg/.node-gyp/4.2.6/include/node/v8.h:4349:34: note: candidate: static v8::Local<v8::FunctionTemplate> v8::FunctionTemplate::New(v8::Isolate*, v8::FunctionCallback, v8::Local<v8::Value>, v8::Local<v8::Signature>, int)
static Local<FunctionTemplate> New(
^
/home/oleg/.node-gyp/4.2.6/include/node/v8.h:4349:34: note: no known conversion for argument 1 from ‘Nan::NAN_METHOD_RETURN_TYPE(Nan::NAN_METHOD_ARGS_TYPE) {aka void(const Nan::FunctionCallbackInfo<v8::Value>&)}’ to ‘v8::Isolate*’
hello.target.mk:96: recipe for target 'Release/obj.target/hello/hello.o' failed
make: *** [Release/obj.target/hello/hello.o] Error 1
make: Leaving directory '/home/oleg/WebstormProjects/oresoftware/replace-line/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/node-gyp/lib/build.js:276:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 4.4.0-57-generic
gyp ERR! command "/usr/bin/nodejs" "/usr/local/bin/node-gyp" "build"
gyp ERR! cwd /home/oleg/WebstormProjects/oresoftware/replace-line
gyp ERR! node -v v4.2.6
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok
I will try some of the the other examples, but would like to know how I can fix! thanks
Hello,
I'm having trouble making a callback and passing a Buffer as the argument.
Look at the code here:
v8::Local<v8::Function> callback;
void SetCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {
callback = info[0].As<v8::Function>();
}
void do_callback() {
int size = 100;
v8::MaybeLocal<v8::Object> obj = Nan::NewBuffer(size);
const unsigned argc = 1;
args[1] = { obj.ToLocalChecked() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, args);
}
I always get "segmentation fault" and I do not know why..
To keep the code simple I am just intializing a new Buffer with size only..
However i would like to intialize the Buffer with data like so:
char* data =...
v8::MaybeLocal<v8::Object> obj = Nan::NewBuffer(data, size);
My goal is to callback a javascript function with a Buffer that is wrapped around an existing char pointer..
Please help.
Thank you!
As of Nan version 2.1.0 there exists Nan::TypedArrayContents, which assists in accessing Typed Arrays. See https://github.com/nodejs/nan/blob/master/doc/v8_misc.md#nantypedarraycontents
It would be very useful to have an example of how to use this. I could make the push request with a new example included so long as I was given some assistance with the coding.
Hi,
in example '3_callbacks\nan' is probably missing a return value in function 'RunCallback'.
Output of 'npm install':
e:\node_addons\node-addon-examples\3_callbacks\nan\addon.cc(14): error C4716: 'RunCallback' : must return a value [e:\node_addons\node-addon-examples\3_callbacks\nan\build\addon.vcxproj]
LINK : fatal error LNK1257: code generation failed [e:\node_addons\node-addon-examples\3_callbacks\nan\build\addon.vcxproj]
It can be fixed by adding a line:
return scope.Close(Undefined());
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.