简体   繁体   English

创建第一个node.js插件

[英]Creating first node.js addon

I'm following the docs to create a node.js addon. 我正在按照文档创建一个node.js插件。 I ran 我跑了

node-gyp configure build --python C:\\Python27

and received error 并收到错误

Error: spawn ENOENT 错误:产生ENOENT

Full stack: 全栈:

gyp info it worked if it ends with ok
gyp info using node-gyp@1.0.3
gyp info using node@0.10.29 | win32 | x64
gyp ERR! configure error
gyp ERR! stack Error: spawn ENOENT
gyp ERR! stack     at errnoException (child_process.js:1000:11)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:791:34)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "node" "C:\\Users\\bmackey\\AppData\\Roaming\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "configure" "build" "--python" "C:\\Python27"
gyp ERR! cwd D:\DevProjects\Node\AddOn
gyp ERR! node -v v0.10.29
gyp ERR! node-gyp -v v1.0.3
gyp ERR! not ok

My 3 required files are all in the same directory: 我的3个必需文件都在同一目录中:

hello.cc: hello.cc:

// hello.cc
#include <node.h>

//Note that all node addons must export an initialization function.
//Does this go in a .h or here or what?
void Initialize (Handle<Object> exports);
NODE_MODULE(module_name, Initialize)

using namespace v8;

void Method(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}

void init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}

NODE_MODULE(addon, init)

binding.gyp: binding.gyp:

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "hello.cc" ]
    }
  ]
}

hello.js: hello.js:

var addon = require('./build/Release/addon');

console.log(addon.hello()); // 'world'

The optional --python argument requires the path to python.exe: 可选的--python参数需要python.exe的路径:

node-gyp configure build --python C:\\Python27\\python.exe

The example on node.js website did not work for me. node.js网站上的示例不适用于我。 This guy's example worked better, but ultimately this worked and made more sense to me: 这个人的例子工作得更好,但最终这对我来说更有意义:

hello.cc hello.cc

#include <node.h>

using namespace v8;

Handle<Value> Method(const Arguments& args) {
  HandleScope scope;
  return scope.Close(String::New("here is some output"));
}

void init(Handle<Object> target) {
  target->Set(String::NewSymbol("methodName"),
      FunctionTemplate::New(Method)->GetFunction());
}
NODE_MODULE(myModuleName, init)

binding.gyp: binding.gyp:

{
  "targets": [
    {
      "target_name": "myModuleName",
      "sources": [ "hello.cc" ]
    }
  ]
}

hello.js: hello.js:

var addon = require('./build/Release/myModuleName');

console.log(addon.methodName()); // prints "here is some output"

This layout took some of the naming ambiguity out. 这种布局消除了一些命名歧义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM