how to write node.js module

92
How To Write Node.js Module How To Write Node.js Module Fred Chien

Upload: fred-chien

Post on 25-Dec-2014

10.418 views

Category:

Technology


1 download

DESCRIPTION

Explain how to writie a Node.js Module, C/C++ Addon and upload modules to NPM registry.

TRANSCRIPT

Page 1: How to Write Node.js Module

How To WriteNode.js Module

How To WriteNode.js Module

Fred Chien

Page 2: How to Write Node.js Module

Warning警告!

Page 3: How to Write Node.js Module

今天會很悶!!!!!!!!!!!!!!!!!!!!!!!!!!!

Page 4: How to Write Node.js Module

我盡量講的!!!!!!!!!!!!!!!!!!!!!!!!!!!

Page 5: How to Write Node.js Module

WHO AM I ?我是誰?

Page 6: How to Write Node.js Module

Fred Chien錢逢祥

永遠的大四生

Page 7: How to Write Node.js Module

Fred Chien錢逢祥

Mandice CEO

Page 8: How to Write Node.js Module

fred-zone.blogspot.com

[email protected]

Page 9: How to Write Node.js Module

people.linux.org.tw/~fred/

[email protected]

Page 10: How to Write Node.js Module

Topics.

Node.js Modules

NPM Registry

C/C++ Addons

Page 11: How to Write Node.js Module

What isNode.js Module ?

Node.js 模組?

Page 12: How to Write Node.js Module

npm install <something>

You Must Be Familiar With

Page 13: How to Write Node.js Module
Page 14: How to Write Node.js Module

You Can Write Module In C/C++ & JavaScript

你可以用 C/C++ 或 JavaScript 寫模組

Page 15: How to Write Node.js Module

How toLoad Module

載入模組

Page 16: How to Write Node.js 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

Page 17: How to Write Node.js Module

Load Local Module

Load the module in the same directory:

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

Or

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

Page 18: How to Write Node.js Module

Write The FirstNode.js Module

動手寫第一個模組

Page 19: How to Write Node.js Module

The First Module Example

module.exports = function() {

console.log('Hello World!');

};

Page 20: How to Write Node.js Module

require() module.exportsBridge between app and module

Page 21: How to Write Node.js Module

Implement a Class in Module

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

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

};

Page 22: How to Write Node.js Module

More JavaScript Styles

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

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

Page 23: How to Write Node.js Module

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;

Page 24: How to Write Node.js Module

index.js&

index.node

Page 25: How to Write Node.js Module

./example/index.js

var ex = require('./example');

如果是目錄,預設讀取 index.js 或 index.node

Page 26: How to Write Node.js Module

Let'sPublish Your Module

釋出!與你的朋友分享成果吧!

Page 27: How to Write Node.js Module

NPM RegistryNPM = Node Package Manager

Page 28: How to Write Node.js Module

NPM Registrynpmjs.org

Page 29: How to Write Node.js Module

Steps to Publish Package

打包並上傳模組的步驟

Page 30: How to Write Node.js Module

1.Get NPM Account

2.Generate package.json

3.To Upload Package

Page 31: How to Write Node.js Module

Get NPM Account

註冊 NPM 帳號

Page 32: How to Write Node.js Module

npm adduser

新增 NPM 帳號

Page 33: How to Write Node.js Module

Initialize Package

初始化你的套件

Page 34: How to Write Node.js Module

npm init

產生 package.json

Page 35: How to Write Node.js Module

Run "npm init"

$ npm initPackage name: (demo) Description: HelloPackage version: (0.0.0) Project homepage: (none) Project git repository: (none)Author name: FredAuthor email: (none) [email protected] url: (none) Main module/entry point: (none) Test command: (none)

Page 36: How to Write Node.js Module

We got package.json

{ "author": "Fred <[email protected]>", "name": "demo", "description": "Hello", "version": "0.0.0", "repository": { "url": "" }, "dependencies": {}, "devDependencies": {}, "optionalDependencies": {}, "engines": { "node": "*" }}

Page 37: How to Write Node.js Module

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

Normal Structure of Package

Page 38: How to Write Node.js Module

I don't want to use index.js !Change Entry Point

我想改變進入啟始點

Page 39: How to Write Node.js Module

Add "main" Property Topackage.json

Page 40: How to Write Node.js Module

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

After Change Entry Point

Page 41: How to Write Node.js Module

require()

Open Directory

package.json

index.jsindex.node

AnotherEntry Point

Page 42: How to Write Node.js Module

Upload Package

上傳套件!公開於世!

Page 43: How to Write Node.js Module

npm publish .

發佈在 '.' 之下的 Package

Page 44: How to Write Node.js Module

Piece of cake!開發模組一點都不難嘛!

Page 45: How to Write Node.js Module

進階Advanced Topic

Page 46: How to Write Node.js Module

How toWrite C/C++ Addons

如何使用 C/C++ 寫模組

Page 47: How to Write Node.js Module

1.GCC (used to compile)

2.Python (For build script)

Development Environment

Page 48: How to Write Node.js Module

Write The FirstC/C++ Addon動手寫第一個 C/C++ 模組

Page 49: How to Write Node.js Module

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

Page 50: How to Write Node.js Module

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

module.exports

Page 51: How to Write Node.js Module

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

function() { return 'world';}

Page 52: How to Write Node.js Module

Compare with JavaScript Version

var target = module.exports;

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

module.exports.hello = function() { return 'world!';};

Page 53: How to Write Node.js Module

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

Page 54: How to Write Node.js Module

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

v8::String Class

Page 55: How to Write Node.js Module
Page 56: How to Write Node.js Module

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

Page 57: How to Write Node.js Module

● 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

HandleScope

Page 58: How to Write Node.js Module

Compile The FirstC/C++ Addon動手編譯第一個 C/C++ 模組

Page 59: How to Write Node.js Module

You Must Havewscript

你必需有一個 wscript

Page 60: How to Write Node.js Module

wscriptsrcdir = '.'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'

Page 61: How to Write Node.js Module

● package.json● README (README.md)● LICENSE● wscript● hello.cc

Structure of Package

Page 62: How to Write Node.js Module

node-waf configure build

使用 node-waf 編譯我們的程式!

Page 63: How to Write Node.js Module

Generatedbuild/Release/hello.node

編譯產生 Binary 檔案

Page 64: How to Write Node.js Module

Write A Test Casevar Hello = require('./build/Release/hello.node');

console.log(Hello.hello());

Page 65: How to Write Node.js Module

Don't Forget ThisBefore Upload Package

上傳模組前要修改 package.json

Page 66: How to Write Node.js Module

Add "scripts" Property Topackage.json

Page 67: How to Write Node.js Module

{ "name": "hello", ... "main": "build/Release/hello.node", "scripts": { "install": "node-waf configure build" }}

Modify package.json

Page 68: How to Write Node.js Module

npm publish .

發佈我們的 C/C++ Addon!

Page 69: How to Write Node.js Module

開發 C/C++ Addon 的竅門

Page 70: How to Write Node.js Module

C/C++ JavaScript

人腦內建:

1. C/C++ Compiler2. JavaScript Compiler3. Virtual Machine

Page 71: How to Write Node.js Module

進階 Part 2Advanced Topic Part 2

Page 72: How to Write Node.js Module

Arguments參數

Page 73: How to Write Node.js Module

Assume We Have Parameters

var Hello = require('./build/Release/hello.node');

console.log(Hello.hello('String', 101, 4.0, true));

Page 74: How to Write Node.js Module

Get Arguments In C/C++

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

printf("%d\n", args.Length());

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

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

return scope.Close(String::New("world"))}

Page 75: How to Write Node.js Module

如果以上能理解進一步討論 C/C++ 與 JavaScript 的關係

Page 76: How to Write Node.js Module

Understanding of Types了解 JavaScript 資料型態

Page 77: How to Write Node.js Module

Types In JavaScript

var string = 'Hello String';var integer = 714;var float = 11.15;var boolean = false;var obj = {};var arr = [];var func = function() {};

Page 78: How to Write Node.js Module

Methods

Type Name Check Type Get Value

String IsString()*String::Utf8Value(data->ToString())*String::AsciiValue(data->ToString())

IntegerIsNumber()

IsInt32()IsUint32()

data->ToInteger()->Value()data->ToInt32()->Value()data->ToUint32()->Value()data->IntegerValue()data->Uint32Value()data->Int32Value()

Float IsNumber() data->NumbeValue()

Boolean IsBoolean() data->ToBoolean()->Value()

Object/Array IsObject() data->ToObject()

Function IsFunction()

Local<Function> cb = Local<Function>::Cast(data);const unsigned argc = 1;Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world"))};cb->Call(Context::GetCurrent()->Global(), argc, argv);

* Assume Local<Value> data;

Page 79: How to Write Node.js Module

Class參數

Page 80: How to Write Node.js Module

Create Class Instancevar Hello = require('./build/Release/hello.node');

var hello = new Hello.Hello();

console.log(hello.method());

Page 81: How to Write Node.js Module

Class Constructor in JavaScript

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

/* Prototype Method */Hello.prototype.myMethod = function() { return 'World';};

Page 82: How to Write Node.js Module

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

Page 83: How to Write Node.js Module

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

Page 84: How to Write Node.js Module

一切只是開端It's beginning to do

Page 85: How to Write Node.js Module

進階 Part 3To Be Continued...

Page 86: How to Write Node.js Module

這真的是進階

I am NOT Kidding You

Page 87: How to Write Node.js Module

Wrapping C++ Object將 C++ Class 包裝成 JavaScript Class

Page 88: How to Write Node.js Module

Create JavaScipt InstanceIn C/C++

Do "new Hello.Hello()" in C/C++

Page 89: How to Write Node.js Module

See You Next Time下次有機會見面再來討論吧!

Page 90: How to Write Node.js Module

喔!差點忘了

火力展示

Page 91: How to Write Node.js Module

Question?歡迎發問

Page 92: How to Write Node.js Module

Thanks感