SlideShare une entreprise Scribd logo
1  sur  92
Télécharger pour lire hors ligne
How To Write
Node.js Module

     Fred Chien
Warning
  警告!
今天會很悶
 !!!!!!!!!!!!!!!!!!!!!!!!!!!
我盡量講的
 !!!!!!!!!!!!!!!!!!!!!!!!!!!
WHO AM I ?
   我是誰?
Fred Chien
  錢逢祥
 永遠的大四生
Fred Chien
  錢逢祥
 Mandice CEO
fred-zone.blogspot.com

    cfsghost@gmail.com
people.linux.org.tw/~fred/

     cfsghost@gmail.com
Topics.
Node.js Modules
 NPM Registry
C/C++ Addons
What is
Node.js Module ?
     Node.js 模組?
npm install <something>

   You Must Be Familiar With
You Can Write Module In
  C/C++ & JavaScript
你可以用 C/C++ 或 JavaScript 寫模組
How to
Load Module
   載入模組
Load Global Module

Example:

var MyModule = require('mymodule');

Node.js will searching in the following location:

 ● ./node_modules
 ● ../node_modules
 ● $HOME/.node_modules
 ● $HOME/.node_libraries
 ● $PREFIX/lib/node
Load Local Module

Load the module in the same directory:

var MyModule = require('./mymodule');

Or

var MyModule = require('./mymodule.js');
Write The First
Node.js Module
   動手寫第一個模組
The First Module Example

module.exports = function() {

     console.log('Hello World!');

};
require()     module.exports
   Bridge between app and module
Implement a Class in Module

module.exports = function() {
 var self = this;
 this.counter = 0;

     this.pump = function() {
        self.counter++;
     };

};
More JavaScript Styles

var Pumper = module.exports = function() {
   this.counter = 0;
};

Pumper.prototype.pump = function() {
   Pumper.counter++;
};
Export Objects and Constants

var Pumper = module.exports.Pumper = function() {
   this.counter = 0;
};

Pumper.prototype.pump = function() {
   Pumper.counter++;
};

module.exports.Pumper1 = function() { ... };
module.exports.Pumper2 = function() { ... };
module.exports.Birthday = 714;
index.js
     &
index.node
./example/index.js
var ex = require('./example');

如果是目錄,預設讀取 index.js 或 index.node
Let's
Publish Your Module
  釋出!與你的朋友分享成果吧!
NPM Registry
NPM = Node Package Manager
NPM Registry
    npmjs.org
Steps to Publish Package

     打包並上傳模組的步驟
1. Get NPM Account

2. Generate package.json

3. To Upload Package
Get NPM Account
   註冊 NPM 帳號
npm adduser
 新增 NPM 帳號
Initialize Package
   初始化你的套件
npm init
產生 package.json
Run "npm init"

$ npm init
Package name: (demo)
Description: Hello
Package version: (0.0.0)
Project homepage: (none)
Project git repository: (none)
Author name: Fred
Author email: (none) cfsghost@gmail.com
Author url: (none)
Main module/entry point: (none)
Test command: (none)
We got package.json
{
    "author": "Fred <cfsghost@gmail.com>",
    "name": "demo",
    "description": "Hello",
    "version": "0.0.0",
    "repository": {
      "url": ""
    },
    "dependencies": {},
    "devDependencies": {},
    "optionalDependencies": {},
    "engines": {
      "node": "*"
    }
}
Normal Structure of Package

● index.js
● package.json
● README (README.md)
● LICENSE
● lib/hello1.js
● lib/hello2.js
● tests/test1.js
● tests/test2.js
I don't want to use index.js !
    Change Entry Point
        我想改變進入啟始點
Add "main" Property To
    package.json
After Change Entry Point

● demo.js
● package.json
● README (README.md)
● LICENSE
● lib/hello1.js
● lib/hello2.js
● tests/test1.js
● tests/test2.js
require()

      Open Directory

        package.json

  index.js            Another
index.node           Entry Point
Upload Package
上傳套件!公開於世!
npm publish .
發佈在 '.' 之下的 Package
Piece of cake!
  開發模組一點都不難嘛!
進階
Advanced Topic
How to
Write C/C++ Addons
    如何使用 C/C++ 寫模組
Development Environment



1. GCC (used to compile)

2. Python (For build script)
Write The First
C/C++ Addon
動手寫第一個 C/C++ 模組
C/C++ Addon Example
#include <node.h>
#include <v8.h>

using namespace v8;

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

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

NODE_MODULE(hello, init);
C/C++ Addon Example
#include <node.h>
#include <v8.h>

using namespace v8;                                    module.exports
Handle<Value> Method(const Arguments& args) {
  HandleScope scope;
  return scope.Close(String::New("world"));
}

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

NODE_MODULE(hello, init);
C/C++ Addon Example
#include <node.h>
#include <v8.h>

using namespace v8;

Handle<Value> Method(const Arguments& args) {
  HandleScope scope;                               function() {
  return scope.Close(String::New("world"));          return 'world';
}                                                  }
void init(Handle<Object> target) {
  target->Set(String::NewSymbol("hello"),
      FunctionTemplate::New(Method)->GetFunction());
}

NODE_MODULE(hello, init);
Compare with JavaScript Version

var target = module.exports;

target['hello'] = function() {
   return 'world!';
};
Or

module.exports.hello = function() {
   return 'world!';
};
C/C++ Addon Example
#include <node.h>
#include <v8.h>

using namespace v8;

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

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

NODE_MODULE(hello, init);
C/C++ Addon Example
#include <node.h>
#include <v8.h>

using namespace v8;

Handle<Value> Method(const Arguments& args) {      v8::String Class
  HandleScope scope;
  return scope.Close(String::New("world"))
}

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

NODE_MODULE(hello, init);
C/C++ Addon Example
#include <node.h>
#include <v8.h>

using namespace v8;

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

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

NODE_MODULE(hello, init);
HandleScope

● Determine Lifetime of handles
● Often created at the beginning of a function call
● Deleted after function return
   ○ scope.Close(<Handle>) to avoid handle being
     deleted by Garbage Collection
Compile The First
C/C++ Addon
動手編譯第一個 C/C++ 模組
You Must Have
  wscript
你必需有一個 wscript
wscript
srcdir = '.'
blddir = 'build'
VERSION = '0.0.1'

def set_options(opt):
  opt.tool_options('compiler_cxx')

def configure(conf):
  conf.check_tool('compiler_cxx')
  conf.check_tool('node_addon')

def build(bld):
  obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
  obj.target = 'hello'
  obj.source = 'hello.cc'
Structure of Package

● package.json
● README (README.md)
● LICENSE
● wscript
● hello.cc
node-waf configure build
  使用 node-waf 編譯我們的程式!
Generated
build/Release/hello.node
     編譯產生 Binary 檔案
Write A Test Case
var Hello = require('./build/Release/hello.node');

console.log(Hello.hello());
Don't Forget This
Before Upload Package
  上傳模組前要修改 package.json
Add "scripts" Property To
     package.json
Modify package.json

{
    "name": "hello",
    ...
    "main": "build/Release/hello.node",
    "scripts": {
        "install": "node-waf configure build"
    }
}
npm publish .
發佈我們的 C/C++ Addon!
開發 C/C++ Addon 的竅門
人腦內建:

                   1. C/C++ Compiler
                   2. JavaScript Compiler
                   3. Virtual Machine




C/C++ JavaScript
進階 Part 2
  Advanced Topic Part 2
Arguments
   參數
Assume We Have Parameters
var Hello = require('./build/Release/hello.node');

console.log(Hello.hello('String', 101, 4.0, true));
Get Arguments In C/C++
Handle<Value> Method(const Arguments& args) {
  HandleScope scope;

    printf("%dn", args.Length());

    if (args[0]->IsString() && args[1]->IsNumber() &&
        args[2]->IsNumber() && args[3]->IsBoolean()) {

        printf("%s %d %f %dn",
           *String::AsciiValue(args[0]->ToString()),
           args[1]->ToInteger()->Value(),
           args[2]->NumberValue(),
           args[3]->ToBoolean());
    }

    return scope.Close(String::New("world"))
}
如果以上能理解
進一步討論 C/C++ 與 JavaScript 的關係
Understanding of Types
    了解 JavaScript 資料型態
Types In JavaScript
var string = 'Hello String';
var integer = 714;
var float = 11.15;
var boolean = false;
var obj = {};
var arr = [];
var func = function() {};
Methods
* Assume Local<Value> data;
Type Name      Check Type                              Get Value
                              *String::Utf8Value(data->ToString())
   String       IsString()    *String::AsciiValue(data->ToString())
                              data->ToInteger()->Value()
                              data->ToInt32()->Value()
               IsNumber()     data->ToUint32()->Value()
  Integer        IsInt32()    data->IntegerValue()
                IsUint32()    data->Uint32Value()
                              data->Int32Value()

   Float       IsNumber()     data->NumbeValue()
  Boolean      IsBoolean()    data->ToBoolean()->Value()

Object/Array    IsObject()    data->ToObject()
                              Local<Function> cb = Local<Function>::Cast(data);
                              const unsigned argc = 1;
                              Local<Value> argv[argc] = {
 Function      IsFunction()       Local<Value>::New(String::New("hello world"))
                              };
                              cb->Call(Context::GetCurrent()->Global(), argc, argv);
Class
 參數
Create Class Instance
var Hello = require('./build/Release/hello.node');

var hello = new Hello.Hello();

console.log(hello.method());
Class Constructor in JavaScript

var Hello = function() {
   /* Constructor */
};
module.exports.Hello = Hello;

/* Prototype Method */
Hello.prototype.myMethod = function() {
   return 'World';
};
Write a Constructor
#include <node.h>
#include <v8.h>

using namespace v8;

Handle<Value> MyConstructor(const Arguments& args) {
  HandleScope scope;

    return args.This();
}

void init(Handle<Object> target) {
  Local<FunctionTemplate> tpl = FunctionTemplate::New(MyConstructor);

    target->Set(String::NewSymbol("Hello"),
      tpl->GetFunction());
}

NODE_MODULE(hello, init);
Write a Prototype Method
...

Handle<Value> MyMethod(const Arguments& args) {
  HandleScope scope;
  return scope.Close(String::New("World"));
}

void init(Handle<Object> target) {
  Local<FunctionTemplate> tpl = FunctionTemplate::New(MyConstructor);

      tpl->InstanceTemplate()->SetInternalFieldCount(1);
      NODE_SET_PROTOTYPE_METHOD(tpl, "myMethod", MyMethod);

      target->Set(String::NewSymbol("Hello"),
        tpl->GetFunction());
}

NODE_MODULE(hello, init);
一切只是開端
It's beginning to do
進階 Part 3
  To Be Continued...
這真的是進階
I am NOT Kidding You
Wrapping C++ Object
將 C++ Class 包裝成 JavaScript Class
Create JavaScipt Instance
        In C/C++
  Do "new Hello.Hello()" in C/C++
See You Next Time
 下次有機會見面再來討論吧!
喔!差點忘了
 火力展示
Question?
  歡迎發問
Thanks
  感

Contenu connexe

Tendances

Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 

Tendances (20)

introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
History & Practices for UniRx(EN)
History & Practices for UniRx(EN)History & Practices for UniRx(EN)
History & Practices for UniRx(EN)
 
Node ppt
Node pptNode ppt
Node ppt
 
NodeJS
NodeJSNodeJS
NodeJS
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Getting started with developing Nodejs
Getting started with developing NodejsGetting started with developing Nodejs
Getting started with developing Nodejs
 
node ffi
node ffinode ffi
node ffi
 
Infrastructure as code - Python Saati #36
Infrastructure as code - Python Saati #36Infrastructure as code - Python Saati #36
Infrastructure as code - Python Saati #36
 
Philly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSPhilly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJS
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Supercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamicSupercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamic
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 

En vedette

我編譯故我在:誰說 Node.js 程式不能編成 binary
我編譯故我在:誰說 Node.js 程式不能編成 binary我編譯故我在:誰說 Node.js 程式不能編成 binary
我編譯故我在:誰說 Node.js 程式不能編成 binary
Fred Chien
 

En vedette (20)

Let s Enjoy Node.js
Let s Enjoy Node.jsLet s Enjoy Node.js
Let s Enjoy Node.js
 
用最潮的 Java script 盡情開發 kde qt 程式
用最潮的 Java script 盡情開發 kde qt 程式用最潮的 Java script 盡情開發 kde qt 程式
用最潮的 Java script 盡情開發 kde qt 程式
 
Node.js 進攻桌面開發
Node.js 進攻桌面開發Node.js 進攻桌面開發
Node.js 進攻桌面開發
 
Koa 正在等一個人
Koa 正在等一個人Koa 正在等一個人
Koa 正在等一個人
 
Stem OS Proposal
Stem OS ProposalStem OS Proposal
Stem OS Proposal
 
OwaNEXT
OwaNEXTOwaNEXT
OwaNEXT
 
Non-MVC Web Framework
Non-MVC Web FrameworkNon-MVC Web Framework
Non-MVC Web Framework
 
App house
App houseApp house
App house
 
軟體人甘苦談
軟體人甘苦談軟體人甘苦談
軟體人甘苦談
 
QML + Node.js
QML + Node.jsQML + Node.js
QML + Node.js
 
Java script 全面逆襲!使用 node.js 打造桌面環境!
Java script 全面逆襲!使用 node.js 打造桌面環境!Java script 全面逆襲!使用 node.js 打造桌面環境!
Java script 全面逆襲!使用 node.js 打造桌面環境!
 
MakerBoard: MT7688 Emulator
MakerBoard: MT7688 EmulatorMakerBoard: MT7688 Emulator
MakerBoard: MT7688 Emulator
 
我編譯故我在:誰說 Node.js 程式不能編成 binary
我編譯故我在:誰說 Node.js 程式不能編成 binary我編譯故我在:誰說 Node.js 程式不能編成 binary
我編譯故我在:誰說 Node.js 程式不能編成 binary
 
Brig:Node.js + QML 華麗大冒險
Brig:Node.js + QML 華麗大冒險Brig:Node.js + QML 華麗大冒險
Brig:Node.js + QML 華麗大冒險
 
超酷炫科幻 UI:QML 入門
超酷炫科幻 UI:QML 入門超酷炫科幻 UI:QML 入門
超酷炫科幻 UI:QML 入門
 
Использовании TypeScript для Node.js
Использовании TypeScript для Node.jsИспользовании TypeScript для Node.js
Использовании TypeScript для Node.js
 
Yarn
YarnYarn
Yarn
 
Nodeconf npm 2011
Nodeconf npm 2011Nodeconf npm 2011
Nodeconf npm 2011
 
Npm: beyond 'npm i'
Npm: beyond 'npm i'Npm: beyond 'npm i'
Npm: beyond 'npm i'
 
Yarn – der neue Package Manager von Facebook
Yarn – der neue Package Manager von FacebookYarn – der neue Package Manager von Facebook
Yarn – der neue Package Manager von Facebook
 

Similaire à How to Write Node.js Module

CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
維佋 唐
 

Similaire à How to Write Node.js Module (20)

Objective c intro (1)
Objective c intro (1)Objective c intro (1)
Objective c intro (1)
 
Day 1
Day 1Day 1
Day 1
 
Book
BookBook
Book
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
 
The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196
 
Getting Input from User
Getting Input from UserGetting Input from User
Getting Input from User
 
Unit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptxUnit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptx
 
The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184
 
Android ndk
Android ndkAndroid ndk
Android ndk
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Guide to Node.js: Basic to Advanced
Guide to Node.js: Basic to AdvancedGuide to Node.js: Basic to Advanced
Guide to Node.js: Basic to Advanced
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Dernier (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

How to Write Node.js Module

  • 1. How To Write Node.js Module Fred Chien
  • 5. WHO AM I ? 我是誰?
  • 6. Fred Chien 錢逢祥 永遠的大四生
  • 7. Fred Chien 錢逢祥 Mandice CEO
  • 8. fred-zone.blogspot.com cfsghost@gmail.com
  • 9. people.linux.org.tw/~fred/ cfsghost@gmail.com
  • 10. Topics. Node.js Modules NPM Registry C/C++ Addons
  • 11. What is Node.js Module ? Node.js 模組?
  • 12. npm install <something> You Must Be Familiar With
  • 13.
  • 14. You Can Write Module In C/C++ & JavaScript 你可以用 C/C++ 或 JavaScript 寫模組
  • 15. How to Load Module 載入模組
  • 16. Load Global Module Example: var MyModule = require('mymodule'); Node.js will searching in the following location: ● ./node_modules ● ../node_modules ● $HOME/.node_modules ● $HOME/.node_libraries ● $PREFIX/lib/node
  • 17. Load Local Module Load the module in the same directory: var MyModule = require('./mymodule'); Or var MyModule = require('./mymodule.js');
  • 18. Write The First Node.js Module 動手寫第一個模組
  • 19. The First Module Example module.exports = function() { console.log('Hello World!'); };
  • 20. require() module.exports Bridge between app and module
  • 21. Implement a Class in Module module.exports = function() { var self = this; this.counter = 0; this.pump = function() { self.counter++; }; };
  • 22. More JavaScript Styles var Pumper = module.exports = function() { this.counter = 0; }; Pumper.prototype.pump = function() { Pumper.counter++; };
  • 23. Export Objects and Constants var Pumper = module.exports.Pumper = function() { this.counter = 0; }; Pumper.prototype.pump = function() { Pumper.counter++; }; module.exports.Pumper1 = function() { ... }; module.exports.Pumper2 = function() { ... }; module.exports.Birthday = 714;
  • 24. index.js & index.node
  • 25. ./example/index.js var ex = require('./example'); 如果是目錄,預設讀取 index.js 或 index.node
  • 26. Let's Publish Your Module 釋出!與你的朋友分享成果吧!
  • 27. NPM Registry NPM = Node Package Manager
  • 28. NPM Registry npmjs.org
  • 29. Steps to Publish Package 打包並上傳模組的步驟
  • 30. 1. Get NPM Account 2. Generate package.json 3. To Upload Package
  • 31. Get NPM Account 註冊 NPM 帳號
  • 32. npm adduser 新增 NPM 帳號
  • 33. Initialize Package 初始化你的套件
  • 35. Run "npm init" $ npm init Package name: (demo) Description: Hello Package version: (0.0.0) Project homepage: (none) Project git repository: (none) Author name: Fred Author email: (none) cfsghost@gmail.com Author url: (none) Main module/entry point: (none) Test command: (none)
  • 36. We got package.json { "author": "Fred <cfsghost@gmail.com>", "name": "demo", "description": "Hello", "version": "0.0.0", "repository": { "url": "" }, "dependencies": {}, "devDependencies": {}, "optionalDependencies": {}, "engines": { "node": "*" } }
  • 37. Normal Structure of Package ● index.js ● package.json ● README (README.md) ● LICENSE ● lib/hello1.js ● lib/hello2.js ● tests/test1.js ● tests/test2.js
  • 38. I don't want to use index.js ! Change Entry Point 我想改變進入啟始點
  • 39. Add "main" Property To package.json
  • 40. After Change Entry Point ● demo.js ● package.json ● README (README.md) ● LICENSE ● lib/hello1.js ● lib/hello2.js ● tests/test1.js ● tests/test2.js
  • 41. require() Open Directory package.json index.js Another index.node Entry Point
  • 43. npm publish . 發佈在 '.' 之下的 Package
  • 44. Piece of cake! 開發模組一點都不難嘛!
  • 46. How to Write C/C++ Addons 如何使用 C/C++ 寫模組
  • 47. Development Environment 1. GCC (used to compile) 2. Python (For build script)
  • 48. Write The First C/C++ Addon 動手寫第一個 C/C++ 模組
  • 49. C/C++ Addon Example #include <node.h> #include <v8.h> using namespace v8; Handle<Value> Method(const Arguments& args) { HandleScope scope; return scope.Close(String::New("world")); } void init(Handle<Object> target) { target->Set(String::NewSymbol("hello"), FunctionTemplate::New(Method)->GetFunction()); } NODE_MODULE(hello, init);
  • 50. C/C++ Addon Example #include <node.h> #include <v8.h> using namespace v8; module.exports Handle<Value> Method(const Arguments& args) { HandleScope scope; return scope.Close(String::New("world")); } void init(Handle<Object> target) { target->Set(String::NewSymbol("hello"), FunctionTemplate::New(Method)->GetFunction()); } NODE_MODULE(hello, init);
  • 51. C/C++ Addon Example #include <node.h> #include <v8.h> using namespace v8; Handle<Value> Method(const Arguments& args) { HandleScope scope; function() { return scope.Close(String::New("world")); return 'world'; } } void init(Handle<Object> target) { target->Set(String::NewSymbol("hello"), FunctionTemplate::New(Method)->GetFunction()); } NODE_MODULE(hello, init);
  • 52. Compare with JavaScript Version var target = module.exports; target['hello'] = function() { return 'world!'; }; Or module.exports.hello = function() { return 'world!'; };
  • 53. C/C++ Addon Example #include <node.h> #include <v8.h> using namespace v8; Handle<Value> Method(const Arguments& args) { HandleScope scope; return scope.Close(String::New("world")) } void init(Handle<Object> target) { target->Set(String::NewSymbol("hello"), FunctionTemplate::New(Method)->GetFunction()); } NODE_MODULE(hello, init);
  • 54. C/C++ Addon Example #include <node.h> #include <v8.h> using namespace v8; Handle<Value> Method(const Arguments& args) { v8::String Class HandleScope scope; return scope.Close(String::New("world")) } void init(Handle<Object> target) { target->Set(String::NewSymbol("hello"), FunctionTemplate::New(Method)->GetFunction()); } NODE_MODULE(hello, init);
  • 55.
  • 56. C/C++ Addon Example #include <node.h> #include <v8.h> using namespace v8; Handle<Value> Method(const Arguments& args) { HandleScope scope; return scope.Close(String::New("world")) } void init(Handle<Object> target) { target->Set(String::NewSymbol("hello"), FunctionTemplate::New(Method)->GetFunction()); } NODE_MODULE(hello, init);
  • 57. HandleScope ● Determine Lifetime of handles ● Often created at the beginning of a function call ● Deleted after function return ○ scope.Close(<Handle>) to avoid handle being deleted by Garbage Collection
  • 58. Compile The First C/C++ Addon 動手編譯第一個 C/C++ 模組
  • 59. You Must Have wscript 你必需有一個 wscript
  • 60. wscript srcdir = '.' blddir = 'build' VERSION = '0.0.1' def set_options(opt): opt.tool_options('compiler_cxx') def configure(conf): conf.check_tool('compiler_cxx') conf.check_tool('node_addon') def build(bld): obj = bld.new_task_gen('cxx', 'shlib', 'node_addon') obj.target = 'hello' obj.source = 'hello.cc'
  • 61. Structure of Package ● package.json ● README (README.md) ● LICENSE ● wscript ● hello.cc
  • 62. node-waf configure build 使用 node-waf 編譯我們的程式!
  • 63. Generated build/Release/hello.node 編譯產生 Binary 檔案
  • 64. Write A Test Case var Hello = require('./build/Release/hello.node'); console.log(Hello.hello());
  • 65. Don't Forget This Before Upload Package 上傳模組前要修改 package.json
  • 66. Add "scripts" Property To package.json
  • 67. Modify package.json { "name": "hello", ... "main": "build/Release/hello.node", "scripts": { "install": "node-waf configure build" } }
  • 69. 開發 C/C++ Addon 的竅門
  • 70. 人腦內建: 1. C/C++ Compiler 2. JavaScript Compiler 3. Virtual Machine C/C++ JavaScript
  • 71. 進階 Part 2 Advanced Topic Part 2
  • 72. Arguments 參數
  • 73. Assume We Have Parameters var Hello = require('./build/Release/hello.node'); console.log(Hello.hello('String', 101, 4.0, true));
  • 74. Get Arguments In C/C++ Handle<Value> Method(const Arguments& args) { HandleScope scope; printf("%dn", args.Length()); if (args[0]->IsString() && args[1]->IsNumber() && args[2]->IsNumber() && args[3]->IsBoolean()) { printf("%s %d %f %dn", *String::AsciiValue(args[0]->ToString()), args[1]->ToInteger()->Value(), args[2]->NumberValue(), args[3]->ToBoolean()); } return scope.Close(String::New("world")) }
  • 76. Understanding of Types 了解 JavaScript 資料型態
  • 77. Types In JavaScript var string = 'Hello String'; var integer = 714; var float = 11.15; var boolean = false; var obj = {}; var arr = []; var func = function() {};
  • 78. Methods * Assume Local<Value> data; Type Name Check Type Get Value *String::Utf8Value(data->ToString()) String IsString() *String::AsciiValue(data->ToString()) data->ToInteger()->Value() data->ToInt32()->Value() IsNumber() data->ToUint32()->Value() Integer IsInt32() data->IntegerValue() IsUint32() data->Uint32Value() data->Int32Value() Float IsNumber() data->NumbeValue() Boolean IsBoolean() data->ToBoolean()->Value() Object/Array IsObject() data->ToObject() Local<Function> cb = Local<Function>::Cast(data); const unsigned argc = 1; Local<Value> argv[argc] = { Function IsFunction() Local<Value>::New(String::New("hello world")) }; cb->Call(Context::GetCurrent()->Global(), argc, argv);
  • 80. Create Class Instance var Hello = require('./build/Release/hello.node'); var hello = new Hello.Hello(); console.log(hello.method());
  • 81. Class Constructor in JavaScript var Hello = function() { /* Constructor */ }; module.exports.Hello = Hello; /* Prototype Method */ Hello.prototype.myMethod = function() { return 'World'; };
  • 82. Write a Constructor #include <node.h> #include <v8.h> using namespace v8; Handle<Value> MyConstructor(const Arguments& args) { HandleScope scope; return args.This(); } void init(Handle<Object> target) { Local<FunctionTemplate> tpl = FunctionTemplate::New(MyConstructor); target->Set(String::NewSymbol("Hello"), tpl->GetFunction()); } NODE_MODULE(hello, init);
  • 83. Write a Prototype Method ... Handle<Value> MyMethod(const Arguments& args) { HandleScope scope; return scope.Close(String::New("World")); } void init(Handle<Object> target) { Local<FunctionTemplate> tpl = FunctionTemplate::New(MyConstructor); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "myMethod", MyMethod); target->Set(String::NewSymbol("Hello"), tpl->GetFunction()); } NODE_MODULE(hello, init);
  • 85. 進階 Part 3 To Be Continued...
  • 87. Wrapping C++ Object 將 C++ Class 包裝成 JavaScript Class
  • 88. Create JavaScipt Instance In C/C++ Do "new Hello.Hello()" in C/C++
  • 89. See You Next Time 下次有機會見面再來討論吧!