├── CNAME ├── _config.yml ├── 34. efsw ├── README.md ├── .gitmodules ├── efsw.js ├── src │ ├── entry.cc │ ├── efsw_core.h │ ├── efsw_core_listener.h │ ├── efsw_core.cc │ └── efsw_core_listener.cc ├── package.json ├── LICENSE ├── .gitignore ├── lib │ └── watcher.js └── binding.gyp ├── .editorconfig ├── cover.jpg ├── flandre.jpg ├── qq_group.jpg ├── 19. at_exit_hook ├── binding.gyp ├── test.js ├── package.json └── at_exit.cc ├── 2. cpp entry ├── binding.gyp ├── package.json └── entry.cpp ├── 11. array prototype map ├── binding.gyp ├── package.json └── map.cc ├── 1. first build ├── binding.gyp ├── package.json └── first.cpp ├── 12. try catch ├── binding.gyp ├── package.json └── try_catch.cc ├── 15. run callback ├── binding.gyp ├── addon.js ├── package.json └── addon.cc ├── 4. object template ├── binding.gyp ├── package.json └── template.cpp ├── 13. hello world again ├── binding.gyp ├── hello.cc └── package.json ├── 16. object factory ├── binding.gyp ├── package.json └── addon.cc ├── 17. function factory ├── binding.gyp ├── addon.js ├── package.json └── addon.cc ├── 3. function template ├── binding.gyp ├── package.json └── template.cpp ├── 10. function template inherit ├── binding.gyp ├── package.json └── inherit.cpp ├── 14. function parameters ├── binding.gyp ├── package.json └── addon.cc ├── 5. object template accessor ├── binding.gyp ├── test.js ├── package.json └── accessor.cpp ├── 8. internal field wrong ├── binding.gyp ├── package.json └── internal_field.cpp ├── 9. internal field right ├── binding.gyp ├── package.json └── internal_field.cpp ├── 20. nan echo ├── binding.gyp ├── package.json └── echo.cc ├── 26. nan json ├── binding.gyp ├── package.json └── json.cc ├── 30. libuv idle ├── binding.gyp ├── test.js ├── package.json └── idle.cc ├── 25. nan array demo ├── binding.gyp ├── package.json └── array.cc ├── 27. nan buffer ├── binding.gyp ├── package.json └── buffer.cc ├── 31. libuv sleep sort ├── binding.gyp ├── package.json └── sleep.cc ├── 21. nan array prototype map ├── binding.gyp ├── package.json └── map.cc ├── 24. nan object demo ├── binding.gyp ├── package.json └── object.cc ├── 23. nan reverse string ├── binding.gyp ├── package.json └── reverse.cc ├── 28. nan nbodies ├── binding.gyp ├── package.json ├── nbody.h ├── addon.cc └── nbody.cc ├── 18. myobject ├── 1 │ ├── addon.cc │ ├── myobject.h │ └── myobject.cc ├── 2 │ ├── addon.cc │ ├── myobject.h │ └── myobject.cc ├── 3 │ ├── addon.cc │ ├── myobject.h │ └── myobject.cc ├── 4 │ ├── addon.cc │ ├── myobject.h │ └── myobject.cc ├── 5 │ ├── addon.cc │ ├── myobject.h │ └── myobject.cc ├── package.json └── binding.gyp ├── 36. napi ├── binding.gyp ├── package.json └── addon.cpp ├── 29. nan dummy download ├── binding.gyp ├── package.json └── download.cc ├── 33. libuv watchdog ├── package.json ├── binding.gyp └── watchdog.cc ├── 6. mapped property interceptor ├── package.json ├── binding.gyp └── interceptor.cpp ├── 7. indexed property interceptor ├── package.json ├── interceptor.cpp └── binding.gyp ├── .gitmodules ├── 32. libuv sleep sort advanced ├── package.json ├── binding.gyp ├── sem │ └── sleep.cc ├── rwlock │ └── sleep.cc └── mutex │ └── sleep.cc ├── 22. nan set method ├── package.json ├── accessor │ └── addon.cc ├── prototype │ └── addon.cc ├── interceptor │ └── addon.cc └── binding.gyp ├── .gitignore ├── README.md ├── README_en.md └── LICENSE /CNAME: -------------------------------------------------------------------------------- 1 | nyaanode.2333.moe 2 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-time-machine -------------------------------------------------------------------------------- /34. efsw/README.md: -------------------------------------------------------------------------------- 1 | # node-efsw 2 | Node.js binding for efsw. 3 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.{json,yaml,yml,pug,jade,styl,gyp}] 2 | indent_size = 2 3 | -------------------------------------------------------------------------------- /cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XadillaX/nyaa-nodejs-demo/HEAD/cover.jpg -------------------------------------------------------------------------------- /flandre.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XadillaX/nyaa-nodejs-demo/HEAD/flandre.jpg -------------------------------------------------------------------------------- /qq_group.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XadillaX/nyaa-nodejs-demo/HEAD/qq_group.jpg -------------------------------------------------------------------------------- /34. efsw/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/deps/efsw"] 2 | path = src/deps/efsw 3 | url = https://github.com/XadillaX/efsw 4 | -------------------------------------------------------------------------------- /19. at_exit_hook/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "at_exit", 4 | "sources": [ "at_exit.cc" ] 5 | }] 6 | } 7 | -------------------------------------------------------------------------------- /2. cpp entry/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "entry", 4 | "sources": [ 5 | "entry.cpp" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /11. array prototype map/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "map", 4 | "sources": [ 5 | "map.cc" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /1. first build/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "first", 4 | "sources": [ 5 | "first.cpp" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /12. try catch/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "try_catch", 4 | "sources": [ 5 | "try_catch.cc" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /15. run callback/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [ 3 | { 4 | "target_name": "addon", 5 | "sources": [ "addon.cc" ] 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /4. object template/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "template", 4 | "sources": [ 5 | "template.cpp" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /13. hello world again/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [ 3 | { 4 | "target_name": "addon", 5 | "sources": [ "hello.cc" ] 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /16. object factory/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [ 3 | { 4 | "target_name": "addon", 5 | "sources": [ "addon.cc" ] 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /17. function factory/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [ 3 | { 4 | "target_name": "addon", 5 | "sources": [ "addon.cc" ] 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /3. function template/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "template", 4 | "sources": [ 5 | "template.cpp" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /10. function template inherit/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "inherit", 4 | "sources": [ 5 | "inherit.cpp" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /14. function parameters/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [ 3 | { 4 | "target_name": "addon", 5 | "sources": [ "addon.cc" ] 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /5. object template accessor/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "accessor", 4 | "sources": [ 5 | "accessor.cpp" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /8. internal field wrong/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "internal_field_wrong", 4 | "sources": [ 5 | "internal_field.cpp" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /9. internal field right/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "internal_field_right", 4 | "sources": [ 5 | "internal_field.cpp" 6 | ] 7 | }] 8 | } -------------------------------------------------------------------------------- /20. nan echo/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "echo", 4 | "sources": [ "echo.cc" ], 5 | "include_dirs": [ 6 | " created at 2017-06-14 14:21:41 with ❤ 3 | * 4 | * Copyright (c) 2017 xcoder.in, all rights reserved. 5 | */ 6 | "use strict"; 7 | 8 | require("./build/Release/at_exit"); 9 | -------------------------------------------------------------------------------- /30. libuv idle/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "idle", 4 | "sources": [ 5 | "idle.cc" 6 | ], 7 | "include_dirs": [ 8 | " created at 2017-08-22 16:30:58 with ❤ 3 | * 4 | * Copyright (c) 2017 xcoder.in, all rights reserved. 5 | */ 6 | "use strict"; 7 | 8 | module.exports.Watcher = require("./lib/watcher"); 9 | -------------------------------------------------------------------------------- /21. nan array prototype map/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "map", 4 | "sources": [ 5 | "map.cc" 6 | ], 7 | "include_dirs": [ 8 | " created at 2017-06-08 16:29:42 with ❤ 3 | * 4 | * Copyright (c) 2017 xcoder.in, all rights reserved. 5 | */ 6 | "use strict"; 7 | 8 | const addon = require("./"); 9 | 10 | const fn = addon(); 11 | console.log(fn()); 12 | -------------------------------------------------------------------------------- /18. myobject/1/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include "myobject.h" 3 | 4 | namespace __addon1__ { 5 | 6 | using v8::Local; 7 | using v8::Object; 8 | 9 | void InitAll(Local exports) 10 | { 11 | MyObject::Init(exports); 12 | } 13 | 14 | NODE_MODULE(addon1, InitAll) 15 | 16 | } 17 | -------------------------------------------------------------------------------- /18. myobject/2/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include "myobject.h" 3 | 4 | namespace __addon2__ { 5 | 6 | using v8::Local; 7 | using v8::Object; 8 | 9 | void InitAll(Local exports) 10 | { 11 | MyObject::Init(exports); 12 | } 13 | 14 | NODE_MODULE(addon1, InitAll) 15 | 16 | } 17 | -------------------------------------------------------------------------------- /18. myobject/3/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include "myobject.h" 3 | 4 | namespace __addon3__ { 5 | 6 | using v8::Local; 7 | using v8::Object; 8 | 9 | void InitAll(Local exports) 10 | { 11 | MyObject::Init(exports); 12 | } 13 | 14 | NODE_MODULE(addon1, InitAll) 15 | 16 | } 17 | -------------------------------------------------------------------------------- /36. napi/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "addon", 4 | "sources": [ 5 | "addon.cpp" 6 | ], 7 | "include_dirs": [ " created at 2017-05-14 14:45:35 with ❤ 3 | * 4 | * Copyright (c) 2017 xcoder.in, all rights reserved. 5 | */ 6 | "use strict"; 7 | 8 | const m = require("./build/Release/accessor"); 9 | 10 | console.log(m.var3); 11 | m.var3 = 2333; 12 | console.log(m.var3); 13 | -------------------------------------------------------------------------------- /18. myobject/4/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include "myobject.h" 3 | 4 | namespace __addon4__ { 5 | 6 | using v8::Local; 7 | using v8::Object; 8 | 9 | void InitAll(Local exports, Local module) 10 | { 11 | MyObject::Init(exports->GetIsolate()); 12 | NODE_SET_METHOD(module, "exports", MyObject::NewInstance); 13 | } 14 | 15 | NODE_MODULE(addon1, InitAll) 16 | 17 | } 18 | -------------------------------------------------------------------------------- /15. run callback/addon.js: -------------------------------------------------------------------------------- 1 | /** 2 | * XadillaX created at 2017-06-06 22:16:19 with ❤ 3 | * 4 | * Copyright (c) 2017 xcoder.in, all rights reserved. 5 | */ 6 | "use strict"; 7 | 8 | const addon = require("./build/Release/addon"); 9 | 10 | module.exports = function(callback) { 11 | if(!callback || typeof callback !== "function") { 12 | throw new Error("Wrong argument"); 13 | } 14 | 15 | addon(callback); 16 | }; 17 | -------------------------------------------------------------------------------- /18. myobject/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "18-myobject", 3 | "version": "1.0.0", 4 | "description": "Demo for MyObject.", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 8 | }, 9 | "author": "XadillaX ", 10 | "license": "GPL-3.0", 11 | "bugs": { 12 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 13 | }, 14 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 15 | } 16 | -------------------------------------------------------------------------------- /34. efsw/src/entry.cc: -------------------------------------------------------------------------------- 1 | /** 2 | * node-efsw - Node.js binding for EFSW 3 | * 4 | * Copyright (c) 2017 XadillaX 5 | * 6 | * MIT License 7 | */ 8 | #ifndef __ENTRY_H__ 9 | #define __ENTRY_H__ 10 | 11 | #include "nan.h" 12 | #include "efsw_core.h" 13 | 14 | namespace efsw_core { 15 | 16 | NAN_MODULE_INIT(Init) 17 | { 18 | EFSWCore::Init(target); 19 | } 20 | 21 | NODE_MODULE(core, Init) 22 | 23 | } 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /19. at_exit_hook/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "19-at_exit_hook", 3 | "version": "1.0.0", 4 | "description": "Demo for AtExit Hook.", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 8 | }, 9 | "author": "XadillaX ", 10 | "license": "GPL-3.0", 11 | "bugs": { 12 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 13 | }, 14 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 15 | } 16 | -------------------------------------------------------------------------------- /18. myobject/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "addon1", 4 | "sources": [ "1/addon.cc", "1/myobject.cc" ] 5 | }, { 6 | "target_name": "addon2", 7 | "sources": [ "2/addon.cc", "2/myobject.cc" ] 8 | }, { 9 | "target_name": "addon3", 10 | "sources": [ "3/addon.cc", "3/myobject.cc" ] 11 | }, { 12 | "target_name": "addon4", 13 | "sources": [ "4/addon.cc", "4/myobject.cc" ] 14 | }, { 15 | "target_name": "addon5", 16 | "sources": [ "5/addon.cc", "5/myobject.cc" ] 17 | }] 18 | } 19 | -------------------------------------------------------------------------------- /2. cpp entry/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "2-cpp-entry", 3 | "version": "1.0.0", 4 | "description": "C++ addon as the entry.", 5 | "main": "build/Release/entry.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /12. try catch/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "12-try-catch", 3 | "version": "1.0.0", 4 | "description": "Demo for try-catch.", 5 | "main": "build/Release/try_catch.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /1. first build/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "1-first-build", 3 | "version": "1.0.0", 4 | "description": "First build for node-gyp.", 5 | "main": "index.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/1.%20first%20build#readme" 16 | } -------------------------------------------------------------------------------- /15. run callback/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "15-run-callback", 3 | "version": "1.0.0", 4 | "description": "Demo for running callback.", 5 | "main": "build/Release/addon.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /16. object factory/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "16-object-factory", 3 | "version": "1.0.0", 4 | "description": "Demo for object factory.", 5 | "main": "build/Release/addon.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /20. nan echo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "20-nan-echo", 3 | "version": "1.0.0", 4 | "description": "Demo for NAN echo.", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 8 | }, 9 | "author": "XadillaX ", 10 | "license": "GPL-3.0", 11 | "bugs": { 12 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 13 | }, 14 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 15 | "dependencies": { 16 | "nan": "^2.6.2" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /17. function factory/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "16-function-factory", 3 | "version": "1.0.0", 4 | "description": "Demo for function factory.", 5 | "main": "build/Release/addon.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /4. object template/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "4-object-template", 3 | "version": "1.0.0", 4 | "description": "Demo for object template.", 5 | "main": "build/Release/template.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /13. hello world again/hello.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace demo { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::Isolate; 7 | using v8::Local; 8 | using v8::Object; 9 | using v8::String; 10 | using v8::Value; 11 | 12 | void Method(const FunctionCallbackInfo& args) { 13 | Isolate* isolate = args.GetIsolate(); 14 | args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world")); 15 | } 16 | 17 | void init(Local exports) { 18 | NODE_SET_METHOD(exports, "hello", Method); 19 | } 20 | 21 | NODE_MODULE(addon, init) 22 | 23 | } 24 | -------------------------------------------------------------------------------- /13. hello world again/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "13-hello-world-again", 3 | "version": "1.0.0", 4 | "description": "Demo for Hello world again.", 5 | "main": "build/Release/addon.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /3. function template/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "3-function-template", 3 | "version": "1.0.0", 4 | "description": "Demo for function template.", 5 | "main": "build/Release/template.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /14. function parameters/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "14-function-parameters", 3 | "version": "1.0.0", 4 | "description": "Demo for function parameters.", 5 | "main": "build/Release/addon.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /33. libuv watchdog/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "33-libuv-watchdog", 3 | "version": "1.0.0", 4 | "description": "Demo for libuv watchdog.", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 8 | }, 9 | "author": "XadillaX ", 10 | "license": "GPL-3.0", 11 | "bugs": { 12 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 13 | }, 14 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 15 | "dependencies": { 16 | "nan": "^2.6.2" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /11. array prototype map/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "11-array-prototype-map", 3 | "version": "1.0.0", 4 | "description": "Demo for dummy array.prototype.map.", 5 | "main": "build/Release/map.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /5. object template accessor/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "5-object-template-accessor", 3 | "version": "1.0.0", 4 | "description": "Demo for object template accessor.", 5 | "main": "build/Release/accessor.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /8. internal field wrong/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8-internal-field-wrong", 3 | "version": "1.0.0", 4 | "description": "Demo for wrong internal field.", 5 | "main": "build/Release/internal_field_wrong.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /9. internal field right/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "9-internal-field-right", 3 | "version": "1.0.0", 4 | "description": "Demo for right internal field.", 5 | "main": "build/Release/internal_field_right.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /26. nan json/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "25-nan-json", 3 | "version": "1.0.0", 4 | "description": "Demo for NAN json.", 5 | "main": "build/Release/json.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /30. libuv idle/test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * XadillaX created at 2017-07-12 15:03:00 with ❤ 3 | * 4 | * Copyright (c) 2017 xcoder.in, all rights reserved. 5 | */ 6 | "use strict"; 7 | 8 | const addon = require("./build/Release/idle"); 9 | 10 | addon.startIdle(100); 11 | 12 | try { 13 | addon.startIdle(1); 14 | } catch(e) { 15 | console.error(e); 16 | } 17 | 18 | let times = 100; 19 | function tick() { 20 | times--; 21 | console.log(`还剩 ${times} 次 tick。`); 22 | 23 | if(times === 0) return; 24 | 25 | setImmediate(tick); 26 | } 27 | 28 | setImmediate(tick); 29 | -------------------------------------------------------------------------------- /30. libuv idle/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "40-libuv-idle", 3 | "version": "1.0.0", 4 | "description": "Demo for libuv idel.", 5 | "main": "build/Release/idle.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /6. mapped property interceptor/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "6-mapped-property-interceptor", 3 | "version": "1.0.0", 4 | "description": "Demo for mapped property interceptor.", 5 | "main": "build/Release/interceptor.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /7. indexed property interceptor/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "7-indexed-property-interceptor", 3 | "version": "1.0.0", 4 | "description": "Demo for indexed property interceptor.", 5 | "main": "build/Release/interceptor.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "deps/mbedtls"] 2 | path = deps/mbedtls 3 | url = https://github.com/particle-iot/mbedtls 4 | 5 | [submodule "deps/minihttp"] 6 | path = deps/minihttp 7 | url = https://github.com/fgenesis/minihttp 8 | 9 | [submodule "deps/efsw"] 10 | path = deps/efsw 11 | url = https://github.com/XadillaX/efsw 12 | 13 | [submodule "34. efsw/src/deps/efsw"] 14 | path = 34. efsw/src/deps/efsw 15 | url = https://github.com/XadillaX/efsw 16 | 17 | [submodule "35. efsw advanced"] 18 | path = 35. efsw advanced 19 | url = https://github.com/XadillaX/node-efsw 20 | -------------------------------------------------------------------------------- /1. first build/first.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __first__ { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::Isolate; 7 | using v8::Local; 8 | using v8::Object; 9 | using v8::String; 10 | using v8::Value; 11 | 12 | void Method(const FunctionCallbackInfo& args) 13 | { 14 | Isolate* isolate = args.GetIsolate(); 15 | args.GetReturnValue().Set(String::NewFromUtf8(isolate, "first build")); 16 | } 17 | 18 | void init(Local exports) 19 | { 20 | NODE_SET_METHOD(exports, "first", Method); 21 | } 22 | 23 | NODE_MODULE(addon, init) 24 | 25 | } -------------------------------------------------------------------------------- /10. function template inherit/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "10-function-template-inherit", 3 | "version": "1.0.0", 4 | "description": "Demo for function template inherit.", 5 | "main": "build/Release/internal_field_right.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme" 16 | } 17 | -------------------------------------------------------------------------------- /20. nan echo/echo.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __nan_echo__ { 4 | 5 | using v8::String; 6 | using v8::FunctionTemplate; 7 | 8 | NAN_METHOD(Echo) 9 | { 10 | if(info.Length() < 1) 11 | { 12 | Nan::ThrowError("Wrong number of arguments."); 13 | return; 14 | } 15 | 16 | info.GetReturnValue().Set(info[0]); 17 | } 18 | 19 | NAN_MODULE_INIT(Init) 20 | { 21 | Nan::Set(target, Nan::New("echo").ToLocalChecked(), 22 | Nan::GetFunction(Nan::New(Echo)).ToLocalChecked()); 23 | } 24 | 25 | NODE_MODULE(echo, Init) 26 | 27 | } 28 | -------------------------------------------------------------------------------- /27. nan buffer/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "25-nan-buffer", 3 | "version": "1.0.0", 4 | "description": "Demo for NAN buffer.", 5 | "main": "build/Release/buffer.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /28. nan nbodies/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "28-nan-nbodies", 3 | "version": "1.0.0", 4 | "description": "Demo for NAN Nbody.", 5 | "main": "build/Release/buffer.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /32. libuv sleep sort advanced/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "32-libuv-sleep-sort-advanced", 3 | "version": "1.0.0", 4 | "description": "Demo for libuv sleep sort advanced.", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 8 | }, 9 | "author": "XadillaX ", 10 | "license": "GPL-3.0", 11 | "bugs": { 12 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 13 | }, 14 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 15 | "dependencies": { 16 | "nan": "^2.6.2" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /25. nan array demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "25-nan-array-demo", 3 | "version": "1.0.0", 4 | "description": "Demo for NAN array.", 5 | "main": "build/Release/array.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /22. nan set method/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "22-nan-set-method", 3 | "version": "1.0.0", 4 | "description": "Demo for NAN setting method.", 5 | "main": "build/Release/map.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /24. nan object demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "24-nan-object-demo", 3 | "version": "1.0.0", 4 | "description": "Demo for NAN object.", 5 | "main": "build/Release/object.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /36. napi/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "36-napi", 3 | "version": "1.0.0", 4 | "description": "N-API for node-gyp.", 5 | "main": "index.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/1.%20first%20build#readme", 16 | "dependencies": { 17 | "node-addon-api": "^0.6.3" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /31. libuv sleep sort/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "31-libuv-sleep-sort", 3 | "version": "1.0.0", 4 | "description": "Demo for libuv sleep sort.", 5 | "main": "build/Release/sleep.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /23. nan reverse string/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "23-nan-reverse-string", 3 | "version": "1.0.0", 4 | "description": "Demo for NAN reversing string.", 5 | "main": "build/Release/reverse.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /29. nan dummy download/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "29-nan-dummy-download", 3 | "version": "1.0.0", 4 | "description": "Demo for NAN dummy download.", 5 | "main": "build/Release/download.node", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/XadillaX/nyaa-nodejs-demo.git" 9 | }, 10 | "author": "XadillaX ", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /32. libuv sleep sort advanced/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "mutex_sleep", 4 | "sources": [ 5 | "mutex/sleep.cc" 6 | ], 7 | "include_dirs": [ 8 | "", 11 | "license": "GPL-3.0", 12 | "bugs": { 13 | "url": "https://github.com/XadillaX/nyaa-nodejs-demo/issues" 14 | }, 15 | "homepage": "https://github.com/XadillaX/nyaa-nodejs-demo#readme", 16 | "dependencies": { 17 | "nan": "^2.6.2" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /16. object factory/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace demo { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::Isolate; 7 | using v8::Local; 8 | using v8::Object; 9 | using v8::String; 10 | using v8::Value; 11 | 12 | void CreateObject(const FunctionCallbackInfo& args) { 13 | Isolate* isolate = args.GetIsolate(); 14 | 15 | Local obj = Object::New(isolate); 16 | obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString()); 17 | 18 | args.GetReturnValue().Set(obj); 19 | } 20 | 21 | void Init(Local exports, Local module) { 22 | NODE_SET_METHOD(module, "exports", CreateObject); 23 | } 24 | 25 | NODE_MODULE(addon, Init) 26 | 27 | } 28 | -------------------------------------------------------------------------------- /25. nan array demo/array.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace __array__ { 5 | 6 | using v8::Local; 7 | using v8::Array; 8 | using v8::String; 9 | 10 | NAN_METHOD(Reverse) 11 | { 12 | Local input = Local::Cast(info[0]); 13 | Local output = Nan::New(); 14 | 15 | for(unsigned int i = 0, j = input->Length() - 1; i < input->Length(); i++, j--) 16 | { 17 | Nan::Set(output, j, Nan::Get(input, i).ToLocalChecked()); 18 | } 19 | 20 | info.GetReturnValue().Set(output); 21 | } 22 | 23 | NAN_MODULE_INIT(Init) 24 | { 25 | Nan::Export(target, "reverse", Reverse); 26 | } 27 | 28 | NODE_MODULE(reverse, Init) 29 | 30 | } 31 | -------------------------------------------------------------------------------- /18. myobject/1/myobject.h: -------------------------------------------------------------------------------- 1 | #ifndef __MYOBJECT_H__ 2 | #define __MYOBJECT_H__ 3 | 4 | #include 5 | #include 6 | 7 | namespace __addon1__ { 8 | 9 | using node::ObjectWrap; 10 | using v8::Object; 11 | using v8::Local; 12 | using v8::Value; 13 | using v8::FunctionCallbackInfo; 14 | 15 | class MyObject : public ObjectWrap { 16 | public: 17 | static void Init(Local exports); 18 | 19 | private: 20 | explicit MyObject(double value = 0); 21 | ~MyObject(); 22 | 23 | static void New(const FunctionCallbackInfo& args); 24 | static void PlusOne(const FunctionCallbackInfo& args); 25 | double value_; 26 | }; 27 | 28 | } 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /23. nan reverse string/reverse.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace __reverse__ { 5 | 6 | using v8::Local; 7 | using v8::String; 8 | 9 | NAN_METHOD(Reverse) 10 | { 11 | Nan::MaybeLocal handle = Nan::To(info[0]); 12 | Local local_handle = handle.ToLocalChecked(); 13 | 14 | Nan::Utf8String val(local_handle); 15 | 16 | // 字符串翻转 17 | std::string str(*val); 18 | std::reverse(str.begin(), str.end()); 19 | 20 | info.GetReturnValue().Set(Nan::New(str.c_str()).ToLocalChecked()); 21 | } 22 | 23 | NAN_MODULE_INIT(Init) 24 | { 25 | Nan::Export(target, "reverse", Reverse); 26 | } 27 | 28 | NODE_MODULE(reverse, Init) 29 | 30 | } 31 | -------------------------------------------------------------------------------- /34. efsw/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "efsw", 3 | "version": "1.0.0", 4 | "description": "Node.js binding for efsw.", 5 | "main": "efsw.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/XadillaX/node-efsw.git" 12 | }, 13 | "keywords": [ 14 | "efsw", 15 | "watcher", 16 | "fsevents" 17 | ], 18 | "author": "XadillaX ", 19 | "license": "MIT", 20 | "bugs": { 21 | "url": "https://github.com/XadillaX/node-efsw/issues" 22 | }, 23 | "homepage": "https://github.com/XadillaX/node-efsw#readme", 24 | "dependencies": { 25 | "nan": "^2.6.2" 26 | } 27 | } -------------------------------------------------------------------------------- /22. nan set method/accessor/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __accessor__ { 4 | 5 | using v8::Local; 6 | using v8::Object; 7 | using v8::ObjectTemplate; 8 | 9 | int x = 0; 10 | 11 | NAN_GETTER(Getter) 12 | { 13 | info.GetReturnValue().Set(x); 14 | } 15 | 16 | NAN_SETTER(Setter) 17 | { 18 | x = value->Int32Value(); 19 | } 20 | 21 | NAN_MODULE_INIT(Init) 22 | { 23 | Local tpl = Nan::New(); 24 | Nan::SetAccessor(tpl, Nan::New("x").ToLocalChecked(), Getter, Setter); 25 | 26 | Local ret = ((Nan::MaybeLocal)tpl->NewInstance()).ToLocalChecked(); 27 | Nan::Set(target, Nan::New("obj").ToLocalChecked(), ret); 28 | } 29 | 30 | NODE_MODULE(accessor, Init) 31 | 32 | } 33 | -------------------------------------------------------------------------------- /15. run callback/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace demo { 4 | 5 | using v8::Function; 6 | using v8::FunctionCallbackInfo; 7 | using v8::Isolate; 8 | using v8::Local; 9 | using v8::Null; 10 | using v8::Object; 11 | using v8::String; 12 | using v8::Value; 13 | 14 | void RunCallback(const FunctionCallbackInfo& args) { 15 | Isolate* isolate = args.GetIsolate(); 16 | Local cb = Local::Cast(args[0]); 17 | const unsigned argc = 1; 18 | Local argv[argc] = { String::NewFromUtf8(isolate, "hello world") }; 19 | cb->Call(Null(isolate), argc, argv); 20 | } 21 | 22 | void Init(Local exports, Local module) { 23 | NODE_SET_METHOD(module, "exports", RunCallback); 24 | } 25 | 26 | NODE_MODULE(addon, Init) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | */build 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | build 40 | 41 | package-lock.json 42 | -------------------------------------------------------------------------------- /18. myobject/2/myobject.h: -------------------------------------------------------------------------------- 1 | #ifndef __MYOBJECT_H__ 2 | #define __MYOBJECT_H__ 3 | 4 | #include 5 | #include 6 | 7 | namespace __addon2__ { 8 | 9 | using node::ObjectWrap; 10 | using v8::Object; 11 | using v8::Local; 12 | using v8::Persistent; 13 | using v8::Value; 14 | using v8::Function; 15 | using v8::FunctionCallbackInfo; 16 | 17 | class MyObject : public ObjectWrap { 18 | public: 19 | static void Init(Local exports); 20 | 21 | private: 22 | explicit MyObject(double value = 0); 23 | ~MyObject(); 24 | 25 | static void New(const FunctionCallbackInfo& args); 26 | static void PlusOne(const FunctionCallbackInfo& args); 27 | static Persistent constructor; 28 | double value_; 29 | }; 30 | 31 | } 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /18. myobject/3/myobject.h: -------------------------------------------------------------------------------- 1 | #ifndef __MYOBJECT_H__ 2 | #define __MYOBJECT_H__ 3 | 4 | #include 5 | #include 6 | 7 | namespace __addon3__ { 8 | 9 | using node::ObjectWrap; 10 | using v8::Object; 11 | using v8::Local; 12 | using v8::Persistent; 13 | using v8::Value; 14 | using v8::Function; 15 | using v8::FunctionCallbackInfo; 16 | 17 | class MyObject : public ObjectWrap { 18 | public: 19 | static void Init(Local exports); 20 | double PlusOne(); 21 | 22 | private: 23 | explicit MyObject(double value = 0); 24 | ~MyObject(); 25 | 26 | static void New(const FunctionCallbackInfo& args); 27 | static void PlusOne(const FunctionCallbackInfo& args); 28 | static Persistent constructor; 29 | double value_; 30 | }; 31 | 32 | } 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /18. myobject/5/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include "myobject.h" 3 | 4 | namespace __addon5__ { 5 | 6 | using v8::Local; 7 | using v8::Number; 8 | using v8::Object; 9 | 10 | void Add(const FunctionCallbackInfo& args) 11 | { 12 | Isolate* isolate = args.GetIsolate(); 13 | 14 | MyObject* obj1 = ObjectWrap::Unwrap(args[0]->ToObject()); 15 | MyObject* obj2 = ObjectWrap::Unwrap(args[1]->ToObject()); 16 | 17 | double sum = obj1->value() + obj2->value(); 18 | args.GetReturnValue().Set(Number::New(isolate, sum)); 19 | } 20 | 21 | void InitAll(Local exports, Local module) 22 | { 23 | MyObject::Init(exports->GetIsolate()); 24 | 25 | NODE_SET_METHOD(exports, "createObject", MyObject::NewInstance); 26 | NODE_SET_METHOD(exports, "add", Add); 27 | } 28 | 29 | NODE_MODULE(addon1, InitAll) 30 | 31 | } 32 | -------------------------------------------------------------------------------- /18. myobject/4/myobject.h: -------------------------------------------------------------------------------- 1 | #ifndef __MYOBJECT_H__ 2 | #define __MYOBJECT_H__ 3 | 4 | #include 5 | #include 6 | 7 | namespace __addon4__ { 8 | 9 | using node::ObjectWrap; 10 | using v8::Object; 11 | using v8::Local; 12 | using v8::Isolate; 13 | using v8::Persistent; 14 | using v8::Value; 15 | using v8::Function; 16 | using v8::FunctionCallbackInfo; 17 | 18 | class MyObject : public ObjectWrap { 19 | public: 20 | static void Init(Isolate* isolate); 21 | static void NewInstance(const FunctionCallbackInfo& args); 22 | double PlusOne(); 23 | 24 | private: 25 | explicit MyObject(double value = 0); 26 | ~MyObject(); 27 | 28 | static void New(const FunctionCallbackInfo& args); 29 | static void PlusOne(const FunctionCallbackInfo& args); 30 | static Persistent constructor; 31 | double value_; 32 | }; 33 | 34 | } 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /28. nan nbodies/nbody.h: -------------------------------------------------------------------------------- 1 | #ifndef __NBODY_H__ 2 | #define __NBODY_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | namespace __nbody__ { 11 | 12 | class Body { 13 | public: 14 | double x; 15 | double y; 16 | double z; 17 | double filler; 18 | double vx; 19 | double vy; 20 | double vz; 21 | double mass; 22 | 23 | public: 24 | Body(); 25 | static Body& jupiter(); 26 | static Body& saturn(); 27 | static Body& uranus(); 28 | static Body& neptune(); 29 | static Body& sun(); 30 | 31 | Body& OffsetMomentum(double px, double py, double pz); 32 | }; 33 | 34 | class NBodySystem { 35 | public: 36 | NBodySystem(); 37 | 38 | void advance(double dt); 39 | double energy(); 40 | 41 | private: 42 | std::tr1::array bodies; 43 | }; 44 | 45 | } 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /34. efsw/src/efsw_core.h: -------------------------------------------------------------------------------- 1 | /** 2 | * node-efsw - Node.js binding for EFSW 3 | * 4 | * Copyright (c) 2017 XadillaX 5 | * 6 | * MIT License 7 | */ 8 | #ifndef __EFSW_CORE_H__ 9 | #define __EFSW_CORE_H__ 10 | #include 11 | #include 12 | #include "./deps/efsw/include/efsw/efsw.hpp" 13 | #include "efsw_core_listener.h" 14 | 15 | namespace efsw_core { 16 | 17 | class EFSWCore : public Nan::ObjectWrap { 18 | public: 19 | static NAN_MODULE_INIT(Init); 20 | 21 | private: 22 | explicit EFSWCore(const char* path, Nan::Callback* listener); 23 | ~EFSWCore(); 24 | 25 | static NAN_METHOD(New); 26 | 27 | private: 28 | std::string path; 29 | Nan::Callback* listener; 30 | efsw::FileWatcher* watcher; 31 | efsw::WatchId watch_id; 32 | EFSWCoreListener core_listener; 33 | }; 34 | 35 | } 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /36. napi/addon.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __first__ { 4 | 5 | napi_value echo(napi_env env, napi_callback_info info) 6 | { 7 | napi_status status; 8 | 9 | size_t argc = 1; 10 | napi_value argv[1]; 11 | status = napi_get_cb_info(env, info, &argc, argv, 0, 0); 12 | if(status != napi_ok || argc < 1) 13 | { 14 | napi_throw_type_error(env, "EBADARGS", "Wrong number of arguments"); 15 | return 0; 16 | } 17 | 18 | return argv[0]; 19 | } 20 | 21 | void init(napi_env env, napi_value exports, napi_value module, void* priv) 22 | { 23 | napi_status status; 24 | 25 | // 用于设置 exports 对象的描述结构体 26 | napi_property_descriptor desc = 27 | { "echo", 0, echo, 0, 0, 0, napi_default, 0 }; 28 | 29 | // 把 "echo" 设置到 exports 去 30 | status = napi_define_properties(env, exports, 1, &desc); 31 | } 32 | 33 | NAPI_MODULE(addon, init) 34 | 35 | } -------------------------------------------------------------------------------- /18. myobject/5/myobject.h: -------------------------------------------------------------------------------- 1 | #ifndef __MYOBJECT_H__ 2 | #define __MYOBJECT_H__ 3 | 4 | #include 5 | #include 6 | 7 | namespace __addon5__ { 8 | 9 | using node::ObjectWrap; 10 | using v8::Object; 11 | using v8::Local; 12 | using v8::Isolate; 13 | using v8::Persistent; 14 | using v8::Value; 15 | using v8::Function; 16 | using v8::FunctionCallbackInfo; 17 | 18 | class MyObject : public ObjectWrap { 19 | public: 20 | static void Init(Isolate* isolate); 21 | static void NewInstance(const FunctionCallbackInfo& args); 22 | double PlusOne(); 23 | inline double value() const { return value_; } 24 | 25 | private: 26 | explicit MyObject(double value = 0); 27 | ~MyObject(); 28 | 29 | static void New(const FunctionCallbackInfo& args); 30 | static void PlusOne(const FunctionCallbackInfo& args); 31 | static Persistent constructor; 32 | double value_; 33 | }; 34 | 35 | } 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /3. function template/template.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __template__ { 4 | 5 | using v8::HandleScope; 6 | using v8::FunctionTemplate; 7 | using v8::FunctionCallbackInfo; 8 | using v8::Function; 9 | using v8::Isolate; 10 | using v8::Local; 11 | using v8::Object; 12 | using v8::String; 13 | using v8::Value; 14 | 15 | void Method(const FunctionCallbackInfo& args) 16 | { 17 | Isolate* isolate = args.GetIsolate(); 18 | args.GetReturnValue().Set(String::NewFromUtf8(isolate, "this is a function")); 19 | } 20 | 21 | void init(Local exports) 22 | { 23 | Isolate* isolate = Isolate::GetCurrent(); 24 | HandleScope scope(isolate); 25 | Local t = FunctionTemplate::New(isolate, Method); 26 | Local fn = t->GetFunction(); 27 | Local name = String::NewFromUtf8(isolate, "funcCreateByTemplate"); 28 | fn->SetName(name); 29 | exports->Set(name, fn); 30 | } 31 | 32 | NODE_MODULE(_template, init) 33 | 34 | } 35 | -------------------------------------------------------------------------------- /24. nan object demo/object.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace __object__ { 5 | 6 | using v8::Local; 7 | using v8::Object; 8 | using v8::String; 9 | 10 | NAN_METHOD(Calc) 11 | { 12 | if(!info.Length()) return; 13 | 14 | auto input = info[0]->ToObject(); 15 | auto output = Nan::New(); 16 | 17 | auto x_prop = Nan::New("x").ToLocalChecked(); 18 | auto y_prop = Nan::New("y").ToLocalChecked(); 19 | auto sum_prop = Nan::New("sum").ToLocalChecked(); 20 | auto product_prop = Nan::New("product").ToLocalChecked(); 21 | 22 | double x = Nan::Get(input, x_prop).ToLocalChecked()->NumberValue(); 23 | double y = Nan::Get(input, y_prop).ToLocalChecked()->NumberValue(); 24 | 25 | Nan::Set(output, sum_prop, Nan::New(x + y)); 26 | Nan::Set(output, product_prop, Nan::New(x * y)); 27 | 28 | info.GetReturnValue().Set(output); 29 | } 30 | 31 | NAN_MODULE_INIT(Init) 32 | { 33 | Nan::Export(target, "calc", Calc); 34 | } 35 | 36 | NODE_MODULE(reverse, Init) 37 | 38 | } 39 | -------------------------------------------------------------------------------- /21. nan array prototype map/map.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __map__ { 4 | 5 | using Nan::FunctionCallbackInfo; 6 | using v8::Local; 7 | using v8::Array; 8 | using v8::Int32; 9 | using v8::Function; 10 | using v8::Object; 11 | using v8::Value; 12 | 13 | void Map(const FunctionCallbackInfo& args) 14 | { 15 | Local array = args[0].As(); 16 | Local func = args[1].As(); 17 | 18 | Local ret = Nan::New(array->Length()); 19 | 20 | Local null = Nan::Null(); 21 | Local a[3] = { Nan::New(), null, array }; 22 | for(uint32_t i = 0; i < array->Length(); i++) 23 | { 24 | a[0] = array->Get(i); 25 | a[1] = Nan::New(i); 26 | 27 | Local v = Nan::MakeCallback(args.This(), func, 3, a); 28 | ret->Set(i, v); 29 | } 30 | 31 | args.GetReturnValue().Set(ret); 32 | } 33 | 34 | NAN_MODULE_INIT(Init) 35 | { 36 | Nan::Export(target, "map", Map); 37 | } 38 | 39 | NODE_MODULE(map, Init) 40 | 41 | } 42 | -------------------------------------------------------------------------------- /17. function factory/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace demo { 4 | 5 | using v8::Function; 6 | using v8::FunctionCallbackInfo; 7 | using v8::FunctionTemplate; 8 | using v8::Isolate; 9 | using v8::Local; 10 | using v8::Object; 11 | using v8::String; 12 | using v8::Value; 13 | 14 | void MyFunction(const FunctionCallbackInfo& args) { 15 | Isolate* isolate = args.GetIsolate(); 16 | args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world")); 17 | } 18 | 19 | void CreateFunction(const FunctionCallbackInfo& args) { 20 | Isolate* isolate = args.GetIsolate(); 21 | 22 | Local tpl = FunctionTemplate::New(isolate, MyFunction); 23 | Local fn = tpl->GetFunction(); 24 | 25 | // omit this to make it anonymous 26 | fn->SetName(String::NewFromUtf8(isolate, "theFunction")); 27 | 28 | args.GetReturnValue().Set(fn); 29 | } 30 | 31 | void Init(Local exports, Local module) { 32 | NODE_SET_METHOD(module, "exports", CreateFunction); 33 | } 34 | 35 | NODE_MODULE(addon, Init) 36 | 37 | } 38 | -------------------------------------------------------------------------------- /34. efsw/src/efsw_core_listener.h: -------------------------------------------------------------------------------- 1 | /** 2 | * node-efsw - Node.js binding for EFSW 3 | * 4 | * Copyright (c) 2017 XadillaX 5 | * 6 | * MIT License 7 | */ 8 | #ifndef __EFSW_CORE_LISTENER_H__ 9 | #define __EFSW_CORE_LISTENER_H__ 10 | #include 11 | #include 12 | #include "./deps/efsw/include/efsw/efsw.hpp" 13 | 14 | namespace efsw_core { 15 | 16 | #define Watch watch 17 | #define AddWatch addWatch 18 | #define HandleFileAction handleFileAction 19 | #define GetLastErrorLog getLastErrorLog 20 | #define WatchId WatchID 21 | 22 | class EFSWCoreListener : public efsw::FileWatchListener { 23 | public: 24 | EFSWCoreListener(Nan::Callback* listener); 25 | ~EFSWCoreListener(); 26 | 27 | void HandleFileAction( 28 | efsw::WatchId, 29 | const std::string& dir, 30 | const std::string& filename, 31 | efsw::Action action, 32 | std::string old_filename); 33 | 34 | private: 35 | Nan::Callback* listener; 36 | }; 37 | 38 | } 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /30. libuv idle/idle.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __idle__ { 4 | 5 | unsigned int idle_times = 0; 6 | uv_idle_t* idle = 0; 7 | 8 | void test_idle(uv_idle_t* handle) 9 | { 10 | // 空转次数减一 11 | idle_times--; 12 | 13 | // 输出点东西 14 | printf("还剩 %u 次空转。\n", idle_times); 15 | 16 | // 若空转次数到达,则该空转停止 17 | if(idle_times == 0) 18 | { 19 | idle = 0; 20 | 21 | // 空转停止 22 | uv_idle_stop(handle); 23 | 24 | // 释放空转句柄 25 | delete handle; 26 | } 27 | } 28 | 29 | NAN_METHOD(StartIdle) 30 | { 31 | if(idle != 0) 32 | { 33 | return Nan::ThrowError("上一个空转仍在进行。"); 34 | } 35 | 36 | idle_times = Nan::To(info[0]).FromJust(); 37 | 38 | idle = new uv_idle_t(); 39 | 40 | // 初始化空转句柄 41 | uv_idle_init(uv_default_loop(), idle); 42 | 43 | // 将 `test_idle` 函数绑定给空转句柄并开始 44 | // 即每个空转阶段都会执行 `test_idle` 函数 45 | uv_idle_start(idle, test_idle); 46 | } 47 | 48 | NAN_MODULE_INIT(Init) 49 | { 50 | Nan::Export(target, "startIdle", StartIdle); 51 | } 52 | 53 | NODE_MODULE(reverse, Init) 54 | 55 | } 56 | -------------------------------------------------------------------------------- /34. efsw/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Khaidi Chu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /34. efsw/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (http://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # Typescript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | build 61 | -------------------------------------------------------------------------------- /14. function parameters/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace demo { 4 | 5 | using v8::Exception; 6 | using v8::FunctionCallbackInfo; 7 | using v8::Isolate; 8 | using v8::Local; 9 | using v8::Number; 10 | using v8::Object; 11 | using v8::String; 12 | using v8::Value; 13 | 14 | // 实现 "add" 函数 15 | void Add(const FunctionCallbackInfo& args) { 16 | Isolate* isolate = args.GetIsolate(); 17 | 18 | // 判断参数个数是否合法 19 | if (args.Length() < 2) { 20 | // 不合法则跑错 21 | isolate->ThrowException(Exception::TypeError( 22 | String::NewFromUtf8(isolate, "Wrong number of arguments"))); 23 | return; 24 | } 25 | 26 | // 判断参数类型是否合法 27 | if (!args[0]->IsNumber() || !args[1]->IsNumber()) { 28 | isolate->ThrowException(Exception::TypeError( 29 | String::NewFromUtf8(isolate, "Wrong arguments"))); 30 | return; 31 | } 32 | 33 | // 计算第一个参数加第二个参数的 `double` 值 34 | // 并新生成一个 Local 句柄,将计算出来的 `double` 传入 35 | double value = args[0]->NumberValue() + args[1]->NumberValue(); 36 | Local num = Number::New(isolate, value); 37 | 38 | // 设置返回值为新生成的 `num` 39 | args.GetReturnValue().Set(num); 40 | } 41 | 42 | void Init(Local exports) { 43 | NODE_SET_METHOD(exports, "add", Add); 44 | } 45 | 46 | NODE_MODULE(addon, Init) 47 | 48 | } 49 | -------------------------------------------------------------------------------- /19. at_exit_hook/at_exit.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | namespace __at_exit__ { 6 | 7 | using node::AtExit; 8 | using v8::HandleScope; 9 | using v8::Isolate; 10 | using v8::Local; 11 | using v8::Object; 12 | 13 | static char cookie[] = "yum yum"; 14 | static int at_exit_cb1_called = 0; 15 | static int at_exit_cb2_called = 0; 16 | 17 | static void at_exit_cb1(void* arg) { 18 | printf("at_exit_cb1 called.\n"); 19 | Isolate* isolate = static_cast(arg); 20 | HandleScope scope(isolate); 21 | Local obj = Object::New(isolate); 22 | assert(!obj.IsEmpty()); // 断言 JavaScript 运行时是否还在运行 23 | assert(obj->IsObject()); 24 | at_exit_cb1_called++; 25 | } 26 | 27 | static void at_exit_cb2(void* arg) { 28 | printf("at_exit_cb2 called.\n"); 29 | assert(arg == static_cast(cookie)); 30 | at_exit_cb2_called++; 31 | } 32 | 33 | static void sanity_check(void*) { 34 | printf("sanity_check called.\n"); 35 | assert(at_exit_cb1_called == 1); 36 | assert(at_exit_cb2_called == 2); 37 | } 38 | 39 | void Init(Local exports) { 40 | AtExit(sanity_check); 41 | AtExit(at_exit_cb2, cookie); 42 | AtExit(at_exit_cb2, cookie); 43 | AtExit(at_exit_cb1, exports->GetIsolate()); 44 | } 45 | 46 | NODE_MODULE(addon, Init) 47 | 48 | } 49 | -------------------------------------------------------------------------------- /2. cpp entry/entry.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __entry__ { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::Function; 7 | using v8::Isolate; 8 | using v8::Local; 9 | using v8::Object; 10 | using v8::String; 11 | using v8::Value; 12 | using v8::HandleScope; 13 | 14 | void RunCallback(const FunctionCallbackInfo& args) 15 | { 16 | Isolate* isolate = Isolate::GetCurrent(); 17 | HandleScope scope(isolate); 18 | 19 | Local cb = Local::Cast(args[0]); 20 | const unsigned argc = 1; 21 | Local argv[argc] = { String::NewFromUtf8(isolate, "hello world") }; 22 | cb->Call(isolate->GetCurrentContext()->Global(), argc, argv); 23 | } 24 | 25 | void init(Local exports, Local module) 26 | { 27 | Isolate* isolate = Isolate::GetCurrent(); 28 | HandleScope scope(isolate); 29 | 30 | NODE_SET_METHOD(exports, "runCallback", RunCallback); 31 | 32 | Local global = isolate->GetCurrentContext()->Global(); 33 | Local console = global->Get(String::NewFromUtf8(isolate, "console"))->ToObject(); 34 | Local log = Local::Cast(console->Get(String::NewFromUtf8(isolate, "log"))); 35 | Local argv[3] = { module, String::NewFromUtf8(isolate, "---"), exports }; 36 | 37 | log->Call(console, 3, argv); 38 | } 39 | 40 | NODE_MODULE(addon, init) 41 | 42 | } -------------------------------------------------------------------------------- /18. myobject/1/myobject.cc: -------------------------------------------------------------------------------- 1 | #include "myobject.h" 2 | 3 | namespace __addon1__ { 4 | 5 | using v8::Isolate; 6 | using v8::FunctionTemplate; 7 | using v8::String; 8 | using v8::Number; 9 | 10 | MyObject::MyObject(double value) : value_(value) 11 | { 12 | } 13 | 14 | MyObject::~MyObject() 15 | { 16 | } 17 | 18 | void MyObject::Init(Local exports) 19 | { 20 | Isolate* isolate = exports->GetIsolate(); 21 | 22 | Local tpl = FunctionTemplate::New(isolate, New); 23 | tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); 24 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 25 | 26 | NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); 27 | 28 | exports->Set(String::NewFromUtf8(isolate, "MyObject"), tpl->GetFunction()); 29 | } 30 | 31 | void MyObject::New(const FunctionCallbackInfo& args) 32 | { 33 | double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); 34 | MyObject* obj = new MyObject(value); 35 | obj->Wrap(args.This()); 36 | 37 | args.GetReturnValue().Set(args.This()); 38 | } 39 | 40 | void MyObject::PlusOne(const FunctionCallbackInfo& args) 41 | { 42 | Isolate* isolate = args.GetIsolate(); 43 | 44 | MyObject* obj = ObjectWrap::Unwrap(args.Holder()); 45 | obj->value_ += 1; 46 | 47 | args.GetReturnValue().Set(Number::New(isolate, obj->value_)); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /34. efsw/src/efsw_core.cc: -------------------------------------------------------------------------------- 1 | /** 2 | * node-efsw - Node.js binding for EFSW 3 | * 4 | * Copyright (c) 2017 XadillaX 5 | * 6 | * MIT License 7 | */ 8 | #include "efsw_core.h" 9 | using namespace efsw; 10 | using namespace v8; 11 | 12 | namespace efsw_core { 13 | 14 | EFSWCore::EFSWCore(const char* path, Nan::Callback* listener) : 15 | path(path), 16 | listener(listener), 17 | core_listener(listener) 18 | { 19 | watcher = new FileWatcher(); 20 | watch_id = watcher->AddWatch(path, &core_listener, true); 21 | } 22 | 23 | EFSWCore::~EFSWCore() 24 | { 25 | Nan::HandleScope scope; 26 | delete watcher; 27 | delete listener; 28 | } 29 | 30 | NAN_METHOD(EFSWCore::New) 31 | { 32 | Nan::Utf8String path(info[0]->ToString()); 33 | Nan::Callback* listener = new Nan::Callback(info[1].As()); 34 | 35 | EFSWCore* core = new EFSWCore(*path, listener); 36 | core->Wrap(info.This()); 37 | info.GetReturnValue().Set(info.This()); 38 | } 39 | 40 | NAN_MODULE_INIT(EFSWCore::Init) 41 | { 42 | v8::Local tpl = Nan::New(New); 43 | tpl->SetClassName(Nan::New("EFSWCore").ToLocalChecked()); 44 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 45 | 46 | Nan::Set(target, Nan::New("EFSWCore").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /11. array prototype map/map.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __map__ { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::HandleScope; 7 | using v8::ObjectTemplate; 8 | using v8::FunctionTemplate; 9 | using v8::Function; 10 | using v8::Isolate; 11 | using v8::Int32; 12 | using v8::Local; 13 | using v8::Context; 14 | using v8::Persistent; 15 | using v8::External; 16 | using v8::Object; 17 | using v8::String; 18 | using v8::Value; 19 | using v8::Number; 20 | using v8::Array; 21 | using v8::MaybeLocal; 22 | 23 | Persistent cons; 24 | 25 | void Map(const FunctionCallbackInfo& args) 26 | { 27 | Isolate* isolate = args.GetIsolate(); 28 | Local context = isolate->GetCurrentContext(); 29 | 30 | Local array = args[0].As(); 31 | Local func = args[1].As(); 32 | 33 | Local ret = Array::New(isolate, array->Length()); 34 | 35 | Local null = v8::Null(isolate); 36 | Local a[3] = { Local(), null, array }; 37 | for(uint32_t i = 0; i < array->Length(); i++) 38 | { 39 | a[0] = array->Get(i); 40 | a[1] = Int32::New(isolate, i); 41 | 42 | MaybeLocal v = func->Call(context, null, 3, a); 43 | ret->Set(i, v.ToLocalChecked()); 44 | } 45 | 46 | args.GetReturnValue().Set(ret); 47 | } 48 | 49 | void Init(Local exports, Local module) 50 | { 51 | Isolate* isolate = Isolate::GetCurrent(); 52 | HandleScope scope(isolate); 53 | 54 | module->Set( 55 | String::NewFromUtf8(isolate, "exports"), 56 | FunctionTemplate::New(isolate, Map)->GetFunction()); 57 | } 58 | 59 | NODE_MODULE(_template, Init) 60 | 61 | } 62 | -------------------------------------------------------------------------------- /28. nan nbodies/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include "nbody.h" 3 | 4 | namespace __nbody__ { 5 | 6 | using v8::Function; 7 | using v8::Local; 8 | using v8::Value; 9 | 10 | class NBodyWorker : public Nan::AsyncWorker { 11 | public: 12 | NBodyWorker(unsigned int times, Nan::Callback* callback) : 13 | times(times), 14 | energy(0), 15 | Nan::AsyncWorker(callback) 16 | { 17 | } 18 | 19 | ~NBodyWorker() {} 20 | 21 | void Execute() 22 | { 23 | NBodySystem bodies; 24 | for(unsigned int i = 0; i < times; i++) bodies.advance(0.01); 25 | energy = bodies.energy(); 26 | } 27 | 28 | void HandleOKCallback() 29 | { 30 | Nan::HandleScope scope; 31 | 32 | Local argv[2] = { 33 | Nan::Undefined(), 34 | Nan::New(energy) 35 | }; 36 | callback->Call(2, argv); 37 | } 38 | 39 | private: 40 | unsigned int times; 41 | double energy; 42 | }; 43 | 44 | NAN_METHOD(Calc) 45 | { 46 | Nan::Callback* callback; 47 | unsigned int times = 50000000; 48 | if(info.Length() > 1) 49 | { 50 | double _times = Nan::To(info[0]).FromJust(); 51 | if(_times < 0) 52 | { 53 | Nan::ThrowRangeError("Wrong times."); 54 | return; 55 | } 56 | 57 | times = _times; 58 | callback = new Nan::Callback(info[1].As()); 59 | } 60 | else 61 | if(info.Length() > 0) 62 | { 63 | callback = new Nan::Callback(info[0].As()); 64 | } 65 | else 66 | { 67 | Nan::ThrowTypeError("Callback needed."); 68 | } 69 | 70 | Nan::AsyncQueueWorker(new NBodyWorker(times, callback)); 71 | } 72 | 73 | NAN_MODULE_INIT(Init) 74 | { 75 | Nan::Export(target, "calc", Calc); 76 | } 77 | 78 | NODE_MODULE(reverse, Init) 79 | 80 | } 81 | -------------------------------------------------------------------------------- /18. myobject/4/myobject.cc: -------------------------------------------------------------------------------- 1 | #include "myobject.h" 2 | 3 | namespace __addon4__ { 4 | 5 | using v8::Isolate; 6 | using v8::FunctionTemplate; 7 | using v8::String; 8 | using v8::Number; 9 | using v8::Context; 10 | 11 | Persistent MyObject::constructor; 12 | 13 | MyObject::MyObject(double value) : value_(value) 14 | { 15 | } 16 | 17 | MyObject::~MyObject() 18 | { 19 | } 20 | 21 | void MyObject::Init(Isolate* isolate) 22 | { 23 | Local tpl = FunctionTemplate::New(isolate, New); 24 | tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); 25 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 26 | 27 | NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); 28 | 29 | constructor.Reset(isolate, tpl->GetFunction()); 30 | } 31 | 32 | void MyObject::New(const FunctionCallbackInfo& args) 33 | { 34 | double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); 35 | MyObject* obj = new MyObject(value); 36 | obj->Wrap(args.This()); 37 | args.GetReturnValue().Set(args.This()); 38 | } 39 | 40 | void MyObject::NewInstance(const FunctionCallbackInfo& args) 41 | { 42 | Isolate* isolate = args.GetIsolate(); 43 | 44 | const int argc = 1; 45 | Local argv[argc] = { args[0] }; 46 | Local context = isolate->GetCurrentContext(); 47 | Local cons = Local::New(isolate, constructor); 48 | Local result = 49 | cons->NewInstance(context, argc, argv).ToLocalChecked(); 50 | args.GetReturnValue().Set(result); 51 | } 52 | 53 | void MyObject::PlusOne(const FunctionCallbackInfo& args) 54 | { 55 | Isolate* isolate = args.GetIsolate(); 56 | 57 | MyObject* obj = ObjectWrap::Unwrap(args.Holder()); 58 | args.GetReturnValue().Set(Number::New(isolate, obj->PlusOne())); 59 | } 60 | 61 | double MyObject::PlusOne() 62 | { 63 | this->value_ += 1; 64 | return this->value_; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /18. myobject/5/myobject.cc: -------------------------------------------------------------------------------- 1 | #include "myobject.h" 2 | 3 | namespace __addon5__ { 4 | 5 | using v8::Isolate; 6 | using v8::FunctionTemplate; 7 | using v8::String; 8 | using v8::Number; 9 | using v8::Context; 10 | 11 | Persistent MyObject::constructor; 12 | 13 | MyObject::MyObject(double value) : value_(value) 14 | { 15 | } 16 | 17 | MyObject::~MyObject() 18 | { 19 | } 20 | 21 | void MyObject::Init(Isolate* isolate) 22 | { 23 | Local tpl = FunctionTemplate::New(isolate, New); 24 | tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); 25 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 26 | 27 | NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); 28 | 29 | constructor.Reset(isolate, tpl->GetFunction()); 30 | } 31 | 32 | void MyObject::New(const FunctionCallbackInfo& args) 33 | { 34 | double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); 35 | MyObject* obj = new MyObject(value); 36 | obj->Wrap(args.This()); 37 | args.GetReturnValue().Set(args.This()); 38 | } 39 | 40 | void MyObject::NewInstance(const FunctionCallbackInfo& args) 41 | { 42 | Isolate* isolate = args.GetIsolate(); 43 | 44 | const int argc = 1; 45 | Local argv[argc] = { args[0] }; 46 | Local context = isolate->GetCurrentContext(); 47 | Local cons = Local::New(isolate, constructor); 48 | Local result = 49 | cons->NewInstance(context, argc, argv).ToLocalChecked(); 50 | args.GetReturnValue().Set(result); 51 | } 52 | 53 | void MyObject::PlusOne(const FunctionCallbackInfo& args) 54 | { 55 | Isolate* isolate = args.GetIsolate(); 56 | 57 | MyObject* obj = ObjectWrap::Unwrap(args.Holder()); 58 | args.GetReturnValue().Set(Number::New(isolate, obj->PlusOne())); 59 | } 60 | 61 | double MyObject::PlusOne() 62 | { 63 | this->value_ += 1; 64 | return this->value_; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /27. nan buffer/buffer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __buffer__ { 4 | 5 | using v8::Local; 6 | using v8::Object; 7 | 8 | void FreeCallback(char* buf, void* hint) 9 | { 10 | printf("Free.\n"); 11 | delete []buf; 12 | printf("Freed.\n"); 13 | } 14 | 15 | NAN_METHOD(PlusOne1) 16 | { 17 | Local old = Nan::To(info[0]).ToLocalChecked(); 18 | 19 | unsigned int length = node::Buffer::Length(old); 20 | char* buf = node::Buffer::Data(old); 21 | 22 | for(unsigned int i = 0; i < length; i++) 23 | { 24 | buf[i] ^= 233; 25 | } 26 | 27 | info.GetReturnValue().Set(Nan::NewBuffer( 28 | buf, 29 | length, 30 | FreeCallback, 31 | 0).ToLocalChecked()); 32 | } 33 | 34 | NAN_METHOD(PlusOne2) 35 | { 36 | Local old = Nan::To(info[0]).ToLocalChecked(); 37 | 38 | unsigned int length = node::Buffer::Length(old); 39 | char* buf = node::Buffer::Data(old); 40 | 41 | for(unsigned int i = 0; i < length; i++) 42 | { 43 | buf[i] ^= 233; 44 | } 45 | 46 | info.GetReturnValue().Set(Nan::CopyBuffer(buf, length).ToLocalChecked()); 47 | } 48 | 49 | NAN_METHOD(PlusOne3) 50 | { 51 | Local old = Nan::To(info[0]).ToLocalChecked(); 52 | 53 | unsigned int length = node::Buffer::Length(old); 54 | char* buf = new char[length]; 55 | memcpy(buf, node::Buffer::Data(old), length); 56 | for(unsigned int i = 0; i < length; i++) 57 | { 58 | buf[i] ^= 233; 59 | } 60 | 61 | info.GetReturnValue().Set(Nan::NewBuffer( 62 | buf, 63 | length, 64 | FreeCallback, 65 | 0).ToLocalChecked()); 66 | } 67 | 68 | NAN_MODULE_INIT(Init) 69 | { 70 | Nan::Export(target, "plusOne1", PlusOne1); 71 | Nan::Export(target, "plusOne2", PlusOne2); 72 | Nan::Export(target, "plusOne3", PlusOne3); 73 | } 74 | 75 | NODE_MODULE(reverse, Init) 76 | 77 | } 78 | -------------------------------------------------------------------------------- /34. efsw/src/efsw_core_listener.cc: -------------------------------------------------------------------------------- 1 | /** 2 | * node-efsw - Node.js binding for EFSW 3 | * 4 | * Copyright (c) 2017 XadillaX 5 | * 6 | * MIT License 7 | */ 8 | #include "efsw_core_listener.h" 9 | using namespace std; 10 | using namespace efsw; 11 | using namespace v8; 12 | 13 | namespace efsw_core { 14 | 15 | struct AsyncArgs { 16 | string dir; 17 | string filename; 18 | string old_filename; 19 | Action action; 20 | Nan::Callback* callback; 21 | 22 | uv_async_t handle; 23 | }; 24 | 25 | void OnAsyncClosed(uv_handle_t* handle) 26 | { 27 | uv_async_t* async = (uv_async_t*)handle; 28 | AsyncArgs* data = (AsyncArgs*)async->data; 29 | delete data; 30 | } 31 | 32 | void OnEFSWEvent(uv_async_t* handle) 33 | { 34 | Nan::HandleScope scope; 35 | AsyncArgs* data = (AsyncArgs*)handle->data; 36 | Local argv[] = { 37 | Nan::New(data->dir.c_str()).ToLocalChecked(), 38 | Nan::New(data->filename.c_str()).ToLocalChecked(), 39 | Nan::New(data->old_filename.c_str()).ToLocalChecked(), 40 | Nan::New(data->action) 41 | }; 42 | data->callback->Call(4, argv); 43 | uv_close((uv_handle_t*)handle, OnAsyncClosed); 44 | } 45 | 46 | EFSWCoreListener::EFSWCoreListener(Nan::Callback* listener) : 47 | listener(listener) 48 | { 49 | } 50 | 51 | EFSWCoreListener::~EFSWCoreListener() 52 | { 53 | } 54 | 55 | void EFSWCoreListener::HandleFileAction( 56 | efsw::WatchId, 57 | const std::string& dir, 58 | const std::string& filename, 59 | efsw::Action action, 60 | std::string old_filename) 61 | { 62 | AsyncArgs* args = new AsyncArgs(); 63 | args->dir = dir; 64 | args->filename = filename; 65 | args->old_filename = old_filename; 66 | args->action = action; 67 | args->callback = listener; 68 | 69 | uv_async_init(uv_default_loop(), &args->handle, OnEFSWEvent); 70 | args->handle.data = (void*)args; 71 | uv_async_send(&args->handle); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /18. myobject/2/myobject.cc: -------------------------------------------------------------------------------- 1 | #include "myobject.h" 2 | 3 | namespace __addon2__ { 4 | 5 | using v8::Isolate; 6 | using v8::FunctionTemplate; 7 | using v8::String; 8 | using v8::Number; 9 | using v8::Context; 10 | 11 | Persistent MyObject::constructor; 12 | 13 | MyObject::MyObject(double value) : value_(value) 14 | { 15 | } 16 | 17 | MyObject::~MyObject() 18 | { 19 | } 20 | 21 | void MyObject::Init(Local exports) 22 | { 23 | Isolate* isolate = exports->GetIsolate(); 24 | 25 | Local tpl = FunctionTemplate::New(isolate, New); 26 | tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); 27 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 28 | 29 | NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); 30 | 31 | constructor.Reset(isolate, tpl->GetFunction()); 32 | exports->Set(String::NewFromUtf8(isolate, "MyObject"), tpl->GetFunction()); 33 | } 34 | 35 | void MyObject::New(const FunctionCallbackInfo& args) 36 | { 37 | Isolate* isolate = args.GetIsolate(); 38 | 39 | if(args.IsConstructCall()) { 40 | // 如果是 `new` 构造函数调用,则逻辑不变 41 | double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); 42 | MyObject* obj = new MyObject(value); 43 | obj->Wrap(args.This()); 44 | args.GetReturnValue().Set(args.This()); 45 | } else { 46 | // 如果不是 `new` 构造函数调用,则通过持久化构造函数句柄生成 47 | const int argc = 1; 48 | Local argv[argc] = { args[0] }; 49 | Local context = isolate->GetCurrentContext(); 50 | Local cons = Local::New(isolate, constructor); 51 | Local result = 52 | cons->NewInstance(context, argc, argv).ToLocalChecked(); 53 | args.GetReturnValue().Set(result); 54 | } 55 | } 56 | 57 | void MyObject::PlusOne(const FunctionCallbackInfo& args) 58 | { 59 | Isolate* isolate = args.GetIsolate(); 60 | 61 | MyObject* obj = ObjectWrap::Unwrap(args.Holder()); 62 | obj->value_ += 1; 63 | 64 | args.GetReturnValue().Set(Number::New(isolate, obj->value_)); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /26. nan json/json.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __array__ { 4 | 5 | using v8::Array; 6 | using v8::Local; 7 | using v8::Object; 8 | using v8::String; 9 | using v8::Value; 10 | 11 | void Plus(Local& obj) 12 | { 13 | if(obj->IsNumber()) 14 | { 15 | obj = Nan::New(Nan::To(obj).FromJust() + 1); 16 | return; 17 | } 18 | if(!obj->IsObject()) return; 19 | 20 | if(obj->IsArray()) 21 | { 22 | auto array = Local::Cast(obj); 23 | for(unsigned int i = 0; i < array->Length(); i++) 24 | { 25 | Local val1; 26 | Local val2; 27 | val1 = val2 = Nan::Get(array, i).ToLocalChecked(); 28 | 29 | Plus(val1); 30 | if(val1 != val2) 31 | { 32 | Nan::Set(array, i, val1); 33 | } 34 | } 35 | return; 36 | } 37 | 38 | Local object = Nan::To(obj).ToLocalChecked(); 39 | auto properties = Nan::GetOwnPropertyNames(object).ToLocalChecked(); 40 | for(unsigned int i = 0; i < properties->Length(); i++) 41 | { 42 | Local key = Nan::To(Nan::Get(properties, i).ToLocalChecked()).ToLocalChecked(); 43 | Local val1; 44 | Local val2; 45 | val1 = val2 = Nan::Get(object, key).ToLocalChecked(); 46 | 47 | Plus(val1); 48 | if(val1 != val2) 49 | { 50 | Nan::Set(object, key, val1); 51 | } 52 | } 53 | return; 54 | } 55 | 56 | NAN_METHOD(PlusOne) 57 | { 58 | Nan::JSON json; 59 | Nan::MaybeLocal parsed = json.Parse(Nan::To(info[0]).ToLocalChecked()); 60 | 61 | if(parsed.IsEmpty()) 62 | { 63 | return info.GetReturnValue().Set(info[0]); 64 | } 65 | 66 | Local ret = parsed.ToLocalChecked(); 67 | Plus(ret); 68 | 69 | info.GetReturnValue().Set(json.Stringify(Nan::To(ret).ToLocalChecked()).ToLocalChecked()); 70 | } 71 | 72 | NAN_MODULE_INIT(Init) 73 | { 74 | Nan::Export(target, "plusOne", PlusOne); 75 | } 76 | 77 | NODE_MODULE(reverse, Init) 78 | 79 | } 80 | -------------------------------------------------------------------------------- /8. internal field wrong/internal_field.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __internal_field_wrong__ { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::HandleScope; 7 | using v8::ObjectTemplate; 8 | using v8::FunctionTemplate; 9 | using v8::Function; 10 | using v8::Isolate; 11 | using v8::Local; 12 | using v8::External; 13 | using v8::Object; 14 | using v8::String; 15 | using v8::Value; 16 | using v8::Number; 17 | using v8::Array; 18 | using v8::MaybeLocal; 19 | 20 | enum Gender { 21 | MALE, 22 | FEMALE 23 | }; 24 | 25 | struct Person { 26 | char name[256]; 27 | int age; 28 | Gender gender; 29 | }; 30 | 31 | void GetSummary(const FunctionCallbackInfo& args) 32 | { 33 | Isolate* isolate = args.GetIsolate(); 34 | Local self = args.Holder(); 35 | Local wrap = Local::Cast(self->GetInternalField(0)); 36 | 37 | Person* person = static_cast(wrap->Value()); 38 | 39 | char ret[512]; 40 | sprintf(ret, "%s,%s,%d 岁。", person->name, person->gender == MALE ? "男" : "女", person->age); 41 | 42 | MaybeLocal summary = String::NewFromUtf8(isolate, ret); 43 | 44 | args.GetReturnValue().Set(summary.ToLocalChecked()); 45 | } 46 | 47 | void Init(Local exports, Local module) 48 | { 49 | Isolate* isolate = Isolate::GetCurrent(); 50 | HandleScope scope(isolate); 51 | 52 | Local templ = ObjectTemplate::New(isolate); 53 | templ->SetInternalFieldCount(1); 54 | 55 | Person* person = new Person(); 56 | 57 | strcpy(person->name, "芙兰朵露·丝卡蕾特"); 58 | person->gender = Gender::FEMALE; 59 | person->age = 495; 60 | 61 | MaybeLocal dummy_obj = templ->NewInstance(); 62 | Local obj = dummy_obj.ToLocalChecked(); 63 | 64 | // 假设 obj 肯定不为空 65 | 66 | obj->SetInternalField(0, External::New(isolate, person)); 67 | obj->Set((MaybeLocal(String::NewFromUtf8(isolate, "getSummary"))).ToLocalChecked(), 68 | FunctionTemplate::New(isolate, GetSummary)->GetFunction()); 69 | 70 | module->Set(String::NewFromUtf8(isolate, "exports"), obj); 71 | } 72 | 73 | NODE_MODULE(_template, Init) 74 | 75 | } 76 | -------------------------------------------------------------------------------- /9. internal field right/internal_field.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __internal_field_right__ { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::HandleScope; 7 | using v8::ObjectTemplate; 8 | using v8::FunctionTemplate; 9 | using v8::Function; 10 | using v8::Isolate; 11 | using v8::Local; 12 | using v8::Persistent; 13 | using v8::External; 14 | using v8::Object; 15 | using v8::String; 16 | using v8::Value; 17 | using v8::Number; 18 | using v8::Array; 19 | using v8::MaybeLocal; 20 | 21 | struct PersistentWrapper { 22 | Persistent persistent; 23 | int value; 24 | }; 25 | 26 | void WeakCallback(const v8::WeakCallbackInfo& data) 27 | { 28 | PersistentWrapper* wrapper = data.GetParameter(); 29 | 30 | if(!wrapper->persistent.IsNearDeath()) 31 | { 32 | printf("WARN...\n"); 33 | } 34 | 35 | printf("deleting 0x%.8X: %d...", wrapper, wrapper->value); // NOLINT 36 | wrapper->persistent.Reset(); 37 | delete wrapper; 38 | printf("ok\n"); 39 | } 40 | 41 | void CreateObject(const FunctionCallbackInfo& args) 42 | { 43 | Isolate* isolate = args.GetIsolate(); 44 | 45 | // 新建对象模板 46 | Local templ = ObjectTemplate::New(isolate); 47 | templ->SetInternalFieldCount(1); 48 | 49 | // 新建对象以及设置内置字段 50 | PersistentWrapper* wrapper = new PersistentWrapper(); 51 | wrapper->value = args[0]->ToNumber()->Int32Value(); 52 | Local obj = templ->NewInstance(); 53 | obj->SetInternalField(0, External::New(isolate, wrapper)); 54 | 55 | // 基于 obj 新建持久句柄 56 | wrapper->persistent.Reset(isolate, obj); 57 | 58 | // 将持久句柄设置为弱持久句柄 59 | wrapper->persistent.SetWeak(wrapper, WeakCallback, v8::WeakCallbackType::kInternalFields); 60 | wrapper->persistent.MarkIndependent(); 61 | 62 | args.GetReturnValue().Set(obj); 63 | } 64 | 65 | void Init(Local exports, Local module) 66 | { 67 | Isolate* isolate = Isolate::GetCurrent(); 68 | HandleScope scope(isolate); 69 | 70 | exports->Set(String::NewFromUtf8(isolate, "create"), FunctionTemplate::New(isolate, CreateObject)->GetFunction()); 71 | } 72 | 73 | NODE_MODULE(_template, Init) 74 | 75 | } 76 | -------------------------------------------------------------------------------- /18. myobject/3/myobject.cc: -------------------------------------------------------------------------------- 1 | #include "myobject.h" 2 | 3 | namespace __addon3__ { 4 | 5 | using v8::Isolate; 6 | using v8::FunctionTemplate; 7 | using v8::String; 8 | using v8::Number; 9 | using v8::Context; 10 | 11 | Persistent MyObject::constructor; 12 | 13 | MyObject::MyObject(double value) : value_(value) 14 | { 15 | } 16 | 17 | MyObject::~MyObject() 18 | { 19 | } 20 | 21 | void MyObject::Init(Local exports) 22 | { 23 | Isolate* isolate = exports->GetIsolate(); 24 | 25 | Local tpl = FunctionTemplate::New(isolate, New); 26 | tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); 27 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 28 | 29 | NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); 30 | 31 | constructor.Reset(isolate, tpl->GetFunction()); 32 | exports->Set(String::NewFromUtf8(isolate, "MyObject"), tpl->GetFunction()); 33 | } 34 | 35 | void MyObject::New(const FunctionCallbackInfo& args) 36 | { 37 | Isolate* isolate = args.GetIsolate(); 38 | 39 | if(args.IsConstructCall()) { 40 | // 如果是 `new` 构造函数调用,则逻辑不变 41 | double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); 42 | MyObject* obj = new MyObject(value); 43 | obj->Wrap(args.This()); 44 | args.GetReturnValue().Set(args.This()); 45 | } else { 46 | // 如果不是 `new` 构造函数调用,则通过持久化构造函数句柄生成 47 | const int argc = 1; 48 | Local argv[argc] = { args[0] }; 49 | Local context = isolate->GetCurrentContext(); 50 | Local cons = Local::New(isolate, constructor); 51 | Local result = 52 | cons->NewInstance(context, argc, argv).ToLocalChecked(); 53 | args.GetReturnValue().Set(result); 54 | } 55 | } 56 | 57 | void MyObject::PlusOne(const FunctionCallbackInfo& args) 58 | { 59 | Isolate* isolate = args.GetIsolate(); 60 | 61 | MyObject* obj = ObjectWrap::Unwrap(args.Holder()); 62 | args.GetReturnValue().Set(Number::New(isolate, obj->PlusOne())); 63 | } 64 | 65 | double MyObject::PlusOne() 66 | { 67 | this->value_ += 1; 68 | return this->value_; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /34. efsw/lib/watcher.js: -------------------------------------------------------------------------------- 1 | /** 2 | * XadillaX created at 2017-08-22 16:19:31 with ❤ 3 | * 4 | * Copyright (c) 2017 xcoder.in, all rights reserved. 5 | */ 6 | "use strict"; 7 | 8 | const EventEmitter = require("events").EventEmitter; 9 | const fs = require("fs"); 10 | const path = require("path"); 11 | 12 | const EFSWCore = require("../build/Release/core").EFSWCore; 13 | 14 | const ACTION_MAP = { 15 | "1": "ADD", 16 | "2": "DELETE", 17 | "3": "MODIFIED", 18 | "4": "MOVED" 19 | }; 20 | 21 | class Watcher extends EventEmitter { 22 | constructor(_path) { 23 | _path = path.resolve(process.cwd(), _path); 24 | 25 | super(); 26 | Object.defineProperties(this, { 27 | path: { 28 | value: _path, 29 | configurable: false, 30 | enumerable: true, 31 | writable: false 32 | }, 33 | core: { 34 | value: new EFSWCore(_path, this._onEFSWEvent.bind(this)), 35 | configurable: false, 36 | enumerable: false, 37 | writable: false 38 | } 39 | }); 40 | 41 | const self = this; 42 | fs.stat(_path, function(err, stat) { 43 | if(err) return self.emit("error", err); 44 | if(!stat.isDirectory()) { 45 | return self.emit("error", new Error(`${_path} is not a directory.`)); 46 | } 47 | }); 48 | } 49 | 50 | _onEFSWEvent(_path, filename, oldFilename, action) { 51 | const fullPath = path.join(_path, filename); 52 | const info = { 53 | dir: _path, 54 | action: ACTION_MAP[action] || "UNKNOWN", 55 | relative: filename 56 | }; 57 | 58 | if(oldFilename) { 59 | info.old = path.join(_path, oldFilename); 60 | info.oldRelative = oldFilename; 61 | } 62 | 63 | if(info.action === "UNKNOWN") { 64 | const err = new Error(`Unknown fs event ${action}.`); 65 | err.info = info; 66 | this.emit("error", err); 67 | } else { 68 | this.emit("change", fullPath, info); 69 | } 70 | } 71 | } 72 | 73 | module.exports = Watcher; 74 | -------------------------------------------------------------------------------- /31. libuv sleep sort/sleep.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace __sleep__ { 5 | 6 | using v8::Array; 7 | using v8::Local; 8 | using v8::Value; 9 | 10 | #ifdef WINDOWS 11 | #include 12 | #else 13 | #include 14 | #endif 15 | 16 | void _Sleep(int sleep_ms) 17 | { 18 | #ifdef WINDOWS 19 | Sleep(sleep_ms); 20 | #else 21 | usleep(sleep_ms * 1000); 22 | #endif 23 | } 24 | 25 | struct ThreadArg { 26 | std::vector* vec; 27 | uint32_t num; 28 | }; 29 | 30 | void Sleep(void* _) 31 | { 32 | ThreadArg* arg = (ThreadArg*)_; 33 | 34 | // 睡上 num * 100 毫秒 35 | _Sleep(arg->num * 100); 36 | arg->vec->push_back(arg->num); 37 | 38 | delete arg; 39 | } 40 | 41 | NAN_METHOD(Sort) 42 | { 43 | if(info.Length() < 1 || !info[0]->IsArray()) 44 | { 45 | return Nan::ThrowError("Wrong argument"); 46 | } 47 | 48 | Local array = info[0].As(); 49 | if(!array->Length()) 50 | { 51 | return info.GetReturnValue().Set(Nan::New()); 52 | } 53 | 54 | std::vector orig; 55 | for(uint32_t i = 0; i < array->Length(); i++) 56 | { 57 | if(!Nan::Get(array, i).ToLocalChecked()->IsUint32()) 58 | { 59 | return Nan::ThrowTypeError("Elements should be unsigned int."); 60 | } 61 | 62 | orig.push_back(Nan::To(Nan::Get(array, i).ToLocalChecked()).FromJust()); 63 | } 64 | 65 | std::vector vec; 66 | std::vector handles(array->Length()); 67 | for(uint32_t i = 0; i < array->Length(); i++) 68 | { 69 | ThreadArg* arg = new ThreadArg(); 70 | arg->vec = &vec; 71 | arg->num = orig[i]; 72 | uv_thread_create(&handles[i], Sleep, arg); 73 | } 74 | 75 | for(uint32_t i = 0; i < handles.size(); i++) 76 | { 77 | uv_thread_join(&handles[i]); 78 | } 79 | 80 | Local ret = Nan::New(); 81 | for(uint32_t i = 0; i < array->Length(); i++) 82 | { 83 | Local v = Nan::New(vec[i]); 84 | Nan::Set(ret, i, v); 85 | } 86 | 87 | info.GetReturnValue().Set(ret); 88 | } 89 | 90 | NAN_MODULE_INIT(Init) 91 | { 92 | Nan::Export(target, "sort", Sort); 93 | } 94 | 95 | NODE_MODULE(sleep, Init) 96 | 97 | } 98 | -------------------------------------------------------------------------------- /22. nan set method/prototype/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __prototype__ { 4 | 5 | using v8::Local; 6 | using v8::Function; 7 | using v8::FunctionTemplate; 8 | using v8::Object; 9 | 10 | Nan::Persistent cons; 11 | 12 | NAN_METHOD(SetName) 13 | { 14 | Nan::Set(info.This(), Nan::New("name").ToLocalChecked(), info[0]); 15 | } 16 | 17 | NAN_METHOD(Summary) 18 | { 19 | Local self = info.This(); 20 | char temp[512]; 21 | 22 | Nan::Utf8String type( 23 | Nan::Get(self, Nan::New("type") 24 | .ToLocalChecked()).ToLocalChecked()->ToString()); 25 | 26 | Nan::Utf8String name( 27 | Nan::Get(self, Nan::New("name") 28 | .ToLocalChecked()).ToLocalChecked()->ToString()); 29 | 30 | snprintf(temp, 511, "%s is a/an %s.", *name, *type); 31 | info.GetReturnValue().Set(Nan::New(temp).ToLocalChecked()); 32 | } 33 | 34 | NAN_METHOD(Pet) 35 | { 36 | Local self = info.This(); 37 | 38 | Nan::Set( 39 | self, 40 | Nan::New("name").ToLocalChecked(), 41 | Nan::New("Unknown").ToLocalChecked()); 42 | 43 | Nan::Set( 44 | self, 45 | Nan::New("type").ToLocalChecked(), 46 | Nan::New("animal").ToLocalChecked()); 47 | 48 | info.GetReturnValue().Set(self); 49 | } 50 | 51 | NAN_METHOD(Dog) 52 | { 53 | Local self = info.This(); 54 | Local super = Nan::New(cons); 55 | 56 | Nan::Call(super, self, 0, NULL); 57 | Nan::Set( 58 | self, 59 | Nan::New("type").ToLocalChecked(), 60 | Nan::New("dog").ToLocalChecked()); 61 | 62 | info.GetReturnValue().Set(self); 63 | } 64 | 65 | NAN_MODULE_INIT(Init) 66 | { 67 | Local pet = Nan::New(Pet); 68 | Nan::SetPrototypeMethod(pet, "setName", SetName); 69 | Nan::SetPrototypeMethod(pet, "summary", Summary); 70 | 71 | Local pet_cons = pet->GetFunction(); 72 | 73 | cons.Reset(pet_cons); 74 | 75 | Local dog = Nan::New(Dog); 76 | dog->Inherit(pet); 77 | 78 | Local dog_cons = dog->GetFunction(); 79 | 80 | Nan::Set(target, Nan::New("Pet").ToLocalChecked(), pet_cons); 81 | Nan::Set(target, Nan::New("Dog").ToLocalChecked(), dog_cons); 82 | } 83 | 84 | NODE_MODULE(prototype, Init) 85 | 86 | } 87 | -------------------------------------------------------------------------------- /12. try catch/try_catch.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __try_catch__ { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::HandleScope; 7 | using v8::ObjectTemplate; 8 | using v8::FunctionTemplate; 9 | using v8::Function; 10 | using v8::Isolate; 11 | using v8::Int32; 12 | using v8::Local; 13 | using v8::Context; 14 | using v8::Persistent; 15 | using v8::External; 16 | using v8::Object; 17 | using v8::String; 18 | using v8::Value; 19 | using v8::Number; 20 | using v8::Array; 21 | using v8::MaybeLocal; 22 | using v8::TryCatch; 23 | using v8::Exception; 24 | 25 | Persistent cons; 26 | 27 | void Get(const FunctionCallbackInfo& args) 28 | { 29 | Isolate* isolate = args.GetIsolate(); 30 | Local context = isolate->GetCurrentContext(); 31 | TryCatch trycatch(isolate); 32 | 33 | MaybeLocal maybe_obj = args[0]->ToObject(context); 34 | MaybeLocal maybe_key = args[1]->ToString(context); 35 | 36 | if(maybe_obj.IsEmpty() || maybe_key.IsEmpty()) 37 | { 38 | if(trycatch.HasCaught()) 39 | trycatch.ReThrow(); 40 | else 41 | args.GetReturnValue().Set(v8::Undefined(isolate)); 42 | 43 | return; 44 | } 45 | 46 | Local obj = maybe_obj.ToLocalChecked(); 47 | Local key = maybe_key.ToLocalChecked(); 48 | 49 | Local ret = obj->Get(context, key).ToLocalChecked(); 50 | args.GetReturnValue().Set(ret); 51 | } 52 | 53 | void Div(const FunctionCallbackInfo& args) 54 | { 55 | // 篇幅所限,使用旧版 API 56 | Isolate* isolate = args.GetIsolate(); 57 | Local a = args[0]->ToInt32(); 58 | Local b = args[1]->ToInt32(); 59 | 60 | int32_t av = a->Value(); 61 | int32_t bv = b->Value(); 62 | 63 | if(bv == 0) 64 | { 65 | isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "除数不能为 0。"))); 66 | return; 67 | } 68 | 69 | args.GetReturnValue().Set(av / bv); 70 | } 71 | 72 | void Init(Local exports, Local module) 73 | { 74 | Isolate* isolate = Isolate::GetCurrent(); 75 | Local context = isolate->GetCurrentContext(); 76 | HandleScope scope(isolate); 77 | 78 | module->Set( 79 | String::NewFromUtf8(isolate, "exports"), 80 | FunctionTemplate::New(isolate, Get)->GetFunction()); 81 | 82 | Local exp = module->Get(context, String::NewFromUtf8(isolate, "exports")).ToLocalChecked().As(); 83 | exp->Set( 84 | String::NewFromUtf8(isolate, "div"), 85 | FunctionTemplate::New(isolate, Div)->GetFunction()); 86 | } 87 | 88 | NODE_MODULE(_template, Init) 89 | 90 | } 91 | -------------------------------------------------------------------------------- /32. libuv sleep sort advanced/sem/sleep.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace __sleep__ { 5 | 6 | using v8::Array; 7 | using v8::Local; 8 | using v8::Value; 9 | 10 | #ifdef WINDOWS 11 | #include 12 | #else 13 | #include 14 | #endif 15 | 16 | void _Sleep(int sleep_ms) 17 | { 18 | #ifdef WINDOWS 19 | Sleep(sleep_ms); 20 | #else 21 | usleep(sleep_ms * 1000); 22 | #endif 23 | } 24 | 25 | struct ThreadArg { 26 | std::vector* vec; 27 | uint32_t num; 28 | uv_sem_t* sem_handle; 29 | }; 30 | 31 | void Sleep(void* _) 32 | { 33 | ThreadArg* arg = (ThreadArg*)_; 34 | 35 | // 睡上 num * 100 毫秒 36 | _Sleep(arg->num * 100); 37 | 38 | uv_sem_wait(arg->sem_handle); 39 | arg->vec->push_back(arg->num); 40 | uv_sem_post(arg->sem_handle); 41 | 42 | delete arg; 43 | } 44 | 45 | NAN_METHOD(Sort) 46 | { 47 | if(info.Length() < 1 || !info[0]->IsArray()) 48 | { 49 | return Nan::ThrowError("Wrong argument"); 50 | } 51 | 52 | Local array = info[0].As(); 53 | if(!array->Length()) 54 | { 55 | return info.GetReturnValue().Set(Nan::New()); 56 | } 57 | 58 | std::vector orig; 59 | for(uint32_t i = 0; i < array->Length(); i++) 60 | { 61 | if(!Nan::Get(array, i).ToLocalChecked()->IsUint32()) 62 | { 63 | return Nan::ThrowTypeError("Elements should be unsigned int."); 64 | } 65 | 66 | orig.push_back(Nan::To(Nan::Get(array, i).ToLocalChecked()).FromJust()); 67 | } 68 | 69 | std::vector vec; 70 | std::vector handles(array->Length()); 71 | uv_sem_t handle; 72 | uv_sem_init(&handle, 1); 73 | for(uint32_t i = 0; i < array->Length(); i++) 74 | { 75 | ThreadArg* arg = new ThreadArg(); 76 | arg->vec = &vec; 77 | arg->num = orig[i]; 78 | arg->sem_handle = &handle; 79 | uv_thread_create(&handles[i], Sleep, arg); 80 | } 81 | 82 | for(uint32_t i = 0; i < handles.size(); i++) 83 | { 84 | uv_thread_join(&handles[i]); 85 | } 86 | 87 | uv_sem_destroy(&handle); 88 | Local ret = Nan::New(); 89 | for(uint32_t i = 0; i < array->Length(); i++) 90 | { 91 | Local v = Nan::New(vec[i]); 92 | Nan::Set(ret, i, v); 93 | } 94 | 95 | info.GetReturnValue().Set(ret); 96 | } 97 | 98 | NAN_MODULE_INIT(Init) 99 | { 100 | Nan::Export(target, "sort", Sort); 101 | } 102 | 103 | NODE_MODULE(mutex_sleep, Init) 104 | 105 | } 106 | -------------------------------------------------------------------------------- /4. object template/template.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace __template__ { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::HandleScope; 7 | using v8::ObjectTemplate; 8 | using v8::FunctionTemplate; 9 | using v8::Function; 10 | using v8::Isolate; 11 | using v8::Local; 12 | using v8::Object; 13 | using v8::String; 14 | using v8::Value; 15 | using v8::Number; 16 | using v8::Array; 17 | 18 | void Constructor(const FunctionCallbackInfo& args) 19 | { 20 | Isolate* isolate = args.GetIsolate(); 21 | args.This()->Set(String::NewFromUtf8(isolate, "value"), Number::New(isolate, 233)); 22 | return args.GetReturnValue().Set(args.This()); 23 | } 24 | 25 | void ClassGet(const FunctionCallbackInfo& args) 26 | { 27 | Isolate* isolate = args.GetIsolate(); 28 | return args.GetReturnValue().Set(args.This()->Get(String::NewFromUtf8(isolate, "value"))); 29 | } 30 | 31 | void Func(const FunctionCallbackInfo& args) 32 | { 33 | args.GetReturnValue().Set(2333); 34 | } 35 | 36 | void Init(Local exports) 37 | { 38 | Isolate* isolate = Isolate::GetCurrent(); 39 | HandleScope scope(isolate); 40 | 41 | // 作为函数模板的原型 42 | Local tpl = FunctionTemplate::New(isolate, Constructor); 43 | tpl->SetClassName(String::NewFromUtf8(isolate, "TestClass")); 44 | Local proto = tpl->PrototypeTemplate(); 45 | proto->Set(String::NewFromUtf8(isolate, "get"), FunctionTemplate::New(isolate, ClassGet)); 46 | 47 | exports->Set(String::NewFromUtf8(isolate, "TestClass"), tpl->GetFunction()); 48 | 49 | // 作为对象模板创建对象 50 | Local fun = FunctionTemplate::New(isolate); 51 | fun->SetClassName(String::NewFromUtf8(isolate, "TestClass2")); 52 | Local obj_tpl = ObjectTemplate::New(isolate, fun); 53 | obj_tpl->Set(String::NewFromUtf8(isolate, "num"), Number::New(isolate, 233)); 54 | Local array = Array::New(isolate, 10); 55 | for(int i = 0; i < 10; i++) 56 | { 57 | array->Set(Number::New(isolate, i), obj_tpl->NewInstance()); 58 | } 59 | exports->Set(String::NewFromUtf8(isolate, "array"), array); 60 | 61 | // 设置函数体 62 | Local obj_with_func_tpl = ObjectTemplate::New(isolate); 63 | obj_with_func_tpl->Set(String::NewFromUtf8(isolate, "cat"), 64 | String::NewFromUtf8(isolate, "南瓜饼")); 65 | obj_with_func_tpl->Set(String::NewFromUtf8(isolate, "dog"), 66 | String::NewFromUtf8(isolate, "蛋花汤")); 67 | obj_with_func_tpl->SetCallAsFunctionHandler(Func); 68 | exports->Set(String::NewFromUtf8(isolate, "func"), obj_with_func_tpl->NewInstance()); 69 | } 70 | 71 | NODE_MODULE(_template, Init) 72 | 73 | } 74 | -------------------------------------------------------------------------------- /29. nan dummy download/download.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "../deps/minihttp/minihttp.h" 4 | 5 | namespace __download__ { 6 | 7 | using v8::Function; 8 | using v8::Local; 9 | using v8::String; 10 | using v8::Value; 11 | using Nan::AsyncProgressWorker; 12 | using namespace std; 13 | 14 | class HttpDumpSocket : public minihttp::HttpSocket { 15 | public: 16 | HttpDumpSocket(const AsyncProgressWorker::ExecutionProgress& progress) : 17 | progress(&progress) 18 | { 19 | } 20 | virtual ~HttpDumpSocket() {} 21 | 22 | protected: 23 | void _OnRecv(void* buf, unsigned int size) 24 | { 25 | if(!size) return; 26 | progress->Send((const char*)buf, size); 27 | } 28 | 29 | private: 30 | const AsyncProgressWorker::ExecutionProgress* progress; 31 | }; 32 | 33 | class DownloadWorker : public AsyncProgressWorker { 34 | public: 35 | DownloadWorker(string uri, Nan::Callback* callback, Nan::Callback* processor) : 36 | AsyncProgressWorker(callback), 37 | processor(processor), 38 | uri(uri) 39 | { 40 | } 41 | 42 | ~DownloadWorker() 43 | { 44 | delete processor; 45 | } 46 | 47 | void Execute(const AsyncProgressWorker::ExecutionProgress& progress) 48 | { 49 | HttpDumpSocket ht(progress); 50 | ht.SetBufsizeIn(64 * 1024); 51 | ht.SetFollowRedirect(true); 52 | ht.SetUserAgent("minihttp"); 53 | ht.SetNonBlocking(false); 54 | ht.SetAlwaysHandle(false); 55 | ht.Download(uri); 56 | while(ht.isOpen() || ht.HasPendingTask()) ht.update(); 57 | } 58 | 59 | void HandleProgressCallback(const char* data, size_t count) 60 | { 61 | Nan::HandleScope scope; 62 | 63 | Local argv[] = { 64 | Nan::CopyBuffer(data, count).ToLocalChecked() 65 | }; 66 | processor->Call(1, argv); 67 | } 68 | 69 | private: 70 | Nan::Callback* processor; 71 | string uri; 72 | }; 73 | 74 | NAN_METHOD(Download) 75 | { 76 | Local uri = Nan::To(info[0]).ToLocalChecked(); 77 | Nan::Utf8String curi(uri); 78 | 79 | Nan::Callback* processor = new Nan::Callback(info[1].As()); 80 | Nan::Callback* callback = new Nan::Callback(info[2].As()); 81 | 82 | Nan::AsyncQueueWorker(new DownloadWorker(*curi, callback, processor)); 83 | } 84 | 85 | static void AtExit(void* arg) 86 | { 87 | minihttp::StopNetwork(); 88 | } 89 | 90 | NAN_MODULE_INIT(Init) 91 | { 92 | minihttp::InitNetwork(); 93 | node::AtExit(AtExit); 94 | 95 | Nan::Export(target, "download", Download); 96 | } 97 | 98 | NODE_MODULE(reverse, Init) 99 | 100 | } 101 | -------------------------------------------------------------------------------- /32. libuv sleep sort advanced/rwlock/sleep.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace __sleep__ { 5 | 6 | using v8::Array; 7 | using v8::Local; 8 | using v8::Value; 9 | 10 | #ifdef WINDOWS 11 | #include 12 | #else 13 | #include 14 | #endif 15 | 16 | void _Sleep(int sleep_ms) 17 | { 18 | #ifdef WINDOWS 19 | Sleep(sleep_ms); 20 | #else 21 | usleep(sleep_ms * 1000); 22 | #endif 23 | } 24 | 25 | struct ThreadArg { 26 | std::vector* vec; 27 | uint32_t num; 28 | uv_rwlock_t* rwlock_handle; 29 | }; 30 | 31 | void Sleep(void* _) 32 | { 33 | ThreadArg* arg = (ThreadArg*)_; 34 | 35 | // 睡上 num * 100 毫秒 36 | _Sleep(arg->num * 100); 37 | 38 | uv_rwlock_wrlock(arg->rwlock_handle); 39 | arg->vec->push_back(arg->num); 40 | uv_rwlock_wrunlock(arg->rwlock_handle); 41 | 42 | // 测试读锁 43 | uv_rwlock_rdlock(arg->rwlock_handle); 44 | printf("当前数组长度:%lu\n", arg->vec->size()); 45 | uv_rwlock_rdunlock(arg->rwlock_handle); 46 | 47 | delete arg; 48 | } 49 | 50 | NAN_METHOD(Sort) 51 | { 52 | if(info.Length() < 1 || !info[0]->IsArray()) 53 | { 54 | return Nan::ThrowError("Wrong argument"); 55 | } 56 | 57 | Local array = info[0].As(); 58 | if(!array->Length()) 59 | { 60 | return info.GetReturnValue().Set(Nan::New()); 61 | } 62 | 63 | std::vector orig; 64 | for(uint32_t i = 0; i < array->Length(); i++) 65 | { 66 | if(!Nan::Get(array, i).ToLocalChecked()->IsUint32()) 67 | { 68 | return Nan::ThrowTypeError("Elements should be unsigned int."); 69 | } 70 | 71 | orig.push_back(Nan::To(Nan::Get(array, i).ToLocalChecked()).FromJust()); 72 | } 73 | 74 | std::vector vec; 75 | std::vector handles(array->Length()); 76 | uv_rwlock_t handle; 77 | uv_rwlock_init(&handle); 78 | for(uint32_t i = 0; i < array->Length(); i++) 79 | { 80 | ThreadArg* arg = new ThreadArg(); 81 | arg->vec = &vec; 82 | arg->num = orig[i]; 83 | arg->rwlock_handle = &handle; 84 | uv_thread_create(&handles[i], Sleep, arg); 85 | } 86 | 87 | for(uint32_t i = 0; i < handles.size(); i++) 88 | { 89 | uv_thread_join(&handles[i]); 90 | } 91 | 92 | uv_rwlock_destroy(&handle); 93 | Local ret = Nan::New(); 94 | for(uint32_t i = 0; i < array->Length(); i++) 95 | { 96 | Local v = Nan::New(vec[i]); 97 | Nan::Set(ret, i, v); 98 | } 99 | 100 | info.GetReturnValue().Set(ret); 101 | } 102 | 103 | NAN_MODULE_INIT(Init) 104 | { 105 | Nan::Export(target, "sort", Sort); 106 | } 107 | 108 | NODE_MODULE(rwlock_sleep, Init) 109 | 110 | } 111 | -------------------------------------------------------------------------------- /32. libuv sleep sort advanced/mutex/sleep.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace __sleep__ { 5 | 6 | using v8::Array; 7 | using v8::Local; 8 | using v8::Value; 9 | 10 | #ifdef WINDOWS 11 | #include 12 | #else 13 | #include 14 | #endif 15 | 16 | struct ScopeLock { 17 | uv_mutex_t* handle; 18 | 19 | ScopeLock(uv_mutex_t* handle) : handle(handle) 20 | { 21 | uv_mutex_lock(handle); 22 | } 23 | 24 | ~ScopeLock() 25 | { 26 | uv_mutex_unlock(handle); 27 | } 28 | }; 29 | 30 | void _Sleep(int sleep_ms) 31 | { 32 | #ifdef WINDOWS 33 | Sleep(sleep_ms); 34 | #else 35 | usleep(sleep_ms * 1000); 36 | #endif 37 | } 38 | 39 | struct ThreadArg { 40 | std::vector* vec; 41 | uint32_t num; 42 | uv_mutex_t* mutex_handle; 43 | }; 44 | 45 | void Sleep(void* _) 46 | { 47 | ThreadArg* arg = (ThreadArg*)_; 48 | 49 | // 睡上 num * 100 毫秒 50 | _Sleep(arg->num * 100); 51 | 52 | ScopeLock lock(arg->mutex_handle); 53 | arg->vec->push_back(arg->num); 54 | 55 | delete arg; 56 | } 57 | 58 | NAN_METHOD(Sort) 59 | { 60 | if(info.Length() < 1 || !info[0]->IsArray()) 61 | { 62 | return Nan::ThrowError("Wrong argument"); 63 | } 64 | 65 | Local array = info[0].As(); 66 | if(!array->Length()) 67 | { 68 | return info.GetReturnValue().Set(Nan::New()); 69 | } 70 | 71 | std::vector orig; 72 | for(uint32_t i = 0; i < array->Length(); i++) 73 | { 74 | if(!Nan::Get(array, i).ToLocalChecked()->IsUint32()) 75 | { 76 | return Nan::ThrowTypeError("Elements should be unsigned int."); 77 | } 78 | 79 | orig.push_back(Nan::To(Nan::Get(array, i).ToLocalChecked()).FromJust()); 80 | } 81 | 82 | std::vector vec; 83 | std::vector handles(array->Length()); 84 | uv_mutex_t handle; 85 | uv_mutex_init(&handle); 86 | for(uint32_t i = 0; i < array->Length(); i++) 87 | { 88 | ThreadArg* arg = new ThreadArg(); 89 | arg->vec = &vec; 90 | arg->num = orig[i]; 91 | arg->mutex_handle = &handle; 92 | uv_thread_create(&handles[i], Sleep, arg); 93 | } 94 | 95 | for(uint32_t i = 0; i < handles.size(); i++) 96 | { 97 | uv_thread_join(&handles[i]); 98 | } 99 | 100 | uv_mutex_destroy(&handle); 101 | Local ret = Nan::New(); 102 | for(uint32_t i = 0; i < array->Length(); i++) 103 | { 104 | Local v = Nan::New(vec[i]); 105 | Nan::Set(ret, i, v); 106 | } 107 | 108 | info.GetReturnValue().Set(ret); 109 | } 110 | 111 | NAN_MODULE_INIT(Init) 112 | { 113 | Nan::Export(target, "sort", Sort); 114 | } 115 | 116 | NODE_MODULE(mutex_sleep, Init) 117 | 118 | } 119 | -------------------------------------------------------------------------------- /33. libuv watchdog/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "efsw", 4 | "type": "static_library", 5 | "sources": [ 6 | "../deps/efsw/src/efsw/Debug.cpp", 7 | "../deps/efsw/src/efsw/DirectorySnapshot.cpp", 8 | "../deps/efsw/src/efsw/DirectorySnapshotDiff.cpp", 9 | "../deps/efsw/src/efsw/DirWatcherGeneric.cpp", 10 | "../deps/efsw/src/efsw/FileInfo.cpp", 11 | "../deps/efsw/src/efsw/FileSystem.cpp", 12 | "../deps/efsw/src/efsw/FileWatcher.cpp", 13 | "../deps/efsw/src/efsw/FileWatcherFSEvents.cpp", 14 | "../deps/efsw/src/efsw/FileWatcherGeneric.cpp", 15 | "../deps/efsw/src/efsw/FileWatcherImpl.cpp", 16 | "../deps/efsw/src/efsw/FileWatcherInotify.cpp", 17 | "../deps/efsw/src/efsw/Log.cpp", 18 | "../deps/efsw/src/efsw/Mutex.cpp", 19 | "../deps/efsw/src/efsw/String.cpp", 20 | "../deps/efsw/src/efsw/System.cpp", 21 | "../deps/efsw/src/efsw/Thread.cpp", 22 | "../deps/efsw/src/efsw/Watcher.cpp", 23 | "../deps/efsw/src/efsw/WatcherFSEvents.cpp", 24 | "../deps/efsw/src/efsw/WatcherGeneric.cpp", 25 | "../deps/efsw/src/efsw/WatcherInotify.cpp" 26 | ], 27 | "include_dirs": [ 28 | "../deps/efsw/include", 29 | "../deps/efsw/src" 30 | ], 31 | "conditions": [ 32 | ["OS==\"win\"", { 33 | "sources": [ 34 | "../deps/efsw/src/efsw/platform/win/FileSystemImpl.cpp", 35 | "../deps/efsw/src/efsw/platform/win/MutexImpl.cpp", 36 | "../deps/efsw/src/efsw/platform/win/SystemImpl.cpp", 37 | "../deps/efsw/src/efsw/platform/win/ThreadImpl.cpp", 38 | "../deps/efsw/src/efsw/FileWatcherWin32.cpp", 39 | "../deps/efsw/src/efsw/WatcherWin32.cpp" 40 | ] 41 | }], 42 | ["OS!=\"win\"", { 43 | "sources": [ 44 | "../deps/efsw/src/efsw/platform/posix/FileSystemImpl.cpp", 45 | "../deps/efsw/src/efsw/platform/posix/MutexImpl.cpp", 46 | "../deps/efsw/src/efsw/platform/posix/SystemImpl.cpp", 47 | "../deps/efsw/src/efsw/platform/posix/ThreadImpl.cpp", 48 | "../deps/efsw/src/efsw/FileWatcherKqueue.cpp", 49 | "../deps/efsw/src/efsw/WatcherKqueue.cpp" 50 | ] 51 | }], 52 | ["OS==\"mac\"", { 53 | "defines": [ 54 | "EFSW_FSEVENTS_SUPPORTED" 55 | ], 56 | "xcode_settings": { 57 | "OTHER_LDFLAGS": [ 58 | "-framework CoreFoundation -framework CoreServices" 59 | ] 60 | } 61 | }] 62 | ] 63 | }, { 64 | "target_name": "watchdog", 65 | "sources": [ 66 | "watchdog.cc" 67 | ], 68 | "include_dirs": [ 69 | " 2 | 3 | namespace __inherit__ { 4 | 5 | using v8::FunctionCallbackInfo; 6 | using v8::HandleScope; 7 | using v8::ObjectTemplate; 8 | using v8::FunctionTemplate; 9 | using v8::Function; 10 | using v8::Isolate; 11 | using v8::Local; 12 | using v8::Persistent; 13 | using v8::External; 14 | using v8::Object; 15 | using v8::String; 16 | using v8::Value; 17 | using v8::Number; 18 | using v8::Array; 19 | using v8::MaybeLocal; 20 | 21 | Persistent cons; 22 | 23 | void SetName(const FunctionCallbackInfo& args) 24 | { 25 | Isolate* isolate = args.GetIsolate(); 26 | 27 | Local self = args.Holder(); 28 | self->Set(String::NewFromUtf8(isolate, "name"), args[0]); 29 | } 30 | 31 | void Summary(const FunctionCallbackInfo& args) 32 | { 33 | Isolate* isolate = args.GetIsolate(); 34 | 35 | Local self = args.Holder(); 36 | char temp[512]; 37 | 38 | String::Utf8Value type(self->Get(String::NewFromUtf8(isolate, "type"))->ToString()); 39 | String::Utf8Value name(self->Get(String::NewFromUtf8(isolate, "name"))->ToString()); 40 | 41 | snprintf(temp, 511, "%s is a/an %s.", *name, *type); 42 | 43 | args.GetReturnValue().Set(String::NewFromUtf8(isolate, temp)); 44 | } 45 | 46 | void Pet(const FunctionCallbackInfo& args) 47 | { 48 | Isolate* isolate = args.GetIsolate(); 49 | 50 | Local self = args.Holder(); 51 | self->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, "Unknown")); 52 | self->Set(String::NewFromUtf8(isolate, "type"), String::NewFromUtf8(isolate, "animal")); 53 | 54 | args.GetReturnValue().Set(self); 55 | } 56 | 57 | void Dog(const FunctionCallbackInfo& args) 58 | { 59 | Isolate* isolate = args.GetIsolate(); 60 | 61 | Local self = args.Holder(); 62 | Local super = cons.Get(isolate); 63 | 64 | super->Call(self, 0, NULL); 65 | self->Set(String::NewFromUtf8(isolate, "type"), String::NewFromUtf8(isolate, "dog")); 66 | 67 | args.GetReturnValue().Set(self); 68 | } 69 | 70 | void Init(Local exports, Local module) 71 | { 72 | Isolate* isolate = Isolate::GetCurrent(); 73 | HandleScope scope(isolate); 74 | 75 | Local pet = FunctionTemplate::New(isolate, Pet); 76 | pet->PrototypeTemplate()->Set( 77 | String::NewFromUtf8(isolate, "setName"), 78 | FunctionTemplate::New(isolate, SetName)); 79 | pet->PrototypeTemplate()->Set( 80 | String::NewFromUtf8(isolate, "summary"), 81 | FunctionTemplate::New(isolate, Summary)); 82 | 83 | Local pet_cons = pet->GetFunction(); 84 | 85 | cons.Reset(isolate, pet_cons); 86 | 87 | Local dog = FunctionTemplate::New(isolate, Dog); 88 | dog->Inherit(pet); 89 | 90 | Local dog_cons = dog->GetFunction(); 91 | 92 | exports->Set(String::NewFromUtf8(isolate, "Pet"), pet_cons); 93 | exports->Set(String::NewFromUtf8(isolate, "Dog"), dog_cons); 94 | } 95 | 96 | NODE_MODULE(_template, Init) 97 | 98 | } 99 | -------------------------------------------------------------------------------- /34. efsw/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "efsw", 4 | "type": "static_library", 5 | "sources": [ 6 | "./src/deps/efsw/src/efsw/Debug.cpp", 7 | "./src/deps/efsw/src/efsw/DirectorySnapshot.cpp", 8 | "./src/deps/efsw/src/efsw/DirectorySnapshotDiff.cpp", 9 | "./src/deps/efsw/src/efsw/DirWatcherGeneric.cpp", 10 | "./src/deps/efsw/src/efsw/FileInfo.cpp", 11 | "./src/deps/efsw/src/efsw/FileSystem.cpp", 12 | "./src/deps/efsw/src/efsw/FileWatcher.cpp", 13 | "./src/deps/efsw/src/efsw/FileWatcherFSEvents.cpp", 14 | "./src/deps/efsw/src/efsw/FileWatcherGeneric.cpp", 15 | "./src/deps/efsw/src/efsw/FileWatcherImpl.cpp", 16 | "./src/deps/efsw/src/efsw/FileWatcherInotify.cpp", 17 | "./src/deps/efsw/src/efsw/Log.cpp", 18 | "./src/deps/efsw/src/efsw/Mutex.cpp", 19 | "./src/deps/efsw/src/efsw/String.cpp", 20 | "./src/deps/efsw/src/efsw/System.cpp", 21 | "./src/deps/efsw/src/efsw/Thread.cpp", 22 | "./src/deps/efsw/src/efsw/Watcher.cpp", 23 | "./src/deps/efsw/src/efsw/WatcherFSEvents.cpp", 24 | "./src/deps/efsw/src/efsw/WatcherGeneric.cpp", 25 | "./src/deps/efsw/src/efsw/WatcherInotify.cpp" 26 | ], 27 | "include_dirs": [ 28 | "./src/deps/efsw/include", 29 | "./src/deps/efsw/src" 30 | ], 31 | "conditions": [ 32 | ["OS==\"win\"", { 33 | "sources": [ 34 | "./src/deps/efsw/src/efsw/platform/win/FileSystemImpl.cpp", 35 | "./src/deps/efsw/src/efsw/platform/win/MutexImpl.cpp", 36 | "./src/deps/efsw/src/efsw/platform/win/SystemImpl.cpp", 37 | "./src/deps/efsw/src/efsw/platform/win/ThreadImpl.cpp", 38 | "./src/deps/efsw/src/efsw/FileWatcherWin32.cpp", 39 | "./src/deps/efsw/src/efsw/WatcherWin32.cpp" 40 | ] 41 | }], 42 | ["OS!=\"win\"", { 43 | "sources": [ 44 | "./src/deps/efsw/src/efsw/platform/posix/FileSystemImpl.cpp", 45 | "./src/deps/efsw/src/efsw/platform/posix/MutexImpl.cpp", 46 | "./src/deps/efsw/src/efsw/platform/posix/SystemImpl.cpp", 47 | "./src/deps/efsw/src/efsw/platform/posix/ThreadImpl.cpp", 48 | "./src/deps/efsw/src/efsw/FileWatcherKqueue.cpp", 49 | "./src/deps/efsw/src/efsw/WatcherKqueue.cpp" 50 | ] 51 | }], 52 | ["OS==\"mac\"", { 53 | "defines": [ 54 | "EFSW_FSEVENTS_SUPPORTED" 55 | ], 56 | "xcode_settings": { 57 | "OTHER_LDFLAGS": [ 58 | "-framework CoreFoundation -framework CoreServices" 59 | ] 60 | } 61 | }] 62 | ] 63 | }, { 64 | "target_name": "core", 65 | "include_dirs": [ 66 | " 2 | #include 3 | #include "../deps/efsw/include/efsw/efsw.hpp" 4 | 5 | namespace __watchdog__ { 6 | 7 | using v8::Array; 8 | using v8::Local; 9 | using v8::Value; 10 | 11 | #define Watch watch 12 | #define AddWatch addWatch 13 | #define HandleFileAction handleFileAction 14 | #define GetLastErrorLog getLastErrorLog 15 | 16 | efsw::FileWatcher* file_watcher; 17 | 18 | struct AsyncArgs { 19 | efsw::WatchID watch_id; 20 | std::string dir; 21 | std::string filename; 22 | efsw::Action action; 23 | std::string old_filename; 24 | uv_async_t handle; 25 | Nan::Callback* callback; 26 | }; 27 | 28 | void OnAsyncClosed(uv_handle_t* handle) 29 | { 30 | uv_async_t* async = (uv_async_t*)handle; 31 | AsyncArgs* data = (AsyncArgs*)async->data; 32 | delete data; 33 | } 34 | 35 | void OnEvent(uv_async_t* handle) 36 | { 37 | Nan::HandleScope scope; 38 | AsyncArgs* data = (AsyncArgs*)handle->data; 39 | Local argv[] = { 40 | Nan::New((int)data->watch_id), 41 | Nan::New(data->dir.c_str()).ToLocalChecked(), 42 | Nan::New(data->filename.c_str()).ToLocalChecked(), 43 | Nan::New(data->action), 44 | Nan::New(data->old_filename.c_str()).ToLocalChecked() 45 | }; 46 | data->callback->Call(5, argv); 47 | uv_close((uv_handle_t*)handle, OnAsyncClosed); 48 | } 49 | 50 | class UpdateListener : public efsw::FileWatchListener { 51 | public: 52 | UpdateListener(Nan::Callback* callback) : 53 | callback(callback) 54 | { 55 | } 56 | 57 | ~UpdateListener() 58 | { 59 | Nan::HandleScope scope; 60 | delete callback; 61 | } 62 | 63 | void HandleFileAction( 64 | efsw::WatchID watchid, 65 | const std::string& dir, 66 | const std::string& filename, 67 | efsw::Action action, 68 | std::string old_filename) 69 | { 70 | AsyncArgs* args = new AsyncArgs(); 71 | args->watch_id = watchid; 72 | args->dir = dir; 73 | args->filename = filename; 74 | args->action = action; 75 | args->old_filename = old_filename; 76 | args->callback = callback; 77 | uv_async_init(uv_default_loop(), &args->handle, OnEvent); 78 | args->handle.data = (void*)args; 79 | uv_async_send(&args->handle); 80 | } 81 | 82 | private: 83 | Nan::Callback* callback; 84 | }; 85 | 86 | std::map > listeners; 87 | 88 | NAN_METHOD(Watch) 89 | { 90 | if(info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) 91 | { 92 | return Nan::ThrowError("Wrong argument"); 93 | } 94 | 95 | Nan::Utf8String path(info[0]->ToString()); 96 | Nan::Callback* callback = new Nan::Callback(info[1].As()); 97 | 98 | // 半成品,没有地方回收该指针 99 | UpdateListener* listener = new UpdateListener(callback); 100 | listeners[*path].push_back(listener); 101 | 102 | efsw::WatchID watch_id = file_watcher->AddWatch(*path, listener, true); 103 | 104 | if(watch_id < 0) 105 | { 106 | return Nan::ThrowError(efsw::Errors::Log::GetLastErrorLog().c_str()); 107 | } 108 | 109 | info.GetReturnValue().Set(Nan::New((int)watch_id)); 110 | } 111 | 112 | NAN_MODULE_INIT(Init) 113 | { 114 | // 半成品,没有地方回收该指针 115 | file_watcher = new efsw::FileWatcher(); 116 | file_watcher->Watch(); 117 | 118 | Nan::Export(target, "watch", Watch); 119 | } 120 | 121 | NODE_MODULE(watchdog, Init) 122 | 123 | } 124 | -------------------------------------------------------------------------------- /7. indexed property interceptor/interceptor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "../deps/minihttp/minihttp.h" 3 | 4 | #ifdef _WIN32 5 | #include 6 | #else 7 | #include 8 | #endif 9 | 10 | namespace __interceptor__ { 11 | 12 | using v8::FunctionCallbackInfo; 13 | using v8::HandleScope; 14 | using v8::EscapableHandleScope; 15 | using v8::ObjectTemplate; 16 | using v8::FunctionTemplate; 17 | using v8::Function; 18 | using v8::Isolate; 19 | using v8::Local; 20 | using v8::Integer; 21 | using v8::MaybeLocal; 22 | using v8::Object; 23 | using v8::String; 24 | using v8::Value; 25 | using v8::Number; 26 | using v8::Array; 27 | using v8::Persistent; 28 | using v8::PropertyCallbackInfo; 29 | using v8::Name; 30 | using v8::PropertyHandlerFlags; 31 | 32 | Local GetList(Isolate* isolate) 33 | { 34 | EscapableHandleScope scope(isolate); 35 | 36 | // 访问 CNode.js API 37 | char* content = minihttp::Download("https://cnodejs.org/api/v1/topics"); 38 | MaybeLocal maybe = v8::JSON::Parse(isolate, String::NewFromUtf8(isolate, content)); 39 | Local ret = maybe.ToLocalChecked(); 40 | free(content); 41 | 42 | // 得到 `data` 数组 43 | Local data = Local::Cast(ret->ToObject()->Get(String::NewFromUtf8(isolate, "data"))->ToObject()); 44 | 45 | printf("fetching %s for %s...ok\n", "https://cnodejs.org/api/v1/topics", "list"); 46 | 47 | return scope.Escape(data); 48 | } 49 | 50 | void __Sleep() 51 | { 52 | #ifdef _WIN32 53 | Sleep(10); 54 | #else 55 | usleep(10); 56 | #endif 57 | } 58 | 59 | void Getter(uint32_t index, const PropertyCallbackInfo& info) 60 | { 61 | Isolate* isolate = info.GetIsolate(); 62 | HandleScope scope(isolate); 63 | 64 | Local data = GetList(isolate); 65 | __Sleep(); 66 | 67 | if(!data.IsEmpty() && index < data->Length()) 68 | { 69 | info.GetReturnValue().Set( 70 | data->Get(Number::New(isolate, index))->ToObject()->Get(String::NewFromUtf8(isolate, "title"))); 71 | } 72 | } 73 | 74 | void Query(uint32_t index, const PropertyCallbackInfo& info) 75 | { 76 | Isolate* isolate = info.GetIsolate(); 77 | HandleScope scope(isolate); 78 | 79 | Local data = GetList(isolate); 80 | __Sleep(); 81 | 82 | if(!data.IsEmpty() && index < data->Length()) 83 | { 84 | info.GetReturnValue().Set( 85 | static_cast(v8::ReadOnly) | 86 | static_cast(v8::DontEnum)); 87 | return; 88 | } 89 | } 90 | 91 | void Enumerator(const PropertyCallbackInfo& info) 92 | { 93 | Isolate* isolate = info.GetIsolate(); 94 | HandleScope scope(isolate); 95 | 96 | Local data = GetList(isolate); 97 | __Sleep(); 98 | 99 | for(unsigned int i = 0; i < data->Length(); i++) 100 | { 101 | data->Set(Number::New(isolate, i), Number::New(isolate, i)); 102 | } 103 | 104 | info.GetReturnValue().Set(data); 105 | } 106 | 107 | void Init(Local exports, Local module) 108 | { 109 | minihttp::InitNetwork(); 110 | atexit(minihttp::StopNetwork); 111 | 112 | Isolate* isolate = Isolate::GetCurrent(); 113 | HandleScope scope(isolate); 114 | 115 | Local tpl = ObjectTemplate::New(isolate); 116 | tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration( 117 | Getter, 118 | 0, 119 | Query, 120 | 0, 121 | Enumerator, 122 | Local(), 123 | PropertyHandlerFlags::kNone)); 124 | 125 | module->Set( 126 | String::NewFromUtf8(isolate, "exports"), 127 | ((v8::MaybeLocal)tpl->NewInstance()).ToLocalChecked()); 128 | } 129 | 130 | NODE_MODULE(indexed_property_interceptor, Init) 131 | 132 | } 133 | -------------------------------------------------------------------------------- /22. nan set method/interceptor/addon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "../../deps/minihttp/minihttp.h" 4 | 5 | #ifdef _WIN32 6 | #include 7 | #else 8 | #include 9 | #endif 10 | 11 | namespace __interceptor__ { 12 | 13 | using v8::Array; 14 | using v8::Number; 15 | using v8::Object; 16 | using v8::ObjectTemplate; 17 | using v8::String; 18 | using v8::Value; 19 | using v8::Local; 20 | 21 | Local GetList() 22 | { 23 | Nan::EscapableHandleScope scope; 24 | Nan::JSON json; 25 | 26 | char* content = minihttp::Download("https://cnodejs.org/api/v1/topics"); 27 | Local ret = json.Parse(Nan::New(content).ToLocalChecked()).ToLocalChecked(); 28 | free(content); 29 | 30 | Local data = Nan::Get(ret->ToObject(), Nan::New("data").ToLocalChecked()) 31 | .ToLocalChecked().As(); 32 | 33 | printf("fetching %s for %s...ok\n", "https://cnodejs.org/api/v1/topics", "list"); 34 | 35 | return scope.Escape(data); 36 | } 37 | 38 | Local GetTopic(const char* id, const char* usage) 39 | { 40 | Nan::EscapableHandleScope scope; 41 | Nan::JSON json; 42 | 43 | int url_length = strlen("https://cnodejs.org/api/v1/topic/") + strlen(id); 44 | char url[url_length + 1]; 45 | url[0] = 0; 46 | strcat(url, "https://cnodejs.org/api/v1/topic/"); 47 | strcat(url, id); 48 | 49 | printf("fetching %s for %s...", url, usage); 50 | 51 | char* content = minihttp::Download(url); 52 | if(0 == content) 53 | { 54 | printf("failed\n"); 55 | return Local(); 56 | } 57 | 58 | Local ret = json.Parse(Nan::New(content).ToLocalChecked()).ToLocalChecked(); 59 | free(content); 60 | 61 | if(Nan::Get(ret->ToObject(), Nan::New("success").ToLocalChecked()) 62 | .ToLocalChecked()->IsFalse()) { 63 | printf("failed\n"); 64 | return Local(); 65 | } 66 | 67 | Local data = Nan::Get(ret->ToObject(), Nan::New("data").ToLocalChecked()) 68 | .ToLocalChecked()->ToObject(); 69 | 70 | printf("ok\n"); 71 | return scope.Escape(data); 72 | } 73 | 74 | void __Sleep() 75 | { 76 | #ifdef _WIN32 77 | Sleep(10); 78 | #else 79 | usleep(10); 80 | #endif 81 | } 82 | 83 | NAN_PROPERTY_GETTER(Getter) 84 | { 85 | if(!property->IsString()) return; 86 | 87 | Nan::Utf8String key(property); 88 | 89 | Local data = GetTopic(*key, "getter"); 90 | __Sleep(); 91 | 92 | if(!data.IsEmpty()) 93 | { 94 | info.GetReturnValue().Set(Nan::Get(data, Nan::New("title").ToLocalChecked()) 95 | .ToLocalChecked()->ToString()); 96 | } 97 | } 98 | 99 | NAN_PROPERTY_QUERY(Query) 100 | { 101 | if(!property->IsString()) return; 102 | 103 | Nan::Utf8String key(property); 104 | 105 | Local data = GetTopic(*key, "query"); 106 | __Sleep(); 107 | 108 | if(!data.IsEmpty()) 109 | { 110 | info.GetReturnValue().Set( 111 | static_cast(v8::ReadOnly) | 112 | static_cast(v8::DontEnum)); 113 | return; 114 | } 115 | } 116 | 117 | NAN_PROPERTY_ENUMERATOR(Enumerator) 118 | { 119 | Local data = GetList(); 120 | __Sleep(); 121 | 122 | for(unsigned int i = 0; i < data->Length(); i++) 123 | { 124 | Local element = Nan::Get(data, Nan::New(i)).ToLocalChecked()->ToObject(); 125 | Local id = Nan::Get(element, Nan::New("id").ToLocalChecked()) 126 | .ToLocalChecked()->ToString(); 127 | Nan::Set(data, Nan::New(i), id); 128 | } 129 | 130 | info.GetReturnValue().Set(data); 131 | } 132 | 133 | NAN_MODULE_INIT(Init) 134 | { 135 | minihttp::InitNetwork(); 136 | atexit(minihttp::StopNetwork); 137 | 138 | Local tpl = Nan::New(); 139 | Nan::SetNamedPropertyHandler(tpl, Getter, 0, Query, 0, Enumerator); 140 | Nan::Set(target, Nan::New("cnode").ToLocalChecked(), tpl->NewInstance()); 141 | } 142 | 143 | NODE_MODULE(interceptor, Init) 144 | 145 | } 146 | -------------------------------------------------------------------------------- /6. mapped property interceptor/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "mbedtls", 4 | "type": "static_library", 5 | "sources": [ 6 | "../deps/mbedtls/library/debug.c", 7 | "../deps/mbedtls/library/net.c", 8 | "../deps/mbedtls/library/ssl_cache.c", 9 | "../deps/mbedtls/library/ssl_ciphersuites.c", 10 | "../deps/mbedtls/library/ssl_cli.c", 11 | "../deps/mbedtls/library/ssl_cookie.c", 12 | "../deps/mbedtls/library/ssl_srv.c", 13 | "../deps/mbedtls/library/ssl_ticket.c", 14 | "../deps/mbedtls/library/ssl_tls.c" 15 | ], 16 | "include_dirs": [ 17 | "../deps/mbedtls/include", 18 | "../deps" 19 | ], 20 | "defines": [ 21 | "MBEDTLS_CONFIG_FILE=\"mbedtls/configs/config-mini-tls1_1.h\"" 22 | ] 23 | }, { 24 | "target_name": "mbedx509", 25 | "type": "static_library", 26 | "sources": [ 27 | "../deps/mbedtls/library/certs.c", 28 | "../deps/mbedtls/library/pkcs11.c", 29 | "../deps/mbedtls/library/x509.c", 30 | "../deps/mbedtls/library/x509_create.c", 31 | "../deps/mbedtls/library/x509_crl.c", 32 | "../deps/mbedtls/library/x509_crt.c", 33 | "../deps/mbedtls/library/x509_csr.c", 34 | "../deps/mbedtls/library/x509write_crt.c", 35 | "../deps/mbedtls/library/x509write_csr.c" 36 | ], 37 | "include_dirs": [ 38 | "../deps/mbedtls/include", 39 | "../deps" 40 | ], 41 | "defines": [ 42 | "MBEDTLS_CONFIG_FILE=\"mbedtls/configs/config-mini-tls1_1.h\"" 43 | ] 44 | }, { 45 | "target_name": "mbedcrypto", 46 | "type": "static_library", 47 | "sources": [ 48 | "../deps/mbedtls/library/aes.c", 49 | "../deps/mbedtls/library/aesni.c", 50 | "../deps/mbedtls/library/arc4.c", 51 | "../deps/mbedtls/library/asn1parse.c", 52 | "../deps/mbedtls/library/asn1write.c", 53 | "../deps/mbedtls/library/base64.c", 54 | "../deps/mbedtls/library/bignum.c", 55 | "../deps/mbedtls/library/blowfish.c", 56 | "../deps/mbedtls/library/camellia.c", 57 | "../deps/mbedtls/library/ccm.c", 58 | "../deps/mbedtls/library/cipher.c", 59 | "../deps/mbedtls/library/cipher_wrap.c", 60 | "../deps/mbedtls/library/ctr_drbg.c", 61 | "../deps/mbedtls/library/des.c", 62 | "../deps/mbedtls/library/dhm.c", 63 | "../deps/mbedtls/library/ecdh.c", 64 | "../deps/mbedtls/library/ecdsa.c", 65 | "../deps/mbedtls/library/ecp.c", 66 | "../deps/mbedtls/library/ecp_curves.c", 67 | "../deps/mbedtls/library/entropy.c", 68 | "../deps/mbedtls/library/entropy_poll.c", 69 | "../deps/mbedtls/library/error.c", 70 | "../deps/mbedtls/library/gcm.c", 71 | "../deps/mbedtls/library/havege.c", 72 | "../deps/mbedtls/library/hmac_drbg.c", 73 | "../deps/mbedtls/library/md.c", 74 | "../deps/mbedtls/library/md2.c", 75 | "../deps/mbedtls/library/md4.c", 76 | "../deps/mbedtls/library/md5.c", 77 | "../deps/mbedtls/library/md_wrap.c", 78 | "../deps/mbedtls/library/memory_buffer_alloc.c", 79 | "../deps/mbedtls/library/oid.c", 80 | "../deps/mbedtls/library/padlock.c", 81 | "../deps/mbedtls/library/pem.c", 82 | "../deps/mbedtls/library/pk.c", 83 | "../deps/mbedtls/library/pk_wrap.c", 84 | "../deps/mbedtls/library/pkcs12.c", 85 | "../deps/mbedtls/library/pkcs5.c", 86 | "../deps/mbedtls/library/pkparse.c", 87 | "../deps/mbedtls/library/pkwrite.c", 88 | "../deps/mbedtls/library/platform.c", 89 | "../deps/mbedtls/library/ripemd160.c", 90 | "../deps/mbedtls/library/rsa.c", 91 | "../deps/mbedtls/library/sha1.c", 92 | "../deps/mbedtls/library/sha256.c", 93 | "../deps/mbedtls/library/sha512.c", 94 | "../deps/mbedtls/library/threading.c", 95 | "../deps/mbedtls/library/timing.c", 96 | "../deps/mbedtls/library/version.c", 97 | "../deps/mbedtls/library/version_features.c", 98 | "../deps/mbedtls/library/xtea.c" 99 | ], 100 | "include_dirs": [ 101 | "../deps/mbedtls/include", 102 | "../deps" 103 | ], 104 | "defines": [ 105 | "MBEDTLS_CONFIG_FILE=\"mbedtls/configs/config-mini-tls1_1.h\"" 106 | ] 107 | }, { 108 | "target_name": "mapped_property_interceptor", 109 | "sources": [ 110 | "../deps/minihttp/minihttp.cpp", 111 | "interceptor.cpp" 112 | ], 113 | "include_dirs": [ 114 | "../deps/mbedtls/include" 115 | ], 116 | "defines": [ "MINIHTTP_USE_MBEDTLS" ], 117 | "dependencies": [ 118 | "mbedtls", 119 | "mbedx509", 120 | "mbedcrypto" 121 | ] 122 | }] 123 | } -------------------------------------------------------------------------------- /7. indexed property interceptor/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "mbedtls", 4 | "type": "static_library", 5 | "sources": [ 6 | "../deps/mbedtls/library/debug.c", 7 | "../deps/mbedtls/library/net.c", 8 | "../deps/mbedtls/library/ssl_cache.c", 9 | "../deps/mbedtls/library/ssl_ciphersuites.c", 10 | "../deps/mbedtls/library/ssl_cli.c", 11 | "../deps/mbedtls/library/ssl_cookie.c", 12 | "../deps/mbedtls/library/ssl_srv.c", 13 | "../deps/mbedtls/library/ssl_ticket.c", 14 | "../deps/mbedtls/library/ssl_tls.c" 15 | ], 16 | "include_dirs": [ 17 | "../deps/mbedtls/include", 18 | "../deps" 19 | ], 20 | "defines": [ 21 | "MBEDTLS_CONFIG_FILE=\"mbedtls/configs/config-mini-tls1_1.h\"" 22 | ] 23 | }, { 24 | "target_name": "mbedx509", 25 | "type": "static_library", 26 | "sources": [ 27 | "../deps/mbedtls/library/certs.c", 28 | "../deps/mbedtls/library/pkcs11.c", 29 | "../deps/mbedtls/library/x509.c", 30 | "../deps/mbedtls/library/x509_create.c", 31 | "../deps/mbedtls/library/x509_crl.c", 32 | "../deps/mbedtls/library/x509_crt.c", 33 | "../deps/mbedtls/library/x509_csr.c", 34 | "../deps/mbedtls/library/x509write_crt.c", 35 | "../deps/mbedtls/library/x509write_csr.c" 36 | ], 37 | "include_dirs": [ 38 | "../deps/mbedtls/include", 39 | "../deps" 40 | ], 41 | "defines": [ 42 | "MBEDTLS_CONFIG_FILE=\"mbedtls/configs/config-mini-tls1_1.h\"" 43 | ] 44 | }, { 45 | "target_name": "mbedcrypto", 46 | "type": "static_library", 47 | "sources": [ 48 | "../deps/mbedtls/library/aes.c", 49 | "../deps/mbedtls/library/aesni.c", 50 | "../deps/mbedtls/library/arc4.c", 51 | "../deps/mbedtls/library/asn1parse.c", 52 | "../deps/mbedtls/library/asn1write.c", 53 | "../deps/mbedtls/library/base64.c", 54 | "../deps/mbedtls/library/bignum.c", 55 | "../deps/mbedtls/library/blowfish.c", 56 | "../deps/mbedtls/library/camellia.c", 57 | "../deps/mbedtls/library/ccm.c", 58 | "../deps/mbedtls/library/cipher.c", 59 | "../deps/mbedtls/library/cipher_wrap.c", 60 | "../deps/mbedtls/library/ctr_drbg.c", 61 | "../deps/mbedtls/library/des.c", 62 | "../deps/mbedtls/library/dhm.c", 63 | "../deps/mbedtls/library/ecdh.c", 64 | "../deps/mbedtls/library/ecdsa.c", 65 | "../deps/mbedtls/library/ecp.c", 66 | "../deps/mbedtls/library/ecp_curves.c", 67 | "../deps/mbedtls/library/entropy.c", 68 | "../deps/mbedtls/library/entropy_poll.c", 69 | "../deps/mbedtls/library/error.c", 70 | "../deps/mbedtls/library/gcm.c", 71 | "../deps/mbedtls/library/havege.c", 72 | "../deps/mbedtls/library/hmac_drbg.c", 73 | "../deps/mbedtls/library/md.c", 74 | "../deps/mbedtls/library/md2.c", 75 | "../deps/mbedtls/library/md4.c", 76 | "../deps/mbedtls/library/md5.c", 77 | "../deps/mbedtls/library/md_wrap.c", 78 | "../deps/mbedtls/library/memory_buffer_alloc.c", 79 | "../deps/mbedtls/library/oid.c", 80 | "../deps/mbedtls/library/padlock.c", 81 | "../deps/mbedtls/library/pem.c", 82 | "../deps/mbedtls/library/pk.c", 83 | "../deps/mbedtls/library/pk_wrap.c", 84 | "../deps/mbedtls/library/pkcs12.c", 85 | "../deps/mbedtls/library/pkcs5.c", 86 | "../deps/mbedtls/library/pkparse.c", 87 | "../deps/mbedtls/library/pkwrite.c", 88 | "../deps/mbedtls/library/platform.c", 89 | "../deps/mbedtls/library/ripemd160.c", 90 | "../deps/mbedtls/library/rsa.c", 91 | "../deps/mbedtls/library/sha1.c", 92 | "../deps/mbedtls/library/sha256.c", 93 | "../deps/mbedtls/library/sha512.c", 94 | "../deps/mbedtls/library/threading.c", 95 | "../deps/mbedtls/library/timing.c", 96 | "../deps/mbedtls/library/version.c", 97 | "../deps/mbedtls/library/version_features.c", 98 | "../deps/mbedtls/library/xtea.c" 99 | ], 100 | "include_dirs": [ 101 | "../deps/mbedtls/include", 102 | "../deps" 103 | ], 104 | "defines": [ 105 | "MBEDTLS_CONFIG_FILE=\"mbedtls/configs/config-mini-tls1_1.h\"" 106 | ] 107 | }, { 108 | "target_name": "indexed_property_interceptor", 109 | "sources": [ 110 | "../deps/minihttp/minihttp.cpp", 111 | "interceptor.cpp" 112 | ], 113 | "include_dirs": [ 114 | "../deps/mbedtls/include" 115 | ], 116 | "defines": [ "MINIHTTP_USE_MBEDTLS" ], 117 | "dependencies": [ 118 | "mbedtls", 119 | "mbedx509", 120 | "mbedcrypto" 121 | ] 122 | }] 123 | } -------------------------------------------------------------------------------- /22. nan set method/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [{ 3 | "target_name": "prototype", 4 | "sources": [ 5 | "prototype/addon.cc" 6 | ], 7 | "include_dirs": [ 8 | " 2 | 3 | namespace __accessor__ { 4 | 5 | using v8::Context; 6 | using v8::External; 7 | using v8::FunctionCallbackInfo; 8 | using v8::HandleScope; 9 | using v8::ObjectTemplate; 10 | using v8::FunctionTemplate; 11 | using v8::Function; 12 | using v8::Isolate; 13 | using v8::Local; 14 | using v8::MaybeLocal; 15 | using v8::Object; 16 | using v8::String; 17 | using v8::Value; 18 | using v8::Number; 19 | using v8::Array; 20 | using v8::Persistent; 21 | using v8::PropertyCallbackInfo; 22 | 23 | int x = 0; 24 | 25 | // Mentioned @ https://github.com/XadillaX/nyaa-nodejs-demo/issues/2 26 | #define CURRENT_CONTEXT(ctx) Isolate* isolate = Isolate::GetCurrent(); \ 27 | Local ctx = isolate->GetCurrentContext(); 28 | 29 | void Getter1(Local property, const PropertyCallbackInfo& info) 30 | { 31 | info.GetReturnValue().Set(x); 32 | } 33 | 34 | void Setter1(Local property, Local value, const PropertyCallbackInfo& info) 35 | { 36 | #if NODE_MODULE_VERSION >= 67 // Node.js 11.0.0+ 37 | CURRENT_CONTEXT(context); 38 | x = value->Int32Value(context).FromJust(); 39 | #else 40 | x = value->Int32Value(); 41 | #endif 42 | } 43 | 44 | void Getter2(Local property, const PropertyCallbackInfo& info) 45 | { 46 | #if NODE_MODULE_VERSION >= 67 // Node.js 11.0.0+ 47 | CURRENT_CONTEXT(context); 48 | info.GetReturnValue().Set( 49 | info.Data()->ToObject(context).ToLocalChecked()->Get(String::NewFromUtf8(info.GetIsolate(), "inner"))); 50 | #else 51 | info.GetReturnValue().Set(info.Data()->ToObject()->Get(String::NewFromUtf8(info.GetIsolate(), "inner"))); 52 | #endif 53 | } 54 | 55 | void Setter2(Local property, Local value, const PropertyCallbackInfo& info) 56 | { 57 | #if NODE_MODULE_VERSION >= 67 58 | CURRENT_CONTEXT(context); 59 | info.Data()->ToObject(context).ToLocalChecked()->Set(String::NewFromUtf8(info.GetIsolate(), "inner"), value); 60 | #else 61 | info.Data()->ToObject()->Set(String::NewFromUtf8(info.GetIsolate(), "inner"), value); 62 | #endif 63 | } 64 | 65 | class TestExternal { 66 | public: 67 | TestExternal(Local obj) 68 | { 69 | value = 233; 70 | _handle.Reset(Isolate::GetCurrent(), obj); 71 | _handle.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter); 72 | _handle.MarkIndependent(); 73 | } 74 | 75 | ~TestExternal() 76 | { 77 | } 78 | 79 | void Set(int _value) 80 | { 81 | value = _value; 82 | } 83 | 84 | int Get() 85 | { 86 | return value; 87 | } 88 | 89 | Persistent _handle; 90 | 91 | static void WeakCallback(const v8::WeakCallbackInfo& data) 92 | { 93 | TestExternal* ex = data.GetParameter(); 94 | ex->_handle.Reset(); 95 | delete ex; 96 | } 97 | 98 | private: 99 | int value; 100 | }; 101 | 102 | void Getter3(Local property, const PropertyCallbackInfo& info) 103 | { 104 | Local self = info.Holder(); 105 | Local wrap = Local::Cast(self->GetInternalField(0)); 106 | void* ptr = wrap->Value(); 107 | TestExternal* ex = (TestExternal*)ptr; 108 | 109 | info.GetReturnValue().Set(ex->Get()); 110 | } 111 | 112 | void Setter3(Local property, Local value, const PropertyCallbackInfo& info) 113 | { 114 | #if NODE_MODULE_VERSION >= 67 // Node.js 11.0.0+ 115 | CURRENT_CONTEXT(context); 116 | #endif 117 | 118 | Local self = info.Holder(); 119 | Local wrap = Local::Cast(self->GetInternalField(0)); 120 | void* ptr = wrap->Value(); 121 | TestExternal* ex = (TestExternal*)ptr; 122 | 123 | #if NODE_MODULE_VERSION >= 67 // Node.js 11.0.0+ 124 | ex->Set(value->ToInt32(context).ToLocalChecked()->Value()); 125 | #else 126 | ex->Set(value->ToInt32()->Value()); 127 | #endif 128 | } 129 | 130 | void Init(Local exports, Local module) 131 | { 132 | Isolate* isolate = Isolate::GetCurrent(); 133 | HandleScope scope(isolate); 134 | 135 | // 全局变量 136 | Local tpl = ObjectTemplate::New(isolate); 137 | tpl->SetInternalFieldCount(1); 138 | tpl->SetAccessor(String::NewFromUtf8(isolate, "var1"), Getter1, Setter1); 139 | 140 | // 类全局变量 141 | Local inner = Object::New(isolate); 142 | inner->Set(String::NewFromUtf8(isolate, "inner"), String::NewFromUtf8(isolate, "蛋花汤")); 143 | tpl->SetAccessor(String::NewFromUtf8(isolate, "var2"), Getter2, Setter2, inner); 144 | 145 | // 动态变量 146 | tpl->SetAccessor(String::NewFromUtf8(isolate, "var3"), Getter3, Setter3); 147 | 148 | Local ret = ((MaybeLocal)tpl->NewInstance()).ToLocalChecked(); 149 | TestExternal* ex = new TestExternal(ret); 150 | ret->SetInternalField(0, External::New(isolate, ex)); 151 | 152 | module->Set(String::NewFromUtf8(isolate, "exports"), ret); 153 | } 154 | 155 | NODE_MODULE(accessor, Init) 156 | 157 | } 158 | -------------------------------------------------------------------------------- /6. mapped property interceptor/interceptor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "../deps/minihttp/minihttp.h" 3 | 4 | #ifdef _WIN32 5 | #include 6 | #else 7 | #include 8 | #endif 9 | 10 | namespace __interceptor__ { 11 | 12 | using v8::FunctionCallbackInfo; 13 | using v8::HandleScope; 14 | using v8::EscapableHandleScope; 15 | using v8::ObjectTemplate; 16 | using v8::FunctionTemplate; 17 | using v8::Function; 18 | using v8::Isolate; 19 | using v8::Local; 20 | using v8::Integer; 21 | using v8::MaybeLocal; 22 | using v8::Object; 23 | using v8::String; 24 | using v8::Value; 25 | using v8::Number; 26 | using v8::Array; 27 | using v8::Persistent; 28 | using v8::PropertyCallbackInfo; 29 | using v8::Name; 30 | using v8::PropertyHandlerFlags; 31 | 32 | Local GetList(Isolate* isolate) 33 | { 34 | EscapableHandleScope scope(isolate); 35 | 36 | // 访问 CNode.js API 37 | char* content = minihttp::Download("https://cnodejs.org/api/v1/topics"); 38 | MaybeLocal maybe = v8::JSON::Parse(isolate, String::NewFromUtf8(isolate, content)); 39 | Local ret = maybe.ToLocalChecked(); 40 | free(content); 41 | 42 | // 得到 `data` 数组 43 | Local data = Local::Cast(ret->ToObject()->Get(String::NewFromUtf8(isolate, "data"))->ToObject()); 44 | 45 | printf("fetching %s for %s...ok\n", "https://cnodejs.org/api/v1/topics", "list"); 46 | 47 | return scope.Escape(data); 48 | } 49 | 50 | Local GetTopic(Isolate* isolate, const char* id, const char* usage) 51 | { 52 | EscapableHandleScope scope(isolate); 53 | 54 | int url_length = strlen("https://cnodejs.org/api/v1/topic/") + strlen(id); 55 | char url[url_length + 1]; 56 | url[0] = 0; 57 | strcat(url, "https://cnodejs.org/api/v1/topic/"); 58 | strcat(url, id); 59 | 60 | printf("fetching %s for %s...", url, usage); 61 | 62 | // 访问 CNode.js API 63 | char* content = minihttp::Download(url); 64 | if(0 == content) 65 | { 66 | printf("failed\n"); 67 | return Local(); 68 | } 69 | MaybeLocal maybe = v8::JSON::Parse(isolate, String::NewFromUtf8(isolate, content)); 70 | Local ret = maybe.ToLocalChecked(); 71 | 72 | free(content); 73 | 74 | if(ret->ToObject()->Get(String::NewFromUtf8(isolate, "success"))->ToBoolean()->IsFalse()) { 75 | printf("failed\n"); 76 | return Local(); 77 | } 78 | 79 | // 得到 `data` 数据 80 | Local data = ret->ToObject()->Get(String::NewFromUtf8(isolate, "data"))->ToObject(); 81 | 82 | printf("ok\n"); 83 | return scope.Escape(data); 84 | } 85 | 86 | void __Sleep() 87 | { 88 | #ifdef _WIN32 89 | Sleep(10); 90 | #else 91 | usleep(10); 92 | #endif 93 | } 94 | 95 | void Getter(Local property, const PropertyCallbackInfo& info) 96 | { 97 | Isolate* isolate = info.GetIsolate(); 98 | HandleScope scope(isolate); 99 | 100 | String::Utf8Value key(property); 101 | 102 | Local data = GetTopic(isolate, *key, "getter"); 103 | __Sleep(); 104 | 105 | if(!data.IsEmpty()) 106 | { 107 | info.GetReturnValue().Set(data->Get(String::NewFromUtf8(isolate, "title"))->ToString()); 108 | } 109 | } 110 | 111 | void Query(Local property, const PropertyCallbackInfo& info) 112 | { 113 | Isolate* isolate = info.GetIsolate(); 114 | HandleScope scope(isolate); 115 | 116 | String::Utf8Value key(property); 117 | 118 | Local data = GetTopic(isolate, *key, "query"); 119 | __Sleep(); 120 | 121 | if(!data.IsEmpty()) 122 | { 123 | info.GetReturnValue().Set( 124 | static_cast(v8::ReadOnly) | 125 | static_cast(v8::DontEnum)); 126 | return; 127 | } 128 | } 129 | 130 | void Enumerator(const PropertyCallbackInfo& info) 131 | { 132 | Isolate* isolate = info.GetIsolate(); 133 | HandleScope scope(isolate); 134 | 135 | Local data = GetList(isolate); 136 | __Sleep(); 137 | 138 | for(unsigned int i = 0; i < data->Length(); i++) 139 | { 140 | Local element = data->Get(Number::New(isolate, i))->ToObject(); 141 | Local id = element->Get(String::NewFromUtf8(isolate, "id"))->ToString(); 142 | data->Set(Number::New(isolate, i), id); 143 | } 144 | 145 | info.GetReturnValue().Set(data); 146 | } 147 | 148 | void Init(Local exports, Local module) 149 | { 150 | minihttp::InitNetwork(); 151 | atexit(minihttp::StopNetwork); 152 | 153 | Isolate* isolate = Isolate::GetCurrent(); 154 | HandleScope scope(isolate); 155 | 156 | Local tpl = ObjectTemplate::New(isolate); 157 | tpl->SetHandler(v8::NamedPropertyHandlerConfiguration( 158 | Getter, 159 | 0, 160 | Query, 161 | 0, 162 | Enumerator, 163 | Local(), 164 | PropertyHandlerFlags::kOnlyInterceptStrings)); 165 | 166 | module->Set( 167 | String::NewFromUtf8(isolate, "exports"), 168 | ((v8::MaybeLocal)tpl->NewInstance()).ToLocalChecked()); 169 | } 170 | 171 | NODE_MODULE(mapped_property_interceptor, Init) 172 | 173 | } 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 《Node.js:来一打 C++ 扩展》随书源码 2 | 3 | ![封面](cover.jpg) 4 | 5 | [English Document](README_en.md) 6 | 7 | 本仓库为死月所著《Node.js:来一打 C++ 扩展》的随书源码,大家尽情享用。 8 | 9 | > **注意**:所有的随书代码均在 macOS 命令行下 Node.js 6.x 测试通过。理论上,它们也可以在 Windows 和 UNIX 上运行良好,但我并没有验证过。 10 | 11 | ## 下载 12 | 13 | 本源码可从博文视点官方网站上下载。如果你对 [Git](https://git-scm.com/) 熟悉,且愿意使用 Git 克隆本仓库使用源码,非常欢迎。 14 | 15 | 如果需要克隆本仓库,可以使用以下命令行: 16 | 17 | ```shell 18 | $ git clone https://github.com/XadillaX/nyaa-nodejs-demo.git --recurse-submodules 19 | ``` 20 | 21 | > `--recurse-submodules` 参数允许你连通 submodule 一起克隆下来。 22 | > 23 | > 由于 GitHub 的特性,如果你直接从 GitHub 的本页面上直接通过 **Download ZIP** 链接下载压缩包,将不会包含一些必要依赖的 submodule。所以如果你想通过压缩包下载的形式获取源码,请转到博文视点官方网站。 24 | 25 | ## 快速导航 26 | 27 | 1. [first build](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/1.%20first%20build):「1.4.2. node-gyp」 28 | 2. [cpp entry](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/2.%20cpp%20entry):「2.2.2. Node.js 模块加载原理」 29 | 3. [function template](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/3.%20function%20template):「3.6.1. 函数模板(Function Template)」 30 | 4. [object template](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/4.%20object%20template):「3.6.2. 对象模板(Object Template)」 31 | 5. [object template accessor](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/5.%20object%20template%20accessor):「3.6.3. 对象模板的访问器(Accessor)与拦截器(Interceptor)」 32 | 6. [mapped property interceptor](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/6.%20mapped%20property%20interceptor):「3.6.3. 对象模板的访问器(Accessor)与拦截器(Interceptor)」 33 | 7. [indexed property interceptor](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/7.%20indexed%20property%20interceptor):「3.6.3. 对象模板的访问器(Accessor)与拦截器(Interceptor)」 34 | 8. [internal field wrong](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/8.%20internal%20field%20wrong):「3.6.4. 对象模板的内置字段(Internal Field)」 35 | 9. [internal field right](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/9.%20internal%20field%20right):「3.6.4. 对象模板的内置字段(Internal Field)」 36 | 10. [function template inherit](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/10.%20function%20template%20inherit):「3.6.5. 函数模板的继承(Inherit)」 37 | 11. [array prototype map](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/11.%20array%20prototype%20map):「3.7.6. 函数(Function)」 38 | 12. [try catch](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/12.%20try%20catch):「3.8.1. Try-Catch」 39 | 13. [hello world again](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/13.%20hello%20world%20again):「4.2.1. 又是 Hello World」 40 | 14. [function parameters](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/14.%20function%20parameters):「4.2.2. 函数参数」 41 | 15. [run callback](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/15.%20run%20callback):「4.2.3. 回调函数」 42 | 16. [object factory](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/16.%20object%20factory):「4.2.4. 对象返回」 43 | 17. [function factory](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/17.%20function%20factory):「4.2.5. 函数返回」 44 | 18. [myobject](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/18.%20myobject):「4.3.1. C++ 与 JavaScript 类封装」 45 | 19. [at_exit_hook](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/19.%20at_exit_hook):「4.3.4. 进程退出钩子」 46 | 20. [nan echo](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/20.%20nan%20echo):「5.2.3. 来不及解释了,先上车」 47 | 21. [nan array prototype map](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/21.%20nan%20array%20prototype%20map):「5.2.4. 基础帮助函数和宏」 48 | 22. [nan set method](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/22.%20nan%20set%20method):「5.3.3. 函数设置」 49 | 23. [nan reverse string](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/23.%20nan%20reverse%20string):「5.4.3. 与数据对象“玩耍”」 50 | 24. [nan object demo](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/24.%20nan%20object%20demo):「5.4.3. 与数据对象“玩耍”」 51 | 25. [nan array demo](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/25.%20nan%20array%20demo):「5.4.3. 与数据对象“玩耍”」 52 | 26. [nan json](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/26.%20nan%20json):「5.4.3. 与数据对象“玩耍”」 53 | 27. [nan buffer](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/27.%20nan%20buffer):「5.4.3. 与数据对象“玩耍”」 54 | 28. [nan nbodies](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/28.%20nan%20nbodies):「5.5.3. Nan::AsyncWorker」 55 | 29. [nan dummy download](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/29.%20nan%20dummy%20download):「5.5.4. Nan::AsyncProgressWorker」 56 | 30. [libuv idle](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/30.%20libuv%20idle):「6.1.3. 尝个甜头」 57 | 31. [libuv sleep sort](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/31.%20libuv%20sleep%20sort):「6.2.1. libuv 的线程」 58 | 32. [libuv sleep sort advanced](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/32.%20libuv%20sleep%20sort%20advanced):「6.2.2. 同步原语(Synchronization Primitives)」 59 | 33. [libuv watchdog](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/33.%20libuv%20watchdog):「6.3.2. Watchdog 半成品实战解析」 60 | 34. [efsw](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/34.%20efsw):「7.1.1. 功能规划」 61 | 35. [efsw advanced](https://github.com/XadillaX/node-efsw/tree/85cc5b816c3e04b4df92f63592f5e9ce99808418):「7.4.2. JavaScript 代码完善」 62 | 36. [napi](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/36.%20napi):「9.1.1. 实现一个 `Echo` 函数」 63 | 64 | ## 购书链接 65 | 66 | + [京东](https://item.jd.com/12380404.html) 67 | + [天猫](https://detail.tmall.com/item.htm?id=571628730908&cat_id=2) 68 | + [当当](http://product.dangdang.com/25291814.html) 69 | + [亚马逊](https://www.amazon.cn/dp/B07DL8GHQC/ie=UTF8&qid=1528969734) 70 | + [china-pub](http://product.china-pub.com/8039217) 71 | + [豆瓣](https://book.douban.com/subject/30247892/)(不算购书链接) 72 | 73 | ## QQ 交流群 74 | 75 | QQ 群 76 | 77 | ## 感谢阅读 78 | 79 | 最后,感谢大家支持本书。 80 | 81 | ![フランドール・スカーレット](flandre.jpg) 82 | 83 |
图片来自 Pixiv
84 | -------------------------------------------------------------------------------- /28. nan nbodies/nbody.cc: -------------------------------------------------------------------------------- 1 | #include "nbody.h" 2 | using namespace std; 3 | 4 | namespace __nbody__ { 5 | 6 | static const double PI = 3.141592653589793; 7 | static const double SOLAR_MASS = 4 * PI * PI; 8 | static const double DAYS_PER_YEAR = 365.24; 9 | 10 | Body::Body() 11 | { 12 | } 13 | 14 | Body& Body::jupiter() 15 | { 16 | static Body p; 17 | p.x = 4.84143144246472090e+00; 18 | p.y = -1.16032004402742839e+00; 19 | p.z = -1.03622044471123109e-01; 20 | p.vx = 1.66007664274403694e-03 * DAYS_PER_YEAR; 21 | p.vy = 7.69901118419740425e-03 * DAYS_PER_YEAR; 22 | p.vz = -6.90460016972063023e-05 * DAYS_PER_YEAR; 23 | p.mass = 9.54791938424326609e-04 * SOLAR_MASS; 24 | return p; 25 | } 26 | 27 | Body& Body::saturn() 28 | { 29 | static Body p; 30 | p.x = 8.34336671824457987e+00; 31 | p.y = 4.12479856412430479e+00; 32 | p.z = -4.03523417114321381e-01; 33 | p.vx = -2.76742510726862411e-03 * DAYS_PER_YEAR; 34 | p.vy = 4.99852801234917238e-03 * DAYS_PER_YEAR; 35 | p.vz = 2.30417297573763929e-05 * DAYS_PER_YEAR; 36 | p.mass = 2.85885980666130812e-04 * SOLAR_MASS; 37 | return p; 38 | } 39 | 40 | Body& Body::uranus() 41 | { 42 | static Body p; 43 | p.x = 1.28943695621391310e+01; 44 | p.y = -1.51111514016986312e+01; 45 | p.z = -2.23307578892655734e-01; 46 | p.vx = 2.96460137564761618e-03 * DAYS_PER_YEAR; 47 | p.vy = 2.37847173959480950e-03 * DAYS_PER_YEAR; 48 | p.vz = -2.96589568540237556e-05 * DAYS_PER_YEAR; 49 | p.mass = 4.36624404335156298e-05 * SOLAR_MASS; 50 | return p; 51 | } 52 | 53 | Body& Body::neptune() 54 | { 55 | static Body p; 56 | p.x = 1.53796971148509165e+01; 57 | p.y = -2.59193146099879641e+01; 58 | p.z = 1.79258772950371181e-01; 59 | p.vx = 2.68067772490389322e-03 * DAYS_PER_YEAR; 60 | p.vy = 1.62824170038242295e-03 * DAYS_PER_YEAR; 61 | p.vz = -9.51592254519715870e-05 * DAYS_PER_YEAR; 62 | p.mass = 5.15138902046611451e-05 * SOLAR_MASS; 63 | return p; 64 | } 65 | 66 | Body& Body::sun() 67 | { 68 | static Body p; 69 | p.mass = SOLAR_MASS; 70 | return p; 71 | } 72 | 73 | Body& Body::OffsetMomentum(double px, double py, double pz) 74 | { 75 | vx = -px / SOLAR_MASS; 76 | vy = -py / SOLAR_MASS; 77 | vz = -pz / SOLAR_MASS; 78 | return *this; 79 | } 80 | 81 | NBodySystem::NBodySystem() : 82 | bodies { { 83 | Body::sun(), 84 | Body::jupiter(), 85 | Body::saturn(), 86 | Body::uranus(), 87 | Body::neptune() 88 | } } 89 | { 90 | double px = 0.0; 91 | double py = 0.0; 92 | double pz = 0.0; 93 | for(unsigned i = 0; i < bodies.size(); ++i) 94 | { 95 | px += bodies[i].vx * bodies[i].mass; 96 | py += bodies[i].vy * bodies[i].mass; 97 | pz += bodies[i].vz * bodies[i].mass; 98 | } 99 | bodies[0].OffsetMomentum(px, py, pz); 100 | } 101 | 102 | void NBodySystem::advance(double dt) 103 | { 104 | const unsigned N = (bodies.size() - 1) * bodies.size() / 2; 105 | struct __attribute__((aligned(16))) R { 106 | double dx, dy, dz, filler; 107 | }; 108 | static R r[1000]; 109 | static __attribute__((aligned(16))) double mag[1000]; 110 | 111 | for(unsigned i = 0, k = 0; i < bodies.size() - 1; ++i) 112 | { 113 | Body& iBody = bodies[i]; 114 | for(unsigned j = i + 1; j < bodies.size(); ++j, ++k) 115 | { 116 | r[k].dx = iBody.x - bodies[j].x; 117 | r[k].dy = iBody.y - bodies[j].y; 118 | r[k].dz = iBody.z - bodies[j].z; 119 | } 120 | } 121 | 122 | for(unsigned i = 0; i < N; i += 2) 123 | { 124 | __m128d dx, dy, dz; 125 | dx = _mm_loadl_pd(dx, &r[i].dx); 126 | dy = _mm_loadl_pd(dy, &r[i].dy); 127 | dz = _mm_loadl_pd(dz, &r[i].dz); 128 | 129 | dx = _mm_loadh_pd(dx, &r[i+1].dx); 130 | dy = _mm_loadh_pd(dy, &r[i+1].dy); 131 | dz = _mm_loadh_pd(dz, &r[i+1].dz); 132 | 133 | __m128d dSquared = dx * dx + dy * dy + dz * dz; 134 | 135 | __m128d distance = _mm_cvtps_pd(_mm_rsqrt_ps(_mm_cvtpd_ps(dSquared))); 136 | for(unsigned j = 0; j < 2; ++j) 137 | { 138 | distance = distance * _mm_set1_pd(1.5) - 139 | ((_mm_set1_pd(0.5) * dSquared) * distance) * 140 | (distance * distance); 141 | } 142 | 143 | __m128d dmag = _mm_set1_pd(dt)/(dSquared) * distance; 144 | _mm_store_pd(&mag[i],dmag); 145 | } 146 | 147 | for(unsigned i=0,k=0; i < bodies.size()-1; ++i) 148 | { 149 | Body& iBody = bodies[i]; 150 | for(unsigned j = i + 1; j < bodies.size(); ++j, ++k) 151 | { 152 | iBody.vx -= r[k].dx * bodies[j].mass * mag[k]; 153 | iBody.vy -= r[k].dy * bodies[j].mass * mag[k]; 154 | iBody.vz -= r[k].dz * bodies[j].mass * mag[k]; 155 | 156 | bodies[j].vx += r[k].dx * iBody.mass * mag[k]; 157 | bodies[j].vy += r[k].dy * iBody.mass * mag[k]; 158 | bodies[j].vz += r[k].dz * iBody.mass * mag[k]; 159 | } 160 | } 161 | 162 | for (unsigned i = 0; i < bodies.size(); ++i) 163 | { 164 | bodies[i].x += dt * bodies[i].vx; 165 | bodies[i].y += dt * bodies[i].vy; 166 | bodies[i].z += dt * bodies[i].vz; 167 | } 168 | } 169 | 170 | double NBodySystem::energy() 171 | { 172 | double e = 0.0; 173 | 174 | for(unsigned i = 0; i < bodies.size(); ++i) 175 | { 176 | Body const & iBody = bodies[i]; 177 | double dx, dy, dz, distance; 178 | e += 0.5 * iBody.mass * 179 | (iBody.vx * iBody.vx + 180 | iBody.vy * iBody.vy + 181 | iBody.vz * iBody.vz); 182 | 183 | for(unsigned j = i + 1; j < bodies.size(); ++j) 184 | { 185 | Body const & jBody = bodies[j]; 186 | dx = iBody.x - jBody.x; 187 | dy = iBody.y - jBody.y; 188 | dz = iBody.z - jBody.z; 189 | 190 | distance = sqrt(dx*dx + dy*dy + dz*dz); 191 | e -= (iBody.mass * jBody.mass) / distance; 192 | } 193 | } 194 | 195 | return e; 196 | } 197 | 198 | } 199 | -------------------------------------------------------------------------------- /README_en.md: -------------------------------------------------------------------------------- 1 | # Source code of "Node.js: Let's Write a Dozen of C++ Add-ons" 2 | 3 | ![Cover](cover.jpg) 4 | 5 | [中文文档](README.md) 6 | 7 | This repo is the source code of book "Node.js: Let's Write a Dozen of C++ Add-ons" which is written by XadillaX. Enjoy 8 | it! 9 | 10 | > **Hint:** All code in this repo were verified under macOS terminal and Node.js 6.x. Theoretically, it may run on 11 | > Windows and UNIX. But I didn't verify for these two platforms. 12 | 13 | ## Download 14 | 15 | You may download the source code from [Brandview official website](http://www.broadview.com.cn/). [Git](https://git-scm.com/) is more recommended if you are familiar with it. 16 | 17 | If you're going to clone this repo, use the command line below: 18 | 19 | ```shell 20 | $ git clone https://github.com/XadillaX/nyaa-nodejs-demo.git --recurse-submodules 21 | ``` 22 | 23 | > Parameter `--recurse-submodules` allows you clone the repo with all submodules. 24 | > 25 | > Due to the feature of GitHub, The ZIP file which downloaded from this page of GitHub will not contain the necessary 26 | > submodules. If you want to get the source code from the method of "Downloading", please go to the official website of 27 | > Brandview. 28 | 29 | ## Quick Navigation 30 | 31 | 1. [first build](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/1.%20first%20build):「1.4.2. node-gyp」 32 | 2. [cpp entry](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/2.%20cpp%20entry):「2.2.2. Node.js Module Loading Principle」 33 | 3. [function template](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/3.%20function%20template):「3.6.1. Function Template」 34 | 4. [object template](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/4.%20object%20template):「3.6.2. Object Template」 35 | 5. [object template accessor](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/5.%20object%20template%20accessor):「3.6.3. Accessor and Interceptor of Object Template」 36 | 6. [mapped property interceptor](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/6.%20mapped%20property%20interceptor):「3.6.3. Accessor and Interceptor of Object Template」 37 | 7. [indexed property interceptor](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/7.%20indexed%20property%20interceptor):「3.6.3. Accessor and Interceptor of Object Template」 38 | 8. [internal field wrong](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/8.%20internal%20field%20wrong):「3.6.4. Internal Field of Object Template」 39 | 9. [internal field right](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/9.%20internal%20field%20right):「3.6.4. Internal Field of Object Template」 40 | 10. [function template inherit](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/10.%20function%20template%20inherit):「3.6.5. Inherit of Object Template」 41 | 11. [array prototype map](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/11.%20array%20prototype%20map):「3.7.6. Function」 42 | 12. [try catch](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/12.%20try%20catch):「3.8.1. Try-Catch」 43 | 13. [hello world again](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/13.%20hello%20world%20again):「4.2.1. Hello World Again」 44 | 14. [function parameters](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/14.%20function%20parameters):「4.2.2. Function Parameters」 45 | 15. [run callback](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/15.%20run%20callback):「4.2.3. Callback Function」 46 | 16. [object factory](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/16.%20object%20factory):「4.2.4. Return an Objects」 47 | 17. [function factory](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/17.%20function%20factory):「4.2.5. Return a Function」 48 | 18. [myobject](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/18.%20myobject):「4.3.1. JavaScript Class C++ Wrapper」 49 | 19. [at_exit_hook](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/19.%20at_exit_hook):「4.3.4. at_exit_hook」 50 | 20. [nan echo](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/20.%20nan%20echo):「5.2.3. Come Come Go!」 51 | 21. [nan array prototype map](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/21.%20nan%20array%20prototype%20map):「5.2.4. Basic Helpers and Macros」 52 | 22. [nan set method](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/22.%20nan%20set%20method):「5.3.3. Setting Method」 53 | 23. [nan reverse string](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/23.%20nan%20reverse%20string):「5.4.3. Play with Data Object」 54 | 24. [nan object demo](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/24.%20nan%20object%20demo):「5.4.3. Play with Data Object」 55 | 25. [nan array demo](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/25.%20nan%20array%20demo):「5.4.3. Play with Data Object」 56 | 26. [nan json](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/26.%20nan%20json):「5.4.3. Play with Data Object」 57 | 27. [nan buffer](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/27.%20nan%20buffer):「5.4.3. Play with Data Object」 58 | 28. [nan nbodies](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/28.%20nan%20nbodies):「5.5.3. Nan::AsyncWorker」 59 | 29. [nan dummy download](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/29.%20nan%20dummy%20download):「5.5.4. Nan::AsyncProgressWorker」 60 | 30. [libuv idle](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/30.%20libuv%20idle):「6.1.3. Have a Taste」 61 | 31. [libuv sleep sort](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/31.%20libuv%20sleep%20sort):「6.2.1. libuv Thread」 62 | 32. [libuv sleep sort advanced](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/32.%20libuv%20sleep%20sort%20advanced):「6.2.2. Synchronization Primitives」 63 | 33. [libuv watchdog](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/33.%20libuv%20watchdog):「6.3.2. Semi-finished Watchdog」 64 | 34. [efsw](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/34.%20efsw):「7.1.1. Functional Planning」 65 | 35. [efsw advanced](https://github.com/XadillaX/node-efsw/tree/85cc5b816c3e04b4df92f63592f5e9ce99808418):「7.4.2. JavaScript Code Improving」 66 | 36. [napi](https://github.com/XadillaX/nyaa-nodejs-demo/tree/master/36.%20napi):「9.1.1. Write a `Echo` Function」 67 | 68 | ## Purchase Link of Book 69 | 70 | + [JD](https://item.jd.com/12380404.html) 71 | + [Tmall](https://detail.tmall.com/item.htm?id=571628730908&cat_id=2) 72 | + [Dangdang](http://product.dangdang.com/25291814.html) 73 | + [Amazon](https://www.amazon.cn/dp/B07DL8GHQC/ie=UTF8&qid=1528969734) 74 | + [china-pub](http://product.china-pub.com/8039217) 75 | + [Douban](https://book.douban.com/subject/30247892/) 76 | 77 | ## QQ Communicate Group 78 | 79 | QQ 群 80 | 81 | ## Thanks 82 | 83 | Thank you for supporting my book! 84 | 85 | ![フランドール・スカーレット](flandre.jpg) 86 | 87 |
This picture from Pixiv
88 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------