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'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
Constructor メソッド: New()
New() メソッドは、カスタム クラス (Gtknotify オブジェクト) の新しいインスタンスを作成し、いくつかの初期値を設定して、オブジェクトの JavaScript 処理を返します。これは、new 演算子を使用してコンストラクターを呼び出す JavaScript の予期される動作です。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 は、waf の基本パッケージである Node 拡張機能をコンパイルするために使用されるビルド ツールです。ビルド プロセスは、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='gtkmm-2.4', args='--cflags --libs', uselib_store='LIBGTKMM') conf.check_cfg(package='libnotifymm-1.0', args='--cflags --libs', uselib_store='LIBNOTIFYMM') 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 = ['LIBGTKMM', 'LIBNOTIFYMM']これでビルドを開始する準備ができました。最上位ディレクトリで次のコマンドを実行します: node-waf configure && node-waf build すべてがうまくいけば、次の場所にあるコンパイルされた拡張機能を取得します。 ./ build/default/gtknotify.node、試してみてください:
$ node > var notif = require('./build/default/gtknotify.node'); > n = new notif.notification(); { icon: 'terminal', title: 'Node.js' } > 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 Documentation. ほとんどのフィールドはオプションであることに注意してください。
すべてがうまくいけば、拡張機能 var Notice = をロードするだけで、新しい npm パッケージをインストールできるようになります。 require('your package name'); もう 1 つの便利な命令型 npm リンク。このコマンドを使用すると、コードを変更するたびにそれをインストールする必要がなくなります。クールな拡張機能を作成し、中央の npm リポジトリでオンラインで公開したいとします。まず、アカウントを作成します:
$ npm adduser
次に、ルート コーディング ディレクトリに戻り、次を実行します。 $ npm publish
これで、パッケージ名を指定して npm install コマンドを使用すると、誰でもパッケージをインストールできるようになります。
以上がNode.jsの各種拡張メソッドのコード例まとめの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

PythonとJavaScriptの将来の傾向には、1。Pythonが科学コンピューティングの分野での位置を統合し、AI、2。JavaScriptはWebテクノロジーの開発を促進します。どちらもそれぞれのフィールドでアプリケーションシナリオを拡大し続け、パフォーマンスをより多くのブレークスルーを行います。

開発環境におけるPythonとJavaScriptの両方の選択が重要です。 1)Pythonの開発環境には、Pycharm、Jupyternotebook、Anacondaが含まれます。これらは、データサイエンスと迅速なプロトタイピングに適しています。 2)JavaScriptの開発環境には、フロントエンドおよびバックエンド開発に適したnode.js、vscode、およびwebpackが含まれます。プロジェクトのニーズに応じて適切なツールを選択すると、開発効率とプロジェクトの成功率が向上する可能性があります。

はい、JavaScriptのエンジンコアはCで記述されています。1)C言語は、JavaScriptエンジンの開発に適した効率的なパフォーマンスと基礎となる制御を提供します。 2)V8エンジンを例にとると、そのコアはCで記述され、Cの効率とオブジェクト指向の特性を組み合わせて書かれています。3)JavaScriptエンジンの作業原理には、解析、コンパイル、実行が含まれ、C言語はこれらのプロセスで重要な役割を果たします。

JavaScriptは、Webページのインタラクティブ性とダイナミズムを向上させるため、現代のWebサイトの中心にあります。 1)ページを更新せずにコンテンツを変更できます。2)Domapiを介してWebページを操作する、3)アニメーションやドラッグアンドドロップなどの複雑なインタラクティブ効果、4)ユーザーエクスペリエンスを改善するためのパフォーマンスとベストプラクティスを最適化します。

CおよびJavaScriptは、WebAssemblyを介して相互運用性を実現します。 1)CコードはWebAssemblyモジュールにコンパイルされ、JavaScript環境に導入され、コンピューティングパワーが強化されます。 2)ゲーム開発では、Cは物理エンジンとグラフィックスレンダリングを処理し、JavaScriptはゲームロジックとユーザーインターフェイスを担当します。

JavaScriptは、Webサイト、モバイルアプリケーション、デスクトップアプリケーション、サーバー側のプログラミングで広く使用されています。 1)Webサイト開発では、JavaScriptはHTMLおよびCSSと一緒にDOMを運用して、JQueryやReactなどのフレームワークをサポートします。 2)ReactNativeおよびIonicを通じて、JavaScriptはクロスプラットフォームモバイルアプリケーションを開発するために使用されます。 3)電子フレームワークにより、JavaScriptはデスクトップアプリケーションを構築できます。 4)node.jsを使用すると、JavaScriptがサーバー側で実行され、高い並行リクエストをサポートします。

Pythonはデータサイエンスと自動化により適していますが、JavaScriptはフロントエンドとフルスタックの開発により適しています。 1. Pythonは、データ処理とモデリングのためにNumpyやPandasなどのライブラリを使用して、データサイエンスと機械学習でうまく機能します。 2。Pythonは、自動化とスクリプトにおいて簡潔で効率的です。 3. JavaScriptはフロントエンド開発に不可欠であり、動的なWebページと単一ページアプリケーションの構築に使用されます。 4. JavaScriptは、node.jsを通じてバックエンド開発において役割を果たし、フルスタック開発をサポートします。

CとCは、主に通訳者とJITコンパイラを実装するために使用されるJavaScriptエンジンで重要な役割を果たします。 1)cは、JavaScriptソースコードを解析し、抽象的な構文ツリーを生成するために使用されます。 2)Cは、Bytecodeの生成と実行を担当します。 3)Cは、JITコンパイラを実装し、実行時にホットスポットコードを最適化およびコンパイルし、JavaScriptの実行効率を大幅に改善します。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

mPDF
mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

ホットトピック









