So I am fairly new to C and working on a simple Node Native extension.
Here is the code for my extension called helloworld.c
Handle<Value> Method(const Arguments& args) {
printf(":%s:\n", "Calling Method");
//SendByte(bdrate,'1');
HandleScope scope;
if(toggleLight()==0){
printf(":%s:\n", "Turning On");
return scope.Close(String::New("Turned On"));
}
else{
printf(":%s:\n", "Turning Off");
return scope.Close(String::New("Turned Off"));
}
}
void init(Handle<Object> target) {
printf(":%s:\n", "Init");
target->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Method)->GetFunction());
}
NODE_MODULE(helloworld, init)
I consume the previous through the following Node.js class...
var addon = require('./build/Release/helloworld');
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(addon.hello());
response.end();
}).listen(8888);
When I call the site I see the following in my terminal
~/Desktop/hellonode$ node testnode
:Init:
:Calling Method:
:Turning Off:
:Calling Method:
:Turning On:
Why does it seem to be calling the method twice? I am sure the answer is obvious but I cannot see it.
This is sort of a duplicate. This is not a bug in your extension, it's an issue in your HTTP code.
See:
Basically, your browser is requesting two urls, /
and /favicon.ico
, and since you aren't checking the URL, it runs your extension code on both requests.