C 节点本机扩展调用方法两次

C Node Native Extension calls method twice

本文关键字:两次 方法 节点 本机 扩展 调用      更新时间:2023-10-16

所以我对C相当陌生,并且正在开发一个简单的Node Native扩展。

这是我的扩展的代码,名为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)

我使用以前的到下面的 Node.js 类...

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);

当我调用该网站时,我在终端中看到以下内容

~/Desktop/hellonode$ node testnode
:Init:
:Calling Method:
:Turning Off:
:Calling Method:
:Turning On:

为什么它似乎调用该方法两次?我相信答案是显而易见的,但我看不到。

这是一种重复。这不是扩展中的错误,而是 HTTP 代码中的问题。

看:

  • 简单的 http 服务器
  • 节点.js页面刷新调用资源两次?

基本上,您的浏览器正在请求两个URL,//favicon.ico,并且由于您没有检查URL,因此它会在两个请求上运行扩展代码。