首页 web前端 js教程 Node.js各种扩展方法代码实例汇总

Node.js各种扩展方法代码实例汇总

Jul 24, 2017 am 11:55 AM
javascript node.js 代码

Node.js扩展

Init方法

为了创建一个Node.js扩展,我们需要编写一个继承node::ObjectWrap的C++类。 ObjectWrap 实现了让我们更容易与Javascript交互的公共方法

我们先来编写类的基本框架:

#include <v8.h> // v8 is the Javascript engine used by QNode
#include <node.h>
// We will need the following libraries for our GTK+ notification
#include <string>
#include <gtkmm.h>
#include <libnotifymm.h>
 
using namespace v8;
 
class Gtknotify : node::ObjectWrap {
 private:
 public:
  Gtknotify() {}
  ~Gtknotify() {}
  static void Init(Handle<Object> target) {
   // This is what Node will call when we load the extension through require(), see boilerplate code below.
  }
};
 
/*
 * WARNING: Boilerplate code ahead.
 * Thats it for actual interfacing with v8, finally we need to let Node.js know how to dynamically load our code.
 * Because a Node.js extension can be loaded at runtime from a shared object, we need a symbol that the dlsym function can find,
 * so we do the following: 
 */
 
v8::Persistent<FunctionTemplate> Gtknotify::persistent_function_template;
extern "C" { // Cause of name mangling in C++, we use extern C here
 static void init(Handle<Object> target) {
  Gtknotify::Init(target);
 }
 NODE_MODULE(gtknotify, init);
}
登录后复制

现在,我们必须把下面的代码编写到我们的Init()方法中:

声明构造函数,并将其绑定到我们的目标变量。var n = require("notification");将绑定notification() 到 n:n.notification().

// Wrap our C++ New() method so that it&#39;s accessible from Javascript
  // This will be called by the new operator in Javascript, for example: new notification();
  v8::Local<FunctionTemplate> local_function_template = v8::FunctionTemplate::New(New);
   
  // Make it persistent and assign it to persistent_function_template which is a static attribute of our class.
  Gtknotify::persistent_function_template = v8::Persistent<FunctionTemplate>::New(local_function_template);
   
  // Each JavaScript object keeps a reference to the C++ object for which it is a wrapper with an internal field.
  Gtknotify::persistent_function_template->InstanceTemplate()->SetInternalFieldCount(1); // 1 since a constructor function only references 1 object
  // Set a "class" name for objects created with our constructor
  Gtknotify::persistent_function_template->SetClassName(v8::String::NewSymbol("Notification"));
   
  // Set the "notification" property of our target variable and assign it to our constructor function
  target->Set(String::NewSymbol("notification"), Gtknotify::persistent_function_template->GetFunction());
登录后复制

声明属性:n.title 和n.icon.

  // Set property accessors
  // SetAccessor arguments: Javascript property name, C++ method that will act as the getter, C++ method that will act as the setter
  Gtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("title"), GetTitle, SetTitle);
  Gtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("icon"), GetIcon, SetIcon);
  // For instance, n.title = "foo" will now call SetTitle("foo"), n.title will now call GetTitle()
登录后复制

声明原型方法:n.send()

  // This is a Node macro to help bind C++ methods to Javascript methods (see https://github.com/joyent/node/blob/v0.2.0/src/node.h#L34)
  // Arguments: our constructor function, Javascript method name, C++ method name
  NODE_SET_PROTOTYPE_METHOD(Gtknotify::persistent_function_template, "send", Send);
登录后复制

现在我们的Init()方法看起来应该是这样的:

// Our constructor
static v8::Persistent<FunctionTemplate> persistent_function_template;
 
static void Init(Handle<Object> target) {
 v8::HandleScope scope; // used by v8 for garbage collection
 
 // Our constructor
 v8::Local<FunctionTemplate> local_function_template = v8::FunctionTemplate::New(New);
 Gtknotify::persistent_function_template = v8::Persistent<FunctionTemplate>::New(local_function_template);
 Gtknotify::persistent_function_template->InstanceTemplate()->SetInternalFieldCount(1); // 1 since this is a constructor function
 Gtknotify::persistent_function_template->SetClassName(v8::String::NewSymbol("Notification"));
 
 // Our getters and setters
 Gtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("title"), GetTitle, SetTitle);
 Gtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("icon"), GetIcon, SetIcon);
 
 // Our methods
 NODE_SET_PROTOTYPE_METHOD(Gtknotify::persistent_function_template, "send", Send);
 
 // Binding our constructor function to the target variable
 target->Set(String::NewSymbol("notification"), Gtknotify::persistent_function_template->GetFunction());
}
登录后复制

剩下要做的就是编写我们在Init方法中用的C++方法:New,GetTitle,SetTitle,GetIcon,SetIcon,Send

构造器方法: New()

New() 方法创建了我们自定义类的新实例(一个 Gtknotify 对象),并设置一些初始值,然后返回该对象的 JavaScript 处理。这是 JavaScript 使用 new 操作符调用构造函数的期望行为。

 std::string title;
std::string icon;
 
// new notification()
static Handle<Value> New(const Arguments& args) {
 HandleScope scope;
 Gtknotify* gtknotify_instance = new Gtknotify();
 // Set some default values
 gtknotify_instance->title = "Node.js";
 gtknotify_instance->icon = "terminal";
 
 // Wrap our C++ object as a Javascript object
 gtknotify_instance->Wrap(args.This());
 
 return args.This();
}
getters 和 setters: GetTitle(), SetTitle(), GetIcon(), SetIcon()
登录后复制

下面主要是一些样板代码,可以归结为 C++ 和 JavaScript (v8) 之间的值转换。

// this.title
static v8::Handle<Value> GetTitle(v8::Local<v8::String> property, const v8::AccessorInfo& info) {
 // Extract the C++ request object from the JavaScript wrapper.
 Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());
 return v8::String::New(gtknotify_instance->title.c_str());
}
// this.title=
static void SetTitle(Local<String> property, Local<Value> value, const AccessorInfo& info) {
 Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());
 v8::String::Utf8Value v8str(value);
 gtknotify_instance->title = *v8str;
}
// this.icon
static v8::Handle<Value> GetIcon(v8::Local<v8::String> property, const v8::AccessorInfo& info) {
 // Extract the C++ request object from the JavaScript wrapper.
 Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());
 return v8::String::New(gtknotify_instance->icon.c_str());
}
// this.icon=
static void SetIcon(Local<String> property, Local<Value> value, const AccessorInfo& info) {
 Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());
 v8::String::Utf8Value v8str(value);
 gtknotify_instance->icon = *v8str;
}
登录后复制

原型方法: Send()

首先我们抽取 C++ 对象的 this 引用,然后使用对象的属性来构建通知并显示。

// this.send()
static v8::Handle<Value> Send(const Arguments& args) {
 v8::HandleScope scope;
 // Extract C++ object reference from "this"
 Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(args.This());
 
 // Convert first argument to V8 String
 v8::String::Utf8Value v8str(args[0]);
 
 // For more info on the Notify library: http://library.gnome.org/devel/libnotify/0.7/NotifyNotification.html
 Notify::init("Basic");
 // Arguments: title, content, icon
 Notify::Notification n(gtknotify_instance->title.c_str(), *v8str, gtknotify_instance->icon.c_str()); // *v8str points to the C string it wraps
 // Display the notification
 n.show();
 // Return value
 return v8::Boolean::New(true);
}
登录后复制

编译扩展

node-waf 是一个构建工具,用来编译 Node 的扩展,这是 waf 的基本封装。构建过程可通过名为 wscript 的文件进行配置。

def set_options(opt):
 opt.tool_options("compiler_cxx")
 
def configure(conf):
 conf.check_tool("compiler_cxx")
 conf.check_tool("node_addon")
 # This will tell the compiler to link our extension with the gtkmm and libnotifymm libraries.
 conf.check_cfg(package=&#39;gtkmm-2.4&#39;, args=&#39;--cflags --libs&#39;, uselib_store=&#39;LIBGTKMM&#39;)
 conf.check_cfg(package=&#39;libnotifymm-1.0&#39;, args=&#39;--cflags --libs&#39;, uselib_store=&#39;LIBNOTIFYMM&#39;)
 
def build(bld):
 obj = bld.new_task_gen("cxx", "shlib", "node_addon")
 obj.cxxflags = ["-g", "-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE", "-Wall"]
 # This is the name of our extension.
 obj.target = "gtknotify"
 obj.source = "src/node_gtknotify.cpp"
 obj.uselib = [&#39;LIBGTKMM&#39;, &#39;LIBNOTIFYMM&#39;]
登录后复制

现在我们已经准备好要开始构建了,在顶级目录下运行如下命令:

node-waf configure && node-waf build

如果一切正常,我们将得到编译过的扩展,位于:./build/default/gtknotify.node ,来试试:

$ node
> var notif = require(&#39;./build/default/gtknotify.node&#39;);
> n = new notif.notification();
{ icon: &#39;terminal&#39;, title: &#39;Node.js&#39; }
> n.send("Hello World!");
true
登录后复制

上述的代码将在你的屏幕右上方显示一个通知信息。

打成npm包

这是非常酷的, 但是怎样与Node社区分享你的努力的成果呢? 这才是npm主要的用途: 使它更加容易扩展和分发.

打npm的扩展包是非常简单的. 你所要做的就是在你的顶级目录中创建一个包含你的扩展信息的文件package.json :

{
 // 扩展的名称 (不要在名称中包含node 或者 js, 这是隐式关键字).
 // 这是通过require() 导入扩展的名称.
 
 "name" : "notify",
 
 // Version should be http://semver.org/ compliant
 
 "version" : "v0.1.0"
 
 // 这些脚本将在调用npm安装和npm卸载的时候运行.
 
 , "scripts" : {
   "preinstall" : "node-waf configure && node-waf build"
   , "preuninstall" : "rm -rf build/*"
  }
 
 // 这是构建我们扩展的相对路径.
 
 , "main" : "build/default/gtknotify.node"
 
 // 以下是可选字段:
 
 , "description" : "Description of the extension...."
 , "homepage" : "https://github.com/olalonde/node-notify"
 , "author" : {
   "name" : "Olivier Lalonde"
   , "email" : "olalonde@gmail.com"
   , "url" : "http://www.syskall.com/"
  }
 , "repository" : {
   "type" : "git"
   , "url" : "https://github.com/olalonde/node-notify.git"
  }
}
登录后复制

关于package.json 格式的更多细节, 可以通过 npm help json 获取文档. 注意 大多数字段都是可选的.

你现在可以在你的顶级目录中通过运行npm install 来安装你的新的npm包了. 如果一切顺利的话, 应该可以简单的加载你的扩展 var notify = require('你的包名');. 另外一个比较有用的命令式 npm link 通过这个命令你可以创建一个到你开发目录的链接,当你的代码发生变化时不必每次都去安装/卸载.

假设你写了一个很酷的扩展, 你可能想要在中央npm库发布到网上. 首先你要先创建一个账户:

$ npm adduser
登录后复制

下一步, 回到你的根目录编码并且运行:

 $ npm publish
登录后复制

就是这样, 你的包现在已经可以被任何人通过npm install 你的包名命令来安装了.

 

以上是Node.js各种扩展方法代码实例汇总的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

解决win7驱动程序代码28的方法 解决win7驱动程序代码28的方法 Dec 30, 2023 pm 11:55 PM

有的用户在安装设备的时候遇到了错误,提示错误代码28,其实这主要是由于驱动程序的原因,我们只要解决win7驱动程序代码28的问题就可以了,下面就一起来看一下应该怎么来操作吧。win7驱动程序代码28怎么办:首先,我们需要点击屏幕左下角的开始菜单。接着,在弹出的菜单中找到并点击“控制面板”选项。这个选项通常位于菜单的底部或者附近。点击后,系统会自动打开控制面板界面。在控制面板中,我们可以进行各种系统设置和管理操作。这是怀旧大扫除关卡中的第一步,希望对大家有所帮助。然后,我们需要继续操作,进入系统和

蓝屏代码0x0000001怎么办 蓝屏代码0x0000001怎么办 Feb 23, 2024 am 08:09 AM

蓝屏代码0x0000001怎么办蓝屏错误是电脑系统或硬件出现问题时的一种警告机制,代码0x0000001通常表示出现了硬件或驱动程序故障。当用户在使用电脑时突然遇到蓝屏错误,可能会感到惊慌和无措。幸运的是,大多数蓝屏错误都可以通过一些简单的步骤进行排除和处理。本文将为读者介绍一些解决蓝屏错误代码0x0000001的方法。首先,当遇到蓝屏错误时,我们可以尝试重

电脑频繁蓝屏而且每次代码不一样 电脑频繁蓝屏而且每次代码不一样 Jan 06, 2024 pm 10:53 PM

win10系统是一款非常优秀的高智能系统强大的智能可以为用户们带来最好的使用体验,一般正常的情况下用户们的win10系统电脑都不会出现任何的问题!但是在优秀的电脑也难免会出现各种故障最近一直有小伙伴们反应自己的win10系统遇到了频繁蓝屏的问题!今天小编就为大家带来了win10电脑频繁蓝屏不同代码的解决办法让我们一起来看一看吧。电脑频繁蓝屏而且每次代码不一样的解决办法:造成各种故障代码的原因以及解决建议1、0×000000116故障原因:应该是显卡驱动不兼容。解决建议:建议更换厂商原带驱动。2、

解决代码0xc000007b错误 解决代码0xc000007b错误 Feb 18, 2024 pm 07:34 PM

终止代码0xc000007b在使用电脑时,有时会遇到各种各样的问题和错误代码。其中,终止代码最为令人困扰,尤其是终止代码0xc000007b。这个代码表示某个应用程序无法正常启动,给用户带来了不便。首先,我们来了解一下终止代码0xc000007b的含义。这个代码是Windows操作系统的错误代码,通常发生在32位应用程序尝试在64位操作系统上运行时。它表示应

详解0x0000007f蓝屏代码的原因和解决方案 详解0x0000007f蓝屏代码的原因和解决方案 Dec 25, 2023 pm 02:19 PM

蓝屏是我们在系统使用的时候经常会碰到的问题,根据错误代码的不同,会有很多中不一样的原因和解决方法。例如我们在使用时遇到stop:0x0000007f的问题,可能是硬件或软件错误,下面就跟着小编一起来看看解决方法吧。0x000000c5蓝屏代码原因:答:内存、CPU、显卡突然超频,或软件运行错误。解决方法一:1、在开机时候不断按F8进入,选择安全模式,回车进入。2、进入到安全模式后,按win+r打开运行窗口,输入cmd,回车。3、在命令提示窗口,输入“chkdsk/f/r”,回车,然后按y键。4、

GE通用远程代码可在任何设备上编程 GE通用远程代码可在任何设备上编程 Mar 02, 2024 pm 01:58 PM

如果您需要远程编程任何设备,这篇文章会给您带来帮助。我们将分享编程任何设备的顶级GE通用远程代码。通用电气的遥控器是什么?GEUniversalRemote是一款遥控器,可用于控制多个设备,如智能电视、LG、Vizio、索尼、蓝光、DVD、DVR、Roku、AppleTV、流媒体播放器等。GEUniversal遥控器有各种型号,具有不同的功能和功能。GEUniversalRemote最多可以控制四台设备。顶级通用遥控器代码,可在任何设备上编程GE遥控器配备一组代码,使其能够与不同设备相配合。您可

蓝屏代码0x000000d1代表什么问题? 蓝屏代码0x000000d1代表什么问题? Feb 18, 2024 pm 01:35 PM

0x000000d1蓝屏代码是什么意思近年来,随着计算机的普及和网络的快速发展,操作系统的稳定性和安全性问题也日益凸显。一个常见的问题是蓝屏错误,代码0x000000d1是其中之一。蓝屏错误,或称为“蓝屏死机”,是当计算机遇到严重系统故障时发生的一种情况。当系统无法从错误中恢复时,Windows操作系统会显示一个蓝色的屏幕,并在屏幕上显示错误代码。这些错误代

学习Python绘图的速成指南:绘制冰墩墩的代码实例 学习Python绘图的速成指南:绘制冰墩墩的代码实例 Jan 13, 2024 pm 02:00 PM

快速上手Python绘图:画出冰墩墩的代码示例Python是一种简单易学且功能强大的编程语言,通过使用Python的绘图库,我们可以轻松地实现各种绘图需求。在本篇文章中,我们将使用Python的绘图库matplotlib来画出冰墩墩的简单图形。冰墩墩是一只拥有可爱形象的熊猫,非常受小朋友们的喜爱。首先,我们需要安装matplotlib库。你可以通过在终端运行

See all articles