├── .dntrc ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .npmignore ├── .pre-commit-config.yaml ├── CHANGELOG.md ├── CMakeLists.txt ├── LICENSE.md ├── Makefile ├── README.md ├── appveyor.yml ├── doc ├── .build.sh ├── asyncworker.md ├── buffers.md ├── callback.md ├── converters.md ├── errors.md ├── json.md ├── maybe_types.md ├── methods.md ├── new.md ├── node_misc.md ├── object_wrappers.md ├── persistent.md ├── scopes.md ├── script.md ├── string_bytes.md ├── v8_internals.md └── v8_misc.md ├── examples └── async_pi_estimate │ ├── README.md │ ├── addon.cc │ ├── addon.js │ ├── async.cc │ ├── async.h │ ├── binding.gyp │ ├── package.json │ ├── pi_est.cc │ ├── pi_est.h │ ├── sync.cc │ └── sync.h ├── include_dirs.js ├── nan.h ├── nan_callbacks.h ├── nan_callbacks_12_inl.h ├── nan_callbacks_pre_12_inl.h ├── nan_converters.h ├── nan_converters_43_inl.h ├── nan_converters_pre_43_inl.h ├── nan_define_own_property_helper.h ├── nan_implementation_12_inl.h ├── nan_implementation_pre_12_inl.h ├── nan_json.h ├── nan_maybe_43_inl.h ├── nan_maybe_pre_43_inl.h ├── nan_new.h ├── nan_object_wrap.h ├── nan_persistent_12_inl.h ├── nan_persistent_pre_12_inl.h ├── nan_private.h ├── nan_scriptorigin.h ├── nan_string_bytes.h ├── nan_typedarray_contents.h ├── nan_weak.h ├── package.json ├── test ├── .jshintrc ├── binding.gyp ├── cpp │ ├── accessors.cpp │ ├── accessors2.cpp │ ├── asyncprogressqueueworker.cpp │ ├── asyncprogressqueueworkerstream.cpp │ ├── asyncprogressworker.cpp │ ├── asyncprogressworkersignal.cpp │ ├── asyncprogressworkerstream.cpp │ ├── asyncresource.cpp │ ├── asyncworker.cpp │ ├── asyncworkererror.cpp │ ├── buffer.cpp │ ├── bufferworkerpersistent.cpp │ ├── callbackcontext.cpp │ ├── converters.cpp │ ├── error.cpp │ ├── gc.cpp │ ├── indexedinterceptors.cpp │ ├── isolatedata.cpp │ ├── json-parse.cpp │ ├── json-stringify.cpp │ ├── makecallback.cpp │ ├── maybe.cpp │ ├── methodswithdata.cpp │ ├── morenews.cpp │ ├── multifile1.cpp │ ├── multifile2.cpp │ ├── multifile2.h │ ├── namedinterceptors.cpp │ ├── nancallback.cpp │ ├── nannew.cpp │ ├── news.cpp │ ├── objectwraphandle.cpp │ ├── persistent.cpp │ ├── private.cpp │ ├── returnemptystring.cpp │ ├── returnnull.cpp │ ├── returnundefined.cpp │ ├── returnvalue.cpp │ ├── setcallhandler.cpp │ ├── settemplate.cpp │ ├── sleep.h │ ├── strings.cpp │ ├── symbols.cpp │ ├── threadlocal.cpp │ ├── trycatch.cpp │ ├── typedarrays.cpp │ ├── weak.cpp │ ├── weak2.cpp │ └── wrappedobjectfactory.cpp ├── js │ ├── accessors-test.js │ ├── accessors2-test.js │ ├── asyncprogressqueueworker-test.js │ ├── asyncprogressqueueworkerstream-test.js │ ├── asyncprogressworker-test.js │ ├── asyncprogressworkersignal-test.js │ ├── asyncprogressworkerstream-test.js │ ├── asyncresource-test.js │ ├── asyncworker-test.js │ ├── asyncworkererror-test.js │ ├── buffer-test.js │ ├── bufferworkerpersistent-test.js │ ├── callbackcontext-test.js │ ├── converters-test.js │ ├── error-test.js │ ├── gc-fn.js │ ├── gc-test.js │ ├── indexedinterceptors-test.js │ ├── isolatedata-test.js │ ├── json-parse-test.js │ ├── json-stringify-test.js │ ├── makecallback-test.js │ ├── maybe-test.js │ ├── methodswithdata-test.js │ ├── morenews-test.js │ ├── multifile-test.js │ ├── namedinterceptors-test.js │ ├── nancallback-test.js │ ├── nannew-test.js │ ├── news-test.js │ ├── objectwraphandle-test.js │ ├── persistent-test.js │ ├── private-test.js │ ├── returnemptystring-test.js │ ├── returnnull-test.js │ ├── returnundefined-test.js │ ├── returnvalue-test.js │ ├── setcallhandler-test.js │ ├── settemplate-test.js │ ├── strings-test.js │ ├── symbols-test.js │ ├── threadlocal-test.js │ ├── trycatch-test.js │ ├── typedarrays-test.js │ ├── weak-test.js │ ├── weak2-test.js │ └── wrappedobjectfactory-test.js └── tap-as-worker.js └── tools ├── 1to2.js ├── README.md └── package.json /.dntrc: -------------------------------------------------------------------------------- 1 | ## DNT config file 2 | ## see https://github.com/rvagg/dnt 3 | 4 | NODE_VERSIONS="\ 5 | master \ 6 | v0.11.13 \ 7 | v0.10.30 \ 8 | v0.10.29 \ 9 | v0.10.28 \ 10 | v0.10.26 \ 11 | v0.10.25 \ 12 | v0.10.24 \ 13 | v0.10.23 \ 14 | v0.10.22 \ 15 | v0.10.21 \ 16 | v0.10.20 \ 17 | v0.10.19 \ 18 | v0.8.28 \ 19 | v0.8.27 \ 20 | v0.8.26 \ 21 | v0.8.24 \ 22 | " 23 | OUTPUT_PREFIX="nan-" 24 | TEST_CMD=" \ 25 | cd /dnt/ && \ 26 | npm install && \ 27 | node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ 28 | node_modules/.bin/tap --gc test/js/*-test.js \ 29 | " 30 | 31 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs 2 | # https://github.com/actions/setup-node 3 | # https://docs.github.com/en/actions/using-github-hosted-runners/using-github-hosted-runners/about-github-hosted-runners#standard-github-hosted-runners-for-public-repositories 4 | 5 | name: ci 6 | on: 7 | push: 8 | # branches: [main] 9 | pull_request: 10 | # branches: [main] 11 | workflow_dispatch: 12 | permissions: 13 | contents: read 14 | jobs: 15 | pre-commit: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v4 19 | - uses: pre-commit/action@v3.0.1 20 | 21 | ci: 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | node-version: [24.x, 23.x, 22.x, 21.x, 20.x, 19.x, 18.x, 17.x, 16.x] 26 | os: [windows-latest] 27 | include: 28 | - node-version: lts/* 29 | os: macos-13 # macOS on Intel 30 | - node-version: lts/* 31 | os: macos-latest # macOS on arm64 32 | - node-version: lts/* 33 | os: ubuntu-latest # Linux on x64 34 | - node-version: lts/* 35 | os: ubuntu-24.04-arm # Linux on arm64 36 | - node-version: lts/* 37 | os: windows-2025 38 | runs-on: ${{ matrix.os }} 39 | steps: 40 | - uses: actions/checkout@v4 41 | - uses: actions/setup-node@v4 42 | with: 43 | node-version: ${{ matrix.node-version }} 44 | - run: npm install 45 | # TODO: On Windows Node.js v11 these will fail but `make test` will succeed 46 | - if: matrix.node-version != '11.x' 47 | run: | 48 | npm run-script rebuild-tests 49 | npm test 50 | - run: make test 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | node_modules/ -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test/ 2 | examples/ 3 | .dntrc 4 | .npmignore 5 | appveyor.yml 6 | Makefile 7 | cpplint.py 8 | nan-*.tgz 9 | doc/.build.sh 10 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/cpplint/cpplint 3 | rev: 2.0.0 4 | hooks: 5 | - id: cpplint 6 | args: 7 | - --filter=-whitespace/indent_namespace,-whitespace/parens 8 | - --linelength=88 9 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 [NAN contributors](<https://github.com/nodejs/nan#wg-members--collaborators>) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | TOPLEVEL ?= $(dir $(lastword $(MAKEFILE_LIST))) 2 | CPPLINT ?= $(TOPLEVEL)/cpplint.py 3 | PYTHON ?= python 4 | BUILDTYPE ?= Release 5 | MODULES = symbols strings 6 | SOURCES = $(MODULES:%=test/cpp/%.cpp) 7 | ADDONS = $(MODULES:%=test/build/$(BUILDTYPE)/%.node) 8 | 9 | LINT_SOURCES = \ 10 | examples/async_pi_estimate/addon.cc \ 11 | examples/async_pi_estimate/async.cc \ 12 | examples/async_pi_estimate/async.h \ 13 | examples/async_pi_estimate/pi_est.cc \ 14 | examples/async_pi_estimate/pi_est.h \ 15 | examples/async_pi_estimate/sync.cc \ 16 | examples/async_pi_estimate/sync.h \ 17 | nan.h \ 18 | nan_callbacks.h \ 19 | nan_callbacks_12_inl.h \ 20 | nan_callbacks_pre_12_inl.h \ 21 | nan_converters.h \ 22 | nan_converters_43_inl.h \ 23 | nan_converters_pre_43_inl.h \ 24 | nan_define_own_property_helper.h \ 25 | nan_implementation_12_inl.h \ 26 | nan_implementation_pre_12_inl.h \ 27 | nan_json.h \ 28 | nan_maybe_43_inl.h \ 29 | nan_maybe_pre_43_inl.h \ 30 | nan_new.h \ 31 | nan_object_wrap.h \ 32 | nan_persistent_12_inl.h \ 33 | nan_persistent_pre_12_inl.h \ 34 | nan_private.h \ 35 | nan_scriptorigin.h \ 36 | nan_string_bytes.h \ 37 | nan_weak.h \ 38 | test/cpp/accessors.cpp \ 39 | test/cpp/accessors2.cpp \ 40 | test/cpp/asyncresource.cpp \ 41 | test/cpp/asyncworker.cpp \ 42 | test/cpp/asyncprogressworker.cpp \ 43 | test/cpp/asyncprogressworkerstream.cpp \ 44 | test/cpp/asyncprogressworkersignal.cpp \ 45 | test/cpp/asyncprogressqueueworker.cpp \ 46 | test/cpp/asyncprogressqueueworkerstream.cpp \ 47 | test/cpp/asyncworkererror.cpp \ 48 | test/cpp/buffer.cpp \ 49 | test/cpp/bufferworkerpersistent.cpp \ 50 | test/cpp/error.cpp \ 51 | test/cpp/gc.cpp \ 52 | test/cpp/indexedinterceptors.cpp \ 53 | test/cpp/callbackcontext.cpp \ 54 | test/cpp/converters.cpp \ 55 | test/cpp/isolatedata.cpp \ 56 | test/cpp/json-parse.cpp \ 57 | test/cpp/json-stringify.cpp \ 58 | test/cpp/makecallback.cpp \ 59 | test/cpp/maybe.cpp \ 60 | test/cpp/morenews.cpp \ 61 | test/cpp/multifile1.cpp \ 62 | test/cpp/multifile2.cpp \ 63 | test/cpp/multifile2.h \ 64 | test/cpp/namedinterceptors.cpp \ 65 | test/cpp/nancallback.cpp \ 66 | test/cpp/nannew.cpp \ 67 | test/cpp/news.cpp \ 68 | test/cpp/objectwraphandle.cpp \ 69 | test/cpp/persistent.cpp \ 70 | test/cpp/private.cpp \ 71 | test/cpp/returnemptystring.cpp \ 72 | test/cpp/returnnull.cpp \ 73 | test/cpp/returnundefined.cpp \ 74 | test/cpp/returnvalue.cpp \ 75 | test/cpp/setcallhandler.cpp \ 76 | test/cpp/settemplate.cpp \ 77 | test/cpp/sleep.h \ 78 | test/cpp/strings.cpp \ 79 | test/cpp/symbols.cpp \ 80 | test/cpp/threadlocal.cpp \ 81 | test/cpp/trycatch.cpp \ 82 | test/cpp/typedarrays.cpp \ 83 | test/cpp/weak.cpp \ 84 | test/cpp/weak2.cpp \ 85 | test/cpp/wrappedobjectfactory.cpp \ 86 | node_modules/node-gyp/gyp/data/win/large-pdb-shim.cc 87 | 88 | FILTER = -build/include_subdir,-whitespace/parens 89 | 90 | .PHONY: lint 91 | 92 | lint: 93 | cd $(TOPLEVEL) && $(PYTHON) $(CPPLINT) --filter=$(FILTER) $(LINT_SOURCES) 94 | 95 | test: $(ADDONS) 96 | npm test 97 | 98 | forcetest: 99 | cd test && ../node_modules/.bin/node-gyp rebuild && cd .. 100 | npm test 101 | 102 | docs: README.md doc/.build.sh doc/asyncworker.md doc/buffers.md doc/callback.md \ 103 | doc/converters.md doc/errors.md doc/maybe_types.md doc/methods.md doc/new.md \ 104 | doc/node_misc.md doc/persistent.md doc/scopes.md doc/script.md doc/string_bytes.md \ 105 | doc/v8_internals.md doc/json.md doc/v8_misc.md 106 | doc/.build.sh 107 | 108 | 109 | $(ADDONS): nan.h nan_new.h nan_implementation_pre_12_inl.h nan_implementation_12_inl.h \ 110 | nan_callbacks.h nan_callbacks_12_inl.h nan_callbacks_pre_12_inl.h \ 111 | nan_converters.h nan_converters_43_inl.h nan_converters_pre_43_inl.h \ 112 | nan_define_own_property_helper.h \ 113 | nan_json.h nan_maybe_43_inl.h nan_maybe_pre_43_inl.h \ 114 | nan_persistent_12_inl.h nan_persistent_pre_12_inl.h nan_private.h \ 115 | nan_weak.h nan_scriptorigin.h nan_string_bytes.h \ 116 | test/binding.gyp $(SOURCES) 117 | cd test/ && ../node_modules/.bin/node-gyp rebuild 118 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | # http://www.appveyor.com/docs/appveyor-yml 2 | # https://www.appveyor.com/docs/windows-images-software 3 | # https://nodejs.org/en/about/previous-releases 4 | # https://devguide.python.org/versions 5 | 6 | # Test supported Node.js versions before unsupported versions. 7 | # Run on the most current Visual Studio possible for each nodejs_version. 8 | # Run on the earliest supported Python version when possible (currently py39). 9 | # For all supported Node.js versions test also on the latest Python (currently py313). 10 | 11 | image: 12 | - Visual Studio 2022 13 | 14 | environment: 15 | NODE_GYP_FORCE_PYTHON: C:\Python39-x64\python.exe 16 | matrix: # Test against these versions of Io.js and Node.js. 17 | - nodejs_version: "24" 18 | - nodejs_version: "23" 19 | - nodejs_version: "22" 20 | - nodejs_version: "22" 21 | NODE_GYP_FORCE_PYTHON: C:\Python312-x64\python.exe 22 | - nodejs_version: "21" 23 | - nodejs_version: "20" 24 | - nodejs_version: "19" 25 | - nodejs_version: "18" 26 | - nodejs_version: "17" 27 | - nodejs_version: "16" 28 | - nodejs_version: "14" 29 | APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 30 | - nodejs_version: "12" 31 | APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 32 | - nodejs_version: "10" 33 | APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 34 | - nodejs_version: "8" 35 | APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 36 | 37 | matrix: 38 | fast_finish: true 39 | 40 | # Install scripts. (runs after repo cloning) 41 | install: 42 | # Output useful info for debugging. 43 | - node --version 44 | - npm --version 45 | - py --list 46 | - py -VV # py is 64-bit AMD64 Python 3 on Visual Studio images 47 | - python -VV # python is 32-bit Intel Python 3 on Visual Studio images 48 | # Get the latest stable version of Node 0.STABLE.latest 49 | - ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) x64 50 | - node --version 51 | - set PATH=%APPDATA%\npm;%PATH% 52 | # Typical npm stuff. 53 | - npm install 54 | - npm run rebuild-tests 55 | 56 | # Post-install test scripts. 57 | test_script: 58 | # Output useful info for debugging. 59 | - node --version 60 | - npm --version 61 | - py --list 62 | - py -VV # py is 64-bit AMD64 Python 3 on Visual Studio images 63 | - python -VV # python is 32-bit Intel Python 3 on Visual Studio images 64 | # run tests 65 | - node node_modules\tap\bin\tap.js --gc test/js/*-test.js 66 | 67 | # Don't actually build. 68 | build: off 69 | 70 | # Set build version format here instead of in the admin panel. 71 | version: "{build}" 72 | -------------------------------------------------------------------------------- /doc/.build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | files=" \ 4 | methods.md \ 5 | scopes.md \ 6 | persistent.md \ 7 | new.md \ 8 | converters.md \ 9 | maybe_types.md \ 10 | script.md \ 11 | json.md \ 12 | errors.md \ 13 | buffers.md \ 14 | callback.md \ 15 | asyncworker.md \ 16 | string_bytes.md \ 17 | object_wrappers.md \ 18 | v8_internals.md \ 19 | v8_misc.md \ 20 | node_misc.md \ 21 | " 22 | 23 | __dirname=$(dirname "${BASH_SOURCE[0]}") 24 | head=$(perl -e 'while (<>) { if (!$en){print;} if ($_=~/<!-- START/){$en=1} };' $__dirname/../README.md) 25 | tail=$(perl -e 'while (<>) { if ($_=~/<!-- END/){$st=1} if ($st){print;} };' $__dirname/../README.md) 26 | apidocs=$(for f in $files; do 27 | perl -pe ' 28 | last if /^<a name/; 29 | $_ =~ s/^## /### /; 30 | $_ =~ s/<a href="#/<a href="doc\/'$f'#/; 31 | ' $__dirname/$f; 32 | done) 33 | 34 | cat > $__dirname/../README.md << EOF 35 | $head 36 | 37 | $apidocs 38 | 39 | $tail 40 | EOF 41 | -------------------------------------------------------------------------------- /doc/buffers.md: -------------------------------------------------------------------------------- 1 | ## Buffers 2 | 3 | NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. 4 | 5 | - <a href="#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a> 6 | - <a href="#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a> 7 | - <a href="#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a> 8 | 9 | <a name="api_nan_new_buffer"></a> 10 | ### Nan::NewBuffer() 11 | 12 | Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`. 13 | 14 | Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management. 15 | When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`. 16 | You _must not_ free the memory space manually once you have created a `Buffer` in this way. 17 | 18 | Signature: 19 | 20 | ```c++ 21 | Nan::MaybeLocal<v8::Object> Nan::NewBuffer(uint32_t size) 22 | Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size) 23 | Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char *data, 24 | size_t length, 25 | Nan::FreeCallback callback, 26 | void *hint) 27 | ``` 28 | 29 | 30 | <a name="api_nan_copy_buffer"></a> 31 | ### Nan::CopyBuffer() 32 | 33 | Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`. 34 | 35 | Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy. 36 | 37 | Signature: 38 | 39 | ```c++ 40 | Nan::MaybeLocal<v8::Object> Nan::CopyBuffer(const char *data, uint32_t size) 41 | ``` 42 | 43 | 44 | <a name="api_nan_free_callback"></a> 45 | ### Nan::FreeCallback() 46 | 47 | A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer). 48 | The supplied callback will be invoked when the `Buffer` undergoes garbage collection. 49 | 50 | Signature: 51 | 52 | ```c++ 53 | typedef void (*FreeCallback)(char *data, void *hint); 54 | ``` 55 | -------------------------------------------------------------------------------- /doc/callback.md: -------------------------------------------------------------------------------- 1 | ## Nan::Callback 2 | 3 | `Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. 4 | 5 | - <a href="#api_nan_callback"><b><code>Nan::Callback</code></b></a> 6 | 7 | <a name="api_nan_callback"></a> 8 | ### Nan::Callback 9 | 10 | ```c++ 11 | class Callback { 12 | public: 13 | Callback(); 14 | 15 | explicit Callback(const v8::Local<v8::Function> &fn); 16 | 17 | ~Callback(); 18 | 19 | bool operator==(const Callback &other) const; 20 | 21 | bool operator!=(const Callback &other) const; 22 | 23 | v8::Local<v8::Function> operator*() const; 24 | 25 | MaybeLocal<v8::Value> operator()(AsyncResource* async_resource, 26 | v8::Local<v8::Object> target, 27 | int argc = 0, 28 | v8::Local<v8::Value> argv[] = 0) const; 29 | 30 | MaybeLocal<v8::Value> operator()(AsyncResource* async_resource, 31 | int argc = 0, 32 | v8::Local<v8::Value> argv[] = 0) const; 33 | 34 | void SetFunction(const v8::Local<v8::Function> &fn); 35 | 36 | v8::Local<v8::Function> GetFunction() const; 37 | 38 | bool IsEmpty() const; 39 | 40 | void Reset(const v8::Local<v8::Function> &fn); 41 | 42 | void Reset(); 43 | 44 | MaybeLocal<v8::Value> Call(v8::Local<v8::Object> target, 45 | int argc, 46 | v8::Local<v8::Value> argv[], 47 | AsyncResource* async_resource) const; 48 | MaybeLocal<v8::Value> Call(int argc, 49 | v8::Local<v8::Value> argv[], 50 | AsyncResource* async_resource) const; 51 | 52 | // Deprecated versions. Use the versions that accept an async_resource instead 53 | // as they run the callback in the correct async context as specified by the 54 | // resource. If you want to call a synchronous JS function (i.e. on a 55 | // non-empty JS stack), you can use Nan::Call instead. 56 | v8::Local<v8::Value> operator()(v8::Local<v8::Object> target, 57 | int argc = 0, 58 | v8::Local<v8::Value> argv[] = 0) const; 59 | 60 | v8::Local<v8::Value> operator()(int argc = 0, 61 | v8::Local<v8::Value> argv[] = 0) const; 62 | v8::Local<v8::Value> Call(v8::Local<v8::Object> target, 63 | int argc, 64 | v8::Local<v8::Value> argv[]) const; 65 | 66 | v8::Local<v8::Value> Call(int argc, v8::Local<v8::Value> argv[]) const; 67 | }; 68 | ``` 69 | 70 | Example usage: 71 | 72 | ```c++ 73 | v8::Local<v8::Function> function; 74 | Nan::Callback callback(function); 75 | callback.Call(0, 0); 76 | ``` 77 | -------------------------------------------------------------------------------- /doc/converters.md: -------------------------------------------------------------------------------- 1 | ## Converters 2 | 3 | NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. 4 | 5 | - <a href="#api_nan_to"><b><code>Nan::To()</code></b></a> 6 | 7 | <a name="api_nan_to"></a> 8 | ### Nan::To() 9 | 10 | Converts a `v8::Local<v8::Value>` to a different subtype of `v8::Value` or to a native data type. Returns a `Nan::MaybeLocal<>` or a `Nan::Maybe<>` accordingly. 11 | 12 | See [maybe_types.md](./maybe_types.md) for more information on `Nan::Maybe` types. 13 | 14 | Signatures: 15 | 16 | ```c++ 17 | // V8 types 18 | Nan::MaybeLocal<v8::Boolean> Nan::To<v8::Boolean>(v8::Local<v8::Value> val); 19 | Nan::MaybeLocal<v8::Int32> Nan::To<v8::Int32>(v8::Local<v8::Value> val); 20 | Nan::MaybeLocal<v8::Integer> Nan::To<v8::Integer>(v8::Local<v8::Value> val); 21 | Nan::MaybeLocal<v8::Object> Nan::To<v8::Object>(v8::Local<v8::Value> val); 22 | Nan::MaybeLocal<v8::Number> Nan::To<v8::Number>(v8::Local<v8::Value> val); 23 | Nan::MaybeLocal<v8::String> Nan::To<v8::String>(v8::Local<v8::Value> val); 24 | Nan::MaybeLocal<v8::Uint32> Nan::To<v8::Uint32>(v8::Local<v8::Value> val); 25 | 26 | // Native types 27 | Nan::Maybe<bool> Nan::To<bool>(v8::Local<v8::Value> val); 28 | Nan::Maybe<double> Nan::To<double>(v8::Local<v8::Value> val); 29 | Nan::Maybe<int32_t> Nan::To<int32_t>(v8::Local<v8::Value> val); 30 | Nan::Maybe<int64_t> Nan::To<int64_t>(v8::Local<v8::Value> val); 31 | Nan::Maybe<uint32_t> Nan::To<uint32_t>(v8::Local<v8::Value> val); 32 | ``` 33 | 34 | ### Example 35 | 36 | ```c++ 37 | v8::Local<v8::Value> val; 38 | Nan::MaybeLocal<v8::String> str = Nan::To<v8::String>(val); 39 | Nan::Maybe<double> d = Nan::To<double>(val); 40 | ``` 41 | 42 | -------------------------------------------------------------------------------- /doc/json.md: -------------------------------------------------------------------------------- 1 | ## JSON 2 | 3 | The _JSON_ object provides the C++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. 4 | 5 | - <a href="#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a> 6 | - <a href="#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a> 7 | 8 | Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. 9 | 10 | <a name="api_nan_json_parse"></a> 11 | 12 | ### Nan::JSON.Parse 13 | 14 | A simple wrapper around [`v8::JSON::Parse`](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html#a936310d2540fb630ed37d3ee3ffe4504). 15 | 16 | Definition: 17 | 18 | ```c++ 19 | Nan::MaybeLocal<v8::Value> Nan::JSON::Parse(v8::Local<v8::String> json_string); 20 | ``` 21 | 22 | Use `JSON.Parse(json_string)` to parse a string into a `v8::Value`. 23 | 24 | Example: 25 | 26 | ```c++ 27 | v8::Local<v8::String> json_string = Nan::New("{ \"JSON\": \"object\" }").ToLocalChecked(); 28 | 29 | Nan::JSON NanJSON; 30 | Nan::MaybeLocal<v8::Value> result = NanJSON.Parse(json_string); 31 | if (!result.IsEmpty()) { 32 | v8::Local<v8::Value> val = result.ToLocalChecked(); 33 | } 34 | ``` 35 | 36 | <a name="api_nan_json_stringify"></a> 37 | 38 | ### Nan::JSON.Stringify 39 | 40 | A simple wrapper around [`v8::JSON::Stringify`](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html#a44b255c3531489ce43f6110209138860). 41 | 42 | Definition: 43 | 44 | ```c++ 45 | Nan::MaybeLocal<v8::String> Nan::JSON::Stringify(v8::Local<v8::Object> json_object, v8::Local<v8::String> gap = v8::Local<v8::String>()); 46 | ``` 47 | 48 | Use `JSON.Stringify(value)` to stringify a `v8::Object`. 49 | 50 | Example: 51 | 52 | ```c++ 53 | // using `v8::Local<v8::Value> val` from the `JSON::Parse` example 54 | v8::Local<v8::Object> obj = Nan::To<v8::Object>(val).ToLocalChecked(); 55 | 56 | Nan::JSON NanJSON; 57 | Nan::MaybeLocal<v8::String> result = NanJSON.Stringify(obj); 58 | if (!result.IsEmpty()) { 59 | v8::Local<v8::String> stringified = result.ToLocalChecked(); 60 | } 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /doc/scopes.md: -------------------------------------------------------------------------------- 1 | ## Scopes 2 | 3 | A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. 4 | 5 | A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. 6 | 7 | The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. 8 | 9 | - <a href="#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a> 10 | - <a href="#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a> 11 | 12 | Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). 13 | 14 | <a name="api_nan_handle_scope"></a> 15 | ### Nan::HandleScope 16 | 17 | A simple wrapper around [`v8::HandleScope`](https://v8docs.nodesource.com/node-8.16/d3/d95/classv8_1_1_handle_scope.html). 18 | 19 | Definition: 20 | 21 | ```c++ 22 | class Nan::HandleScope { 23 | public: 24 | Nan::HandleScope(); 25 | static int NumberOfHandles(); 26 | }; 27 | ``` 28 | 29 | Allocate a new `Nan::HandleScope` whenever you are creating new V8 JavaScript objects. Note that an implicit `HandleScope` is created for you on JavaScript-accessible methods so you do not need to insert one yourself. 30 | 31 | Example: 32 | 33 | ```c++ 34 | // new object is created, it needs a new scope: 35 | void Pointless() { 36 | Nan::HandleScope scope; 37 | v8::Local<v8::Object> obj = Nan::New<v8::Object>(); 38 | } 39 | 40 | // JavaScript-accessible method already has a HandleScope 41 | NAN_METHOD(Pointless2) { 42 | v8::Local<v8::Object> obj = Nan::New<v8::Object>(); 43 | } 44 | ``` 45 | 46 | <a name="api_nan_escapable_handle_scope"></a> 47 | ### Nan::EscapableHandleScope 48 | 49 | Similar to [`Nan::HandleScope`](#api_nan_handle_scope) but should be used in cases where a function needs to return a V8 JavaScript type that has been created within it. 50 | 51 | Definition: 52 | 53 | ```c++ 54 | class Nan::EscapableHandleScope { 55 | public: 56 | Nan::EscapableHandleScope(); 57 | static int NumberOfHandles(); 58 | template<typename T> v8::Local<T> Escape(v8::Local<T> value); 59 | } 60 | ``` 61 | 62 | Use `Escape(value)` to return the object. 63 | 64 | Example: 65 | 66 | ```c++ 67 | v8::Local<v8::Object> EmptyObj() { 68 | Nan::EscapableHandleScope scope; 69 | v8::Local<v8::Object> obj = Nan::New<v8::Object>(); 70 | return scope.Escape(obj); 71 | } 72 | ``` 73 | 74 | -------------------------------------------------------------------------------- /doc/script.md: -------------------------------------------------------------------------------- 1 | ## Script 2 | 3 | NAN provides `v8::Script` helpers as the API has changed over the supported versions of V8. 4 | 5 | - <a href="#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a> 6 | - <a href="#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a> 7 | - <a href="#api_nan_script_origin"><b><code>Nan::ScriptOrigin</code></b></a> 8 | 9 | 10 | <a name="api_nan_compile_script"></a> 11 | ### Nan::CompileScript() 12 | 13 | A wrapper around [`v8::ScriptCompiler::Compile()`](https://v8docs.nodesource.com/node-8.16/da/da5/classv8_1_1_script_compiler.html#a93f5072a0db55d881b969e9fc98e564b). 14 | 15 | Note that `Nan::BoundScript` is an alias for `v8::Script`. 16 | 17 | Signature: 18 | 19 | ```c++ 20 | Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript( 21 | v8::Local<v8::String> s, 22 | const v8::ScriptOrigin& origin); 23 | Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(v8::Local<v8::String> s); 24 | ``` 25 | 26 | 27 | <a name="api_nan_run_script"></a> 28 | ### Nan::RunScript() 29 | 30 | Calls `script->Run()` or `script->BindToCurrentContext()->Run(Nan::GetCurrentContext())`. 31 | 32 | Note that `Nan::BoundScript` is an alias for `v8::Script` and `Nan::UnboundScript` is an alias for `v8::UnboundScript` where available and `v8::Script` on older versions of V8. 33 | 34 | Signature: 35 | 36 | ```c++ 37 | Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::UnboundScript> script) 38 | Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::BoundScript> script) 39 | ``` 40 | 41 | <a name="api_nan_script_origin"></a> 42 | ### Nan::ScriptOrigin 43 | 44 | A class transparently extending [`v8::ScriptOrigin`](https://v8docs.nodesource.com/node-16.0/db/d84/classv8_1_1_script_origin.html#pub-methods) 45 | to provide backwards compatibility. Only the listed methods are guaranteed to 46 | be available on all versions of Node. 47 | 48 | Declaration: 49 | 50 | ```c++ 51 | class Nan::ScriptOrigin : public v8::ScriptOrigin { 52 | public: 53 | ScriptOrigin(v8::Local<v8::Value> name, v8::Local<v8::Integer> line = v8::Local<v8::Integer>(), v8::Local<v8::Integer> column = v8::Local<v8::Integer>()) 54 | v8::Local<v8::Value> ResourceName() const; 55 | v8::Local<v8::Integer> ResourceLineOffset() const; 56 | v8::Local<v8::Integer> ResourceColumnOffset() const; 57 | } 58 | ``` 59 | -------------------------------------------------------------------------------- /doc/string_bytes.md: -------------------------------------------------------------------------------- 1 | ## Strings & Bytes 2 | 3 | Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. 4 | 5 | - <a href="#api_nan_encoding"><b><code>Nan::Encoding</code></b></a> 6 | - <a href="#api_nan_encode"><b><code>Nan::Encode()</code></b></a> 7 | - <a href="#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a> 8 | - <a href="#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a> 9 | 10 | 11 | <a name="api_nan_encoding"></a> 12 | ### Nan::Encoding 13 | 14 | An enum representing the supported encoding types. A copy of `node::encoding` that is consistent across versions of Node. 15 | 16 | Definition: 17 | 18 | ```c++ 19 | enum Nan::Encoding { ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER } 20 | ``` 21 | 22 | 23 | <a name="api_nan_encode"></a> 24 | ### Nan::Encode() 25 | 26 | A wrapper around `node::Encode()` that provides a consistent implementation across supported versions of Node. 27 | 28 | Signature: 29 | 30 | ```c++ 31 | v8::Local<v8::Value> Nan::Encode(const void *buf, 32 | size_t len, 33 | enum Nan::Encoding encoding = BINARY); 34 | ``` 35 | 36 | 37 | <a name="api_nan_decode_bytes"></a> 38 | ### Nan::DecodeBytes() 39 | 40 | A wrapper around `node::DecodeBytes()` that provides a consistent implementation across supported versions of Node. 41 | 42 | Signature: 43 | 44 | ```c++ 45 | ssize_t Nan::DecodeBytes(v8::Local<v8::Value> val, 46 | enum Nan::Encoding encoding = BINARY); 47 | ``` 48 | 49 | 50 | <a name="api_nan_decode_write"></a> 51 | ### Nan::DecodeWrite() 52 | 53 | A wrapper around `node::DecodeWrite()` that provides a consistent implementation across supported versions of Node. 54 | 55 | Signature: 56 | 57 | ```c++ 58 | ssize_t Nan::DecodeWrite(char *buf, 59 | size_t len, 60 | v8::Local<v8::Value> val, 61 | enum Nan::Encoding encoding = BINARY); 62 | ``` 63 | -------------------------------------------------------------------------------- /doc/v8_misc.md: -------------------------------------------------------------------------------- 1 | ## Miscellaneous V8 Helpers 2 | 3 | - <a href="#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a> 4 | - <a href="#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a> 5 | - <a href="#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a> 6 | - <a href="#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a> 7 | - <a href="#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a> 8 | 9 | 10 | <a name="api_nan_utf8_string"></a> 11 | ### Nan::Utf8String 12 | 13 | Converts an object to a UTF-8-encoded character array. If conversion to a string fails (e.g. due to an exception in the toString() method of the object) then the length() method returns 0 and the * operator returns NULL. The underlying memory used for this object is managed by the object. 14 | 15 | An implementation of [`v8::String::Utf8Value`](https://v8docs.nodesource.com/node-8.16/d4/d1b/classv8_1_1_string_1_1_utf8_value.html) that is consistent across all supported versions of V8. 16 | 17 | Definition: 18 | 19 | ```c++ 20 | class Nan::Utf8String { 21 | public: 22 | Nan::Utf8String(v8::Local<v8::Value> from); 23 | 24 | int length() const; 25 | 26 | char* operator*(); 27 | const char* operator*() const; 28 | }; 29 | ``` 30 | 31 | <a name="api_nan_get_current_context"></a> 32 | ### Nan::GetCurrentContext() 33 | 34 | A call to [`v8::Isolate::GetCurrent()->GetCurrentContext()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a81c7a1ed7001ae2a65e89107f75fd053) that works across all supported versions of V8. 35 | 36 | Signature: 37 | 38 | ```c++ 39 | v8::Local<v8::Context> Nan::GetCurrentContext() 40 | ``` 41 | 42 | <a name="api_nan_set_isolate_data"></a> 43 | ### Nan::SetIsolateData() 44 | 45 | A helper to provide a consistent API to [`v8::Isolate#SetData()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a7acadfe7965997e9c386a05f098fbe36). 46 | 47 | Signature: 48 | 49 | ```c++ 50 | void Nan::SetIsolateData(v8::Isolate *isolate, T *data) 51 | ``` 52 | 53 | 54 | <a name="api_nan_get_isolate_data"></a> 55 | ### Nan::GetIsolateData() 56 | 57 | A helper to provide a consistent API to [`v8::Isolate#GetData()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#aabd223436bc1100a787dadaa024c6257). 58 | 59 | Signature: 60 | 61 | ```c++ 62 | T *Nan::GetIsolateData(v8::Isolate *isolate) 63 | ``` 64 | 65 | <a name="api_nan_typedarray_contents"></a> 66 | ### Nan::TypedArrayContents<T> 67 | 68 | A helper class for accessing the contents of an ArrayBufferView (aka a typedarray) from C++. If the input array is not a valid typedarray, then the data pointer of TypedArrayContents will default to `NULL` and the length will be 0. If the data pointer is not compatible with the alignment requirements of type, an assertion error will fail. 69 | 70 | Note that you must store a reference to the `array` object while you are accessing its contents. 71 | 72 | Definition: 73 | 74 | ```c++ 75 | template<typename T> 76 | class Nan::TypedArrayContents { 77 | public: 78 | TypedArrayContents(v8::Local<Value> array); 79 | 80 | size_t length() const; 81 | 82 | T* const operator*(); 83 | const T* const operator*() const; 84 | }; 85 | ``` 86 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/README.md: -------------------------------------------------------------------------------- 1 | In this directory run `node-gyp rebuild` and then `node ./addon.js` -------------------------------------------------------------------------------- /examples/async_pi_estimate/addon.cc: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | #include "sync.h" // NOLINT(build/include_subdir) 11 | #include "async.h" // NOLINT(build/include_subdir) 12 | 13 | using v8::FunctionTemplate; 14 | using v8::Object; 15 | using v8::String; 16 | using Nan::GetFunction; 17 | using Nan::New; 18 | using Nan::Set; 19 | 20 | // Expose synchronous and asynchronous access to our 21 | // Estimate() function 22 | NAN_MODULE_INIT(InitAll) { 23 | Set(target, New<String>("calculateSync").ToLocalChecked(), 24 | GetFunction(New<FunctionTemplate>(CalculateSync)).ToLocalChecked()); 25 | 26 | Set(target, New<String>("calculateAsync").ToLocalChecked(), 27 | GetFunction(New<FunctionTemplate>(CalculateAsync)).ToLocalChecked()); 28 | } 29 | 30 | NODE_MODULE(addon, InitAll) 31 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/addon.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | var addon = require('./build/Release/addon'); 10 | var calculations = process.argv[2] || 100000000; 11 | 12 | function printResult(type, pi, ms) { 13 | console.log(type, 'method:'); 14 | console.log('\tπ ≈ ' + pi + 15 | ' (' + Math.abs(pi - Math.PI) + ' away from actual)'); 16 | console.log('\tTook ' + ms + 'ms'); 17 | console.log(); 18 | } 19 | 20 | function runSync() { 21 | var start = Date.now(); 22 | // Estimate() will execute in the current thread, 23 | // the next line won't return until it is finished 24 | var result = addon.calculateSync(calculations); 25 | printResult('Sync', result, Date.now() - start); 26 | } 27 | 28 | function runAsync() { 29 | // how many batches should we split the work in to? 30 | var batches = process.argv[3] || 16; 31 | var ended = 0; 32 | var total = 0; 33 | var start = Date.now(); 34 | 35 | function done (err, result) { 36 | total += result; 37 | 38 | // have all the batches finished executing? 39 | if (++ended === batches) { 40 | printResult('Async', total / batches, Date.now() - start); 41 | } 42 | } 43 | 44 | // for each batch of work, request an async Estimate() for 45 | // a portion of the total number of calculations 46 | for (var i = 0; i < batches; i++) { 47 | addon.calculateAsync(calculations / batches, done); 48 | } 49 | } 50 | 51 | runSync(); 52 | runAsync(); 53 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/async.cc: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | #include "pi_est.h" // NOLINT(build/include_subdir) 11 | #include "async.h" // NOLINT(build/include_subdir) 12 | 13 | using v8::Function; 14 | using v8::Local; 15 | using v8::Number; 16 | using v8::Value; 17 | using Nan::AsyncQueueWorker; 18 | using Nan::AsyncWorker; 19 | using Nan::Callback; 20 | using Nan::HandleScope; 21 | using Nan::New; 22 | using Nan::Null; 23 | using Nan::To; 24 | 25 | class PiWorker : public AsyncWorker { 26 | public: 27 | PiWorker(Callback *callback, int points) 28 | : AsyncWorker(callback), points(points), estimate(0) {} 29 | ~PiWorker() {} 30 | 31 | // Executed inside the worker-thread. 32 | // It is not safe to access V8, or V8 data structures 33 | // here, so everything we need for input and output 34 | // should go on `this`. 35 | void Execute () { 36 | estimate = Estimate(points); 37 | } 38 | 39 | // Executed when the async work is complete 40 | // this function will be run inside the main event loop 41 | // so it is safe to use V8 again 42 | void HandleOKCallback () { 43 | HandleScope scope; 44 | 45 | Local<Value> argv[] = { 46 | Null() 47 | , New<Number>(estimate) 48 | }; 49 | 50 | callback->Call(2, argv, async_resource); 51 | } 52 | 53 | private: 54 | int points; 55 | double estimate; 56 | }; 57 | 58 | // Asynchronous access to the `Estimate()` function 59 | NAN_METHOD(CalculateAsync) { 60 | int points = To<int>(info[0]).FromJust(); 61 | Callback *callback = new Callback(To<Function>(info[1]).ToLocalChecked()); 62 | 63 | AsyncQueueWorker(new PiWorker(callback, points)); 64 | } 65 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/async.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef EXAMPLES_ASYNC_PI_ESTIMATE_ASYNC_H_ 10 | #define EXAMPLES_ASYNC_PI_ESTIMATE_ASYNC_H_ 11 | 12 | #include <nan.h> 13 | 14 | NAN_METHOD(CalculateAsync); 15 | 16 | #endif // EXAMPLES_ASYNC_PI_ESTIMATE_ASYNC_H_ 17 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [ 3 | { 4 | "target_name": "addon", 5 | "sources": [ 6 | "addon.cc", 7 | "pi_est.cc", 8 | "sync.cc", 9 | "async.cc" 10 | ], 11 | "include_dirs": ["<!(node -e \"require('nan')\")"] 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "async_work", 3 | "version": "0.0.0", 4 | "description": "Node.js Addons Example #9", 5 | "main": "addon.js", 6 | "private": true, 7 | "gypfile": true, 8 | "dependencies": { 9 | "nan": "*" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/pi_est.cc: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <cstdlib> 10 | #include "pi_est.h" // NOLINT(build/include_subdir) 11 | 12 | /* 13 | Estimate the value of π by using a Monte Carlo method. 14 | Take `points` samples of random x and y values on a 15 | [0,1][0,1] plane. Calculating the length of the diagonal 16 | tells us whether the point lies inside, or outside a 17 | quarter circle running from 0,1 to 1,0. The ratio of the 18 | number of points inside to outside gives us an 19 | approximation of π/4. 20 | 21 | See https://en.wikipedia.org/wiki/File:Pi_30K.gif 22 | for a visualization of how this works. 23 | */ 24 | 25 | inline int randall(unsigned int *p_seed) { 26 | // windows has thread safe rand() 27 | #ifdef _WIN32 28 | return rand(); // NOLINT(runtime/threadsafe_fn) 29 | #else 30 | return rand_r(p_seed); 31 | #endif 32 | } 33 | 34 | double Estimate (int points) { 35 | int i = points; 36 | int inside = 0; 37 | unsigned int randseed = 1; 38 | 39 | #ifdef _WIN32 40 | srand(randseed); 41 | #endif 42 | 43 | // unique seed for each run, for threaded use 44 | unsigned int seed = randall(&randseed); 45 | 46 | #ifdef _WIN32 47 | srand(seed); 48 | #endif 49 | 50 | while (i-- > 0) { 51 | double x = randall(&seed) / static_cast<double>(RAND_MAX); 52 | double y = randall(&seed) / static_cast<double>(RAND_MAX); 53 | 54 | // x & y and now values between 0 and 1 55 | // now do a pythagorean diagonal calculation 56 | // `1` represents our 1/4 circle 57 | if ((x * x) + (y * y) <= 1) 58 | inside++; 59 | } 60 | 61 | // calculate ratio and multiply by 4 for π 62 | return (inside / static_cast<double>(points)) * 4; 63 | } 64 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/pi_est.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef EXAMPLES_ASYNC_PI_ESTIMATE_PI_EST_H_ 10 | #define EXAMPLES_ASYNC_PI_ESTIMATE_PI_EST_H_ 11 | 12 | double Estimate(int points); 13 | 14 | #endif // EXAMPLES_ASYNC_PI_ESTIMATE_PI_EST_H_ 15 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/sync.cc: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | #include "pi_est.h" // NOLINT(build/include_subdir) 11 | #include "sync.h" // NOLINT(build/include_subdir) 12 | 13 | // Simple synchronous access to the `Estimate()` function 14 | NAN_METHOD(CalculateSync) { 15 | // expect a number as the first argument 16 | int points = Nan::To<int>(info[0]).FromJust(); 17 | double est = Estimate(points); 18 | 19 | info.GetReturnValue().Set(est); 20 | } 21 | -------------------------------------------------------------------------------- /examples/async_pi_estimate/sync.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef EXAMPLES_ASYNC_PI_ESTIMATE_SYNC_H_ 10 | #define EXAMPLES_ASYNC_PI_ESTIMATE_SYNC_H_ 11 | 12 | #include <nan.h> 13 | 14 | NAN_METHOD(CalculateSync); 15 | 16 | #endif // EXAMPLES_ASYNC_PI_ESTIMATE_SYNC_H_ 17 | -------------------------------------------------------------------------------- /include_dirs.js: -------------------------------------------------------------------------------- 1 | console.log(require('path').relative('.', __dirname)); 2 | -------------------------------------------------------------------------------- /nan_converters.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef NAN_CONVERTERS_H_ 10 | #define NAN_CONVERTERS_H_ 11 | 12 | namespace imp { 13 | template<typename T> struct ToFactoryBase { 14 | typedef MaybeLocal<T> return_t; 15 | }; 16 | template<typename T> struct ValueFactoryBase { typedef Maybe<T> return_t; }; 17 | 18 | template<typename T> struct ToFactory; 19 | 20 | template<> 21 | struct ToFactory<v8::Function> : ToFactoryBase<v8::Function> { 22 | static inline return_t convert(v8::Local<v8::Value> val) { 23 | if (val.IsEmpty() || !val->IsFunction()) return MaybeLocal<v8::Function>(); 24 | return MaybeLocal<v8::Function>(val.As<v8::Function>()); 25 | } 26 | }; 27 | 28 | #define X(TYPE) \ 29 | template<> \ 30 | struct ToFactory<v8::TYPE> : ToFactoryBase<v8::TYPE> { \ 31 | static inline return_t convert(v8::Local<v8::Value> val); \ 32 | }; 33 | 34 | X(Boolean) 35 | X(Number) 36 | X(String) 37 | X(Object) 38 | X(Integer) 39 | X(Uint32) 40 | X(Int32) 41 | 42 | #undef X 43 | 44 | #define X(TYPE) \ 45 | template<> \ 46 | struct ToFactory<TYPE> : ValueFactoryBase<TYPE> { \ 47 | static inline return_t convert(v8::Local<v8::Value> val); \ 48 | }; 49 | 50 | X(bool) 51 | X(double) 52 | X(int64_t) 53 | X(uint32_t) 54 | X(int32_t) 55 | 56 | #undef X 57 | } // end of namespace imp 58 | 59 | template<typename T> 60 | inline 61 | typename imp::ToFactory<T>::return_t To(v8::Local<v8::Value> val) { 62 | return imp::ToFactory<T>::convert(val); 63 | } 64 | 65 | #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ 66 | (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) 67 | # include "nan_converters_43_inl.h" 68 | #else 69 | # include "nan_converters_pre_43_inl.h" 70 | #endif 71 | 72 | #endif // NAN_CONVERTERS_H_ 73 | -------------------------------------------------------------------------------- /nan_converters_43_inl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef NAN_CONVERTERS_43_INL_H_ 10 | #define NAN_CONVERTERS_43_INL_H_ 11 | 12 | #define X(TYPE) \ 13 | imp::ToFactory<v8::TYPE>::return_t \ 14 | imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \ 15 | v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ 16 | v8::EscapableHandleScope scope(isolate); \ 17 | return scope.Escape( \ 18 | val->To ## TYPE(isolate->GetCurrentContext()) \ 19 | .FromMaybe(v8::Local<v8::TYPE>())); \ 20 | } 21 | 22 | X(Number) 23 | X(String) 24 | X(Object) 25 | X(Integer) 26 | X(Uint32) 27 | X(Int32) 28 | // V8 <= 7.0 29 | #if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0) 30 | X(Boolean) 31 | #else 32 | imp::ToFactory<v8::Boolean>::return_t \ 33 | imp::ToFactory<v8::Boolean>::convert(v8::Local<v8::Value> val) { \ 34 | v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ 35 | v8::EscapableHandleScope scope(isolate); \ 36 | return scope.Escape(val->ToBoolean(isolate)); \ 37 | } 38 | #endif 39 | 40 | #undef X 41 | 42 | #define X(TYPE, NAME) \ 43 | imp::ToFactory<TYPE>::return_t \ 44 | imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \ 45 | v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ 46 | v8::HandleScope scope(isolate); \ 47 | return val->NAME ## Value(isolate->GetCurrentContext()); \ 48 | } 49 | 50 | X(double, Number) 51 | X(int64_t, Integer) 52 | X(uint32_t, Uint32) 53 | X(int32_t, Int32) 54 | // V8 <= 7.0 55 | #if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0) 56 | X(bool, Boolean) 57 | #else 58 | imp::ToFactory<bool>::return_t \ 59 | imp::ToFactory<bool>::convert(v8::Local<v8::Value> val) { \ 60 | v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ 61 | v8::HandleScope scope(isolate); \ 62 | return Just<bool>(val->BooleanValue(isolate)); \ 63 | } 64 | #endif 65 | 66 | #undef X 67 | 68 | #endif // NAN_CONVERTERS_43_INL_H_ 69 | -------------------------------------------------------------------------------- /nan_converters_pre_43_inl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef NAN_CONVERTERS_PRE_43_INL_H_ 10 | #define NAN_CONVERTERS_PRE_43_INL_H_ 11 | 12 | #define X(TYPE) \ 13 | imp::ToFactory<v8::TYPE>::return_t \ 14 | imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \ 15 | return val->To ## TYPE(); \ 16 | } 17 | 18 | X(Boolean) 19 | X(Number) 20 | X(String) 21 | X(Object) 22 | X(Integer) 23 | X(Uint32) 24 | X(Int32) 25 | 26 | #undef X 27 | 28 | #define X(TYPE, NAME) \ 29 | imp::ToFactory<TYPE>::return_t \ 30 | imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \ 31 | return Just(val->NAME ## Value()); \ 32 | } 33 | 34 | X(bool, Boolean) 35 | X(double, Number) 36 | X(int64_t, Integer) 37 | X(uint32_t, Uint32) 38 | X(int32_t, Int32) 39 | 40 | #undef X 41 | 42 | #endif // NAN_CONVERTERS_PRE_43_INL_H_ 43 | -------------------------------------------------------------------------------- /nan_define_own_property_helper.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef NAN_DEFINE_OWN_PROPERTY_HELPER_H_ 10 | #define NAN_DEFINE_OWN_PROPERTY_HELPER_H_ 11 | 12 | namespace imp { 13 | 14 | inline Maybe<bool> DefineOwnPropertyHelper( 15 | v8::PropertyAttribute current 16 | , v8::Handle<v8::Object> obj 17 | , v8::Handle<v8::String> key 18 | , v8::Handle<v8::Value> value 19 | , v8::PropertyAttribute attribs = v8::None) { 20 | return !(current & v8::DontDelete) || // configurable OR 21 | (!(current & v8::ReadOnly) && // writable AND 22 | !((attribs ^ current) & ~v8::ReadOnly)) // same excluding RO 23 | ? Just<bool>(obj->ForceSet(key, value, attribs)) 24 | : Nothing<bool>(); 25 | } 26 | 27 | } // end of namespace imp 28 | 29 | #endif // NAN_DEFINE_OWN_PROPERTY_HELPER_H_ 30 | -------------------------------------------------------------------------------- /nan_persistent_12_inl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef NAN_PERSISTENT_12_INL_H_ 10 | #define NAN_PERSISTENT_12_INL_H_ 11 | 12 | template<typename T, typename M> class Persistent : 13 | public v8::Persistent<T, M> { 14 | public: 15 | inline Persistent() : v8::Persistent<T, M>() {} 16 | 17 | template<typename S> inline Persistent(v8::Local<S> that) : 18 | v8::Persistent<T, M>(v8::Isolate::GetCurrent(), that) {} 19 | 20 | template<typename S, typename M2> 21 | inline 22 | Persistent(const v8::Persistent<S, M2> &that) : // NOLINT(runtime/explicit) 23 | v8::Persistent<T, M2>(v8::Isolate::GetCurrent(), that) {} 24 | 25 | inline void Reset() { v8::PersistentBase<T>::Reset(); } 26 | 27 | template <typename S> 28 | inline void Reset(const v8::Local<S> &other) { 29 | v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); 30 | } 31 | 32 | template <typename S> 33 | inline void Reset(const v8::PersistentBase<S> &other) { 34 | v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); 35 | } 36 | 37 | template<typename P> 38 | inline void SetWeak( 39 | P *parameter 40 | , typename WeakCallbackInfo<P>::Callback callback 41 | , WeakCallbackType type); 42 | 43 | private: 44 | inline T *operator*() const { return *PersistentBase<T>::persistent; } 45 | 46 | template<typename S, typename M2> 47 | inline void Copy(const Persistent<S, M2> &that) { 48 | TYPE_CHECK(T, S); 49 | 50 | this->Reset(); 51 | 52 | if (!that.IsEmpty()) { 53 | this->Reset(that); 54 | M::Copy(that, this); 55 | } 56 | } 57 | }; 58 | 59 | #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ 60 | (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) 61 | template<typename T> 62 | class Global : public v8::Global<T> { 63 | public: 64 | inline Global() : v8::Global<T>() {} 65 | 66 | template<typename S> inline Global(v8::Local<S> that) : 67 | v8::Global<T>(v8::Isolate::GetCurrent(), that) {} 68 | 69 | template<typename S> 70 | inline 71 | Global(const v8::PersistentBase<S> &that) : // NOLINT(runtime/explicit) 72 | v8::Global<S>(v8::Isolate::GetCurrent(), that) {} 73 | 74 | inline void Reset() { v8::PersistentBase<T>::Reset(); } 75 | 76 | template <typename S> 77 | inline void Reset(const v8::Local<S> &other) { 78 | v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); 79 | } 80 | 81 | template <typename S> 82 | inline void Reset(const v8::PersistentBase<S> &other) { 83 | v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); 84 | } 85 | 86 | template<typename P> 87 | inline void SetWeak( 88 | P *parameter 89 | , typename WeakCallbackInfo<P>::Callback callback 90 | , WeakCallbackType type) { 91 | reinterpret_cast<Persistent<T>*>(this)->SetWeak( 92 | parameter, callback, type); 93 | } 94 | }; 95 | #else 96 | template<typename T> 97 | class Global : public v8::UniquePersistent<T> { 98 | public: 99 | inline Global() : v8::UniquePersistent<T>() {} 100 | 101 | template<typename S> inline Global(v8::Local<S> that) : 102 | v8::UniquePersistent<T>(v8::Isolate::GetCurrent(), that) {} 103 | 104 | template<typename S> 105 | inline 106 | Global(const v8::PersistentBase<S> &that) : // NOLINT(runtime/explicit) 107 | v8::UniquePersistent<S>(v8::Isolate::GetCurrent(), that) {} 108 | 109 | inline void Reset() { v8::PersistentBase<T>::Reset(); } 110 | 111 | template <typename S> 112 | inline void Reset(const v8::Local<S> &other) { 113 | v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); 114 | } 115 | 116 | template <typename S> 117 | inline void Reset(const v8::PersistentBase<S> &other) { 118 | v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); 119 | } 120 | 121 | template<typename P> 122 | inline void SetWeak( 123 | P *parameter 124 | , typename WeakCallbackInfo<P>::Callback callback 125 | , WeakCallbackType type) { 126 | reinterpret_cast<Persistent<T>*>(this)->SetWeak( 127 | parameter, callback, type); 128 | } 129 | }; 130 | #endif 131 | 132 | #endif // NAN_PERSISTENT_12_INL_H_ 133 | -------------------------------------------------------------------------------- /nan_private.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef NAN_PRIVATE_H_ 10 | #define NAN_PRIVATE_H_ 11 | 12 | inline Maybe<bool> 13 | HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { 14 | HandleScope scope; 15 | #if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION 16 | v8::Isolate *isolate = v8::Isolate::GetCurrent(); 17 | v8::Local<v8::Context> context = isolate->GetCurrentContext(); 18 | v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); 19 | return object->HasPrivate(context, private_key); 20 | #else 21 | return Just(!object->GetHiddenValue(key).IsEmpty()); 22 | #endif 23 | } 24 | 25 | inline MaybeLocal<v8::Value> 26 | GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { 27 | #if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION 28 | v8::Isolate *isolate = v8::Isolate::GetCurrent(); 29 | v8::EscapableHandleScope scope(isolate); 30 | v8::Local<v8::Context> context = isolate->GetCurrentContext(); 31 | v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); 32 | v8::MaybeLocal<v8::Value> v = object->GetPrivate(context, private_key); 33 | return scope.Escape(v.ToLocalChecked()); 34 | #else 35 | EscapableHandleScope scope; 36 | v8::Local<v8::Value> v = object->GetHiddenValue(key); 37 | if (v.IsEmpty()) { 38 | v = Undefined(); 39 | } 40 | return scope.Escape(v); 41 | #endif 42 | } 43 | 44 | inline Maybe<bool> SetPrivate( 45 | v8::Local<v8::Object> object, 46 | v8::Local<v8::String> key, 47 | v8::Local<v8::Value> value) { 48 | #if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION 49 | HandleScope scope; 50 | v8::Isolate *isolate = v8::Isolate::GetCurrent(); 51 | v8::Local<v8::Context> context = isolate->GetCurrentContext(); 52 | v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); 53 | return object->SetPrivate(context, private_key, value); 54 | #else 55 | return Just(object->SetHiddenValue(key, value)); 56 | #endif 57 | } 58 | 59 | inline Maybe<bool> DeletePrivate( 60 | v8::Local<v8::Object> object, 61 | v8::Local<v8::String> key) { 62 | #if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION 63 | HandleScope scope; 64 | v8::Isolate *isolate = v8::Isolate::GetCurrent(); 65 | v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); 66 | return object->DeletePrivate(isolate->GetCurrentContext(), private_key); 67 | #else 68 | return Just(object->DeleteHiddenValue(key)); 69 | #endif 70 | } 71 | 72 | #endif // NAN_PRIVATE_H_ 73 | 74 | -------------------------------------------------------------------------------- /nan_scriptorigin.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2021 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef NAN_SCRIPTORIGIN_H_ 10 | #define NAN_SCRIPTORIGIN_H_ 11 | 12 | class ScriptOrigin : public v8::ScriptOrigin { 13 | public: 14 | #if defined(V8_MAJOR_VERSION) && \ 15 | (V8_MAJOR_VERSION > 12 || \ 16 | (V8_MAJOR_VERSION == 12 && \ 17 | (defined(V8_MINOR_VERSION) && \ 18 | (V8_MINOR_VERSION > 6 || \ 19 | (V8_MINOR_VERSION == 6 && defined(V8_BUILD_NUMBER) && \ 20 | V8_BUILD_NUMBER >= 175))))) 21 | explicit ScriptOrigin(v8::Local<v8::Value> name) : 22 | v8::ScriptOrigin(name) {} 23 | 24 | ScriptOrigin(v8::Local<v8::Value> name 25 | , v8::Local<v8::Integer> line) : 26 | v8::ScriptOrigin(name 27 | , To<int32_t>(line).FromMaybe(0)) {} 28 | 29 | ScriptOrigin(v8::Local<v8::Value> name 30 | , v8::Local<v8::Integer> line 31 | , v8::Local<v8::Integer> column) : 32 | v8::ScriptOrigin(name 33 | , To<int32_t>(line).FromMaybe(0) 34 | , To<int32_t>(column).FromMaybe(0)) {} 35 | #elif defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 9 || \ 36 | (V8_MAJOR_VERSION == 9 && (defined(V8_MINOR_VERSION) && (V8_MINOR_VERSION > 0\ 37 | || (V8_MINOR_VERSION == 0 && defined(V8_BUILD_NUMBER) \ 38 | && V8_BUILD_NUMBER >= 1))))) 39 | explicit ScriptOrigin(v8::Local<v8::Value> name) : 40 | v8::ScriptOrigin(v8::Isolate::GetCurrent(), name) {} 41 | 42 | ScriptOrigin(v8::Local<v8::Value> name 43 | , v8::Local<v8::Integer> line) : 44 | v8::ScriptOrigin(v8::Isolate::GetCurrent() 45 | , name 46 | , To<int32_t>(line).FromMaybe(0)) {} 47 | 48 | ScriptOrigin(v8::Local<v8::Value> name 49 | , v8::Local<v8::Integer> line 50 | , v8::Local<v8::Integer> column) : 51 | v8::ScriptOrigin(v8::Isolate::GetCurrent() 52 | , name 53 | , To<int32_t>(line).FromMaybe(0) 54 | , To<int32_t>(column).FromMaybe(0)) {} 55 | #elif defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 8 || \ 56 | (V8_MAJOR_VERSION == 8 && (defined(V8_MINOR_VERSION) && (V8_MINOR_VERSION > 9\ 57 | || (V8_MINOR_VERSION == 9 && defined(V8_BUILD_NUMBER) \ 58 | && V8_BUILD_NUMBER >= 45))))) 59 | explicit ScriptOrigin(v8::Local<v8::Value> name) : v8::ScriptOrigin(name) {} 60 | 61 | ScriptOrigin(v8::Local<v8::Value> name 62 | , v8::Local<v8::Integer> line) : 63 | v8::ScriptOrigin(name, To<int32_t>(line).FromMaybe(0)) {} 64 | 65 | ScriptOrigin(v8::Local<v8::Value> name 66 | , v8::Local<v8::Integer> line 67 | , v8::Local<v8::Integer> column) : 68 | v8::ScriptOrigin(name 69 | , To<int32_t>(line).FromMaybe(0) 70 | , To<int32_t>(column).FromMaybe(0)) {} 71 | #else 72 | explicit ScriptOrigin(v8::Local<v8::Value> name) : v8::ScriptOrigin(name) {} 73 | 74 | ScriptOrigin(v8::Local<v8::Value> name 75 | , v8::Local<v8::Integer> line) : v8::ScriptOrigin(name, line) {} 76 | 77 | ScriptOrigin(v8::Local<v8::Value> name 78 | , v8::Local<v8::Integer> line 79 | , v8::Local<v8::Integer> column) : 80 | v8::ScriptOrigin(name, line, column) {} 81 | #endif 82 | 83 | #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 8 || \ 84 | (V8_MAJOR_VERSION == 8 && (defined(V8_MINOR_VERSION) && (V8_MINOR_VERSION > 9\ 85 | || (V8_MINOR_VERSION == 9 && defined(V8_BUILD_NUMBER) \ 86 | && V8_BUILD_NUMBER >= 45))))) 87 | v8::Local<v8::Integer> ResourceLineOffset() const { 88 | return New(LineOffset()); 89 | } 90 | 91 | v8::Local<v8::Integer> ResourceColumnOffset() const { 92 | return New(ColumnOffset()); 93 | } 94 | #endif 95 | }; 96 | 97 | #endif // NAN_SCRIPTORIGIN_H_ 98 | -------------------------------------------------------------------------------- /nan_typedarray_contents.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef NAN_TYPEDARRAY_CONTENTS_H_ 10 | #define NAN_TYPEDARRAY_CONTENTS_H_ 11 | 12 | template<typename T> 13 | class TypedArrayContents { 14 | public: 15 | inline explicit TypedArrayContents(v8::Local<v8::Value> from) : 16 | length_(0), data_(NULL) { 17 | HandleScope scope; 18 | 19 | size_t length = 0; 20 | void* data = NULL; 21 | 22 | #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ 23 | (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) 24 | 25 | if (from->IsArrayBufferView()) { 26 | v8::Local<v8::ArrayBufferView> array = 27 | v8::Local<v8::ArrayBufferView>::Cast(from); 28 | 29 | const size_t byte_length = array->ByteLength(); 30 | const ptrdiff_t byte_offset = array->ByteOffset(); 31 | v8::Local<v8::ArrayBuffer> buffer = array->Buffer(); 32 | 33 | length = byte_length / sizeof(T); 34 | // Actually it's 7.9 here but this would lead to ABI issues with Node.js 13 35 | // using 7.8 till 13.2.0. 36 | #if (V8_MAJOR_VERSION >= 8) 37 | data = static_cast<char*>(buffer->GetBackingStore()->Data()) + byte_offset; 38 | #else 39 | data = static_cast<char*>(buffer->GetContents().Data()) + byte_offset; 40 | #endif 41 | } 42 | 43 | #else 44 | 45 | if (from->IsObject() && !from->IsNull()) { 46 | v8::Local<v8::Object> array = v8::Local<v8::Object>::Cast(from); 47 | 48 | MaybeLocal<v8::Value> buffer = Get(array, 49 | New<v8::String>("buffer").ToLocalChecked()); 50 | MaybeLocal<v8::Value> byte_length = Get(array, 51 | New<v8::String>("byteLength").ToLocalChecked()); 52 | MaybeLocal<v8::Value> byte_offset = Get(array, 53 | New<v8::String>("byteOffset").ToLocalChecked()); 54 | 55 | if (!buffer.IsEmpty() && 56 | !byte_length.IsEmpty() && byte_length.ToLocalChecked()->IsUint32() && 57 | !byte_offset.IsEmpty() && byte_offset.ToLocalChecked()->IsUint32()) { 58 | data = array->GetIndexedPropertiesExternalArrayData(); 59 | if(data) { 60 | length = byte_length.ToLocalChecked()->Uint32Value() / sizeof(T); 61 | } 62 | } 63 | } 64 | 65 | #endif 66 | 67 | #if defined(_MSC_VER) && _MSC_VER >= 1900 || __cplusplus >= 201103L 68 | assert(reinterpret_cast<uintptr_t>(data) % alignof (T) == 0); 69 | #elif defined(_MSC_VER) && _MSC_VER >= 1600 || defined(__GNUC__) 70 | assert(reinterpret_cast<uintptr_t>(data) % __alignof(T) == 0); 71 | #else 72 | assert(reinterpret_cast<uintptr_t>(data) % sizeof (T) == 0); 73 | #endif 74 | 75 | length_ = length; 76 | data_ = static_cast<T*>(data); 77 | } 78 | 79 | inline size_t length() const { return length_; } 80 | inline T* operator*() { return data_; } 81 | inline const T* operator*() const { return data_; } 82 | 83 | private: 84 | NAN_DISALLOW_ASSIGN_COPY_MOVE(TypedArrayContents) 85 | 86 | // Disable heap allocation 87 | void *operator new(size_t size); 88 | void operator delete(void *, size_t) { 89 | abort(); 90 | } 91 | 92 | size_t length_; 93 | T* data_; 94 | }; 95 | 96 | #endif // NAN_TYPEDARRAY_CONTENTS_H_ 97 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nan", 3 | "version": "2.23.0", 4 | "description": "Native Abstractions for Node.js: C++ header for Node 0.8 -> 24 compatibility", 5 | "main": "include_dirs.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git://github.com/nodejs/nan.git" 9 | }, 10 | "scripts": { 11 | "test": "tap --gc --stderr test/js/*-test.js", 12 | "test:worker": "node --experimental-worker test/tap-as-worker.js --gc --stderr test/js/*-test.js", 13 | "rebuild-tests-2015": "node-gyp rebuild --msvs_version=2015 --directory test", 14 | "rebuild-tests": "node-gyp rebuild --directory test", 15 | "docs": "doc/.build.sh" 16 | }, 17 | "contributors": [ 18 | "Rod Vagg <r@va.gg> (https://github.com/rvagg)", 19 | "Benjamin Byholm <bbyholm@abo.fi> (https://github.com/kkoopa/)", 20 | "Trevor Norris <trev.norris@gmail.com> (https://github.com/trevnorris)", 21 | "Nathan Rajlich <nathan@tootallnate.net> (https://github.com/TooTallNate)", 22 | "Brett Lawson <brett19@gmail.com> (https://github.com/brett19)", 23 | "Ben Noordhuis <info@bnoordhuis.nl> (https://github.com/bnoordhuis)", 24 | "David Siegel <david@artcom.de> (https://github.com/agnat)", 25 | "Michael Ira Krufky <mkrufky@gmail.com> (https://github.com/mkrufky)" 26 | ], 27 | "devDependencies": { 28 | "bindings": "~1.2.1", 29 | "commander": "^2.8.1", 30 | "glob": "^5.0.14", 31 | "request": "=2.81.0", 32 | "node-gyp": "~v10.3.1", 33 | "readable-stream": "^2.1.4", 34 | "tap": "~0.7.1", 35 | "xtend": "~4.0.0" 36 | }, 37 | "license": "MIT" 38 | } 39 | -------------------------------------------------------------------------------- /test/.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "predef": [ ] 3 | , "bitwise": false 4 | , "camelcase": false 5 | , "curly": false 6 | , "eqeqeq": false 7 | , "forin": false 8 | , "immed": false 9 | , "latedef": false 10 | , "noarg": true 11 | , "noempty": true 12 | , "nonew": true 13 | , "plusplus": false 14 | , "quotmark": true 15 | , "regexp": false 16 | , "undef": true 17 | , "unused": true 18 | , "strict": false 19 | , "trailing": true 20 | , "maxlen": 120 21 | , "asi": true 22 | , "boss": true 23 | , "debug": true 24 | , "eqnull": true 25 | , "esnext": true 26 | , "evil": true 27 | , "expr": true 28 | , "funcscope": false 29 | , "globalstrict": false 30 | , "iterator": false 31 | , "lastsemic": true 32 | , "laxbreak": true 33 | , "laxcomma": true 34 | , "loopfunc": true 35 | , "multistr": false 36 | , "onecase": false 37 | , "proto": false 38 | , "regexdash": false 39 | , "scripturl": true 40 | , "smarttabs": false 41 | , "shadow": false 42 | , "sub": true 43 | , "supernew": false 44 | , "validthis": true 45 | , "browser": true 46 | , "couch": false 47 | , "devel": false 48 | , "dojo": false 49 | , "mootools": false 50 | , "node": true 51 | , "nonstandard": true 52 | , "prototypejs": false 53 | , "rhino": false 54 | , "worker": true 55 | , "wsh": false 56 | , "nomen": false 57 | , "onevar": true 58 | , "passfail": false 59 | } -------------------------------------------------------------------------------- /test/cpp/asyncprogressqueueworker.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | class ProgressQueueWorker : public AsyncProgressQueueWorker<char> { 14 | public: 15 | ProgressQueueWorker( 16 | Callback *callback 17 | , Callback *progress 18 | , int iters) 19 | : AsyncProgressQueueWorker(callback), progress(progress) 20 | , iters(iters) {} 21 | 22 | ~ProgressQueueWorker() { 23 | delete progress; 24 | } 25 | 26 | void Execute (const AsyncProgressQueueWorker::ExecutionProgress& progress) { 27 | for (int i = 0; i < iters; ++i) { 28 | progress.Send(reinterpret_cast<const char*>(&i), sizeof(int)); 29 | } 30 | } 31 | 32 | void HandleProgressCallback(const char *data, size_t count) { 33 | HandleScope scope; 34 | 35 | v8::Local<v8::Value> argv[] = { 36 | New<v8::Integer>(*reinterpret_cast<int*>(const_cast<char*>(data))) 37 | }; 38 | progress->Call(1, argv, async_resource); 39 | } 40 | 41 | private: 42 | Callback *progress; 43 | int iters; 44 | }; 45 | 46 | NAN_METHOD(DoProgress) { 47 | Callback *progress = new Callback(To<v8::Function>(info[1]).ToLocalChecked()); 48 | Callback *callback = new Callback(To<v8::Function>(info[2]).ToLocalChecked()); 49 | AsyncQueueWorker(new ProgressQueueWorker( 50 | callback 51 | , progress 52 | , To<uint32_t>(info[0]).FromJust())); 53 | } 54 | 55 | NAN_MODULE_INIT(Init) { 56 | Set(target 57 | , New<v8::String>("doProgress").ToLocalChecked() 58 | , GetFunction(New<v8::FunctionTemplate>(DoProgress)).ToLocalChecked()); 59 | } 60 | 61 | NODE_MODULE(asyncprogressqueueworker, Init) 62 | -------------------------------------------------------------------------------- /test/cpp/asyncprogressqueueworkerstream.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | // Custom data type: This serves as an example of how external 14 | // libraries could be hooked in, populate their objects and send them to JS. 15 | struct data_t { 16 | int index; 17 | int data; 18 | }; 19 | 20 | template<typename T> 21 | class ProgressQueueWorker : public AsyncProgressQueueWorker<T> { 22 | public: 23 | ProgressQueueWorker( 24 | Callback *callback 25 | , Callback *progress 26 | , int iters) 27 | : AsyncProgressQueueWorker<T>(callback), progress(progress) 28 | , iters(iters) {} 29 | 30 | ~ProgressQueueWorker() { 31 | delete progress; 32 | } 33 | 34 | void Execute ( 35 | const typename AsyncProgressQueueWorker<T>::ExecutionProgress& progress) { 36 | data_t data; 37 | for (int i = 0; i < iters; ++i) { 38 | data.index = i; 39 | data.data = i * 2; 40 | progress.Send(&data, 1); 41 | } 42 | } 43 | 44 | void HandleProgressCallback(const T *data, size_t count) { 45 | HandleScope scope; 46 | v8::Local<v8::Object> obj = Nan::New<v8::Object>(); 47 | Nan::Set( 48 | obj, 49 | Nan::New("index").ToLocalChecked(), 50 | New<v8::Integer>(data->index)); 51 | Nan::Set( 52 | obj, 53 | Nan::New("data").ToLocalChecked(), 54 | New<v8::Integer>(data->data)); 55 | 56 | v8::Local<v8::Value> argv[] = { obj }; 57 | progress->Call(1, argv, this->async_resource); 58 | } 59 | 60 | private: 61 | Callback *progress; 62 | int iters; 63 | }; 64 | 65 | NAN_METHOD(DoProgress) { 66 | Callback *progress = new Callback(To<v8::Function>(info[1]).ToLocalChecked()); 67 | Callback *callback = new Callback(To<v8::Function>(info[2]).ToLocalChecked()); 68 | AsyncQueueWorker(new ProgressQueueWorker<data_t>( 69 | callback 70 | , progress 71 | , To<uint32_t>(info[0]).FromJust())); 72 | } 73 | 74 | NAN_MODULE_INIT(Init) { 75 | Set(target 76 | , New<v8::String>("doProgress").ToLocalChecked() 77 | , GetFunction(New<v8::FunctionTemplate>(DoProgress)).ToLocalChecked()); 78 | } 79 | 80 | NODE_MODULE(asyncprogressqueueworkerstream, Init) 81 | -------------------------------------------------------------------------------- /test/cpp/asyncprogressworker.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | #include "sleep.h" // NOLINT(build/include_subdir) 12 | 13 | using namespace Nan; // NOLINT(build/namespaces) 14 | 15 | class ProgressWorker : public AsyncProgressWorker { 16 | public: 17 | ProgressWorker( 18 | Callback *callback 19 | , Callback *progress 20 | , int milliseconds 21 | , int iters) 22 | : AsyncProgressWorker(callback), progress(progress) 23 | , milliseconds(milliseconds), iters(iters) {} 24 | 25 | ~ProgressWorker() { 26 | delete progress; 27 | } 28 | 29 | void Execute (const AsyncProgressWorker::ExecutionProgress& progress) { 30 | for (int i = 0; i < iters; ++i) { 31 | progress.Send(reinterpret_cast<const char*>(&i), sizeof(int)); 32 | Sleep(milliseconds); 33 | } 34 | } 35 | 36 | void HandleProgressCallback(const char *data, size_t count) { 37 | HandleScope scope; 38 | 39 | v8::Local<v8::Value> argv[] = { 40 | New<v8::Integer>(*reinterpret_cast<int*>(const_cast<char*>(data))) 41 | }; 42 | progress->Call(1, argv, async_resource); 43 | } 44 | 45 | private: 46 | Callback *progress; 47 | int milliseconds; 48 | int iters; 49 | }; 50 | 51 | NAN_METHOD(DoProgress) { 52 | Callback *progress = new Callback(To<v8::Function>(info[2]).ToLocalChecked()); 53 | Callback *callback = new Callback(To<v8::Function>(info[3]).ToLocalChecked()); 54 | AsyncQueueWorker(new ProgressWorker( 55 | callback 56 | , progress 57 | , To<uint32_t>(info[0]).FromJust() 58 | , To<uint32_t>(info[1]).FromJust())); 59 | } 60 | 61 | NAN_MODULE_INIT(Init) { 62 | Set(target 63 | , New<v8::String>("a").ToLocalChecked() 64 | , GetFunction(New<v8::FunctionTemplate>(DoProgress)).ToLocalChecked()); 65 | } 66 | 67 | NODE_MODULE(asyncprogressworker, Init) 68 | -------------------------------------------------------------------------------- /test/cpp/asyncprogressworkersignal.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | #include "sleep.h" // NOLINT(build/include_subdir) 12 | 13 | using namespace Nan; // NOLINT(build/namespaces) 14 | 15 | class ProgressWorker : public AsyncProgressWorker { 16 | public: 17 | ProgressWorker( 18 | Callback *callback 19 | , Callback *progress 20 | , int milliseconds 21 | , int iters) 22 | : AsyncProgressWorker(callback), progress(progress) 23 | , milliseconds(milliseconds), iters(iters) {} 24 | 25 | ~ProgressWorker() { 26 | delete progress; 27 | } 28 | 29 | void Execute (const AsyncProgressWorker::ExecutionProgress& progress) { 30 | for (int i = 0; i < iters; ++i) { 31 | progress.Signal(); 32 | Sleep(milliseconds); 33 | } 34 | } 35 | 36 | void HandleProgressCallback(const char *data, size_t count) { 37 | HandleScope scope; 38 | 39 | v8::Local<v8::Value> arg = New<v8::Boolean>(data == NULL && count == 0); 40 | progress->Call(1, &arg, async_resource); 41 | } 42 | 43 | private: 44 | Callback *progress; 45 | int milliseconds; 46 | int iters; 47 | }; 48 | 49 | NAN_METHOD(DoProgress) { 50 | Callback *progress = new Callback(To<v8::Function>(info[2]).ToLocalChecked()); 51 | Callback *callback = new Callback(To<v8::Function>(info[3]).ToLocalChecked()); 52 | AsyncQueueWorker(new ProgressWorker( 53 | callback 54 | , progress 55 | , To<uint32_t>(info[0]).FromJust() 56 | , To<uint32_t>(info[1]).FromJust())); 57 | } 58 | 59 | NAN_MODULE_INIT(Init) { 60 | Set(target 61 | , New<v8::String>("a").ToLocalChecked() 62 | , GetFunction(New<v8::FunctionTemplate>(DoProgress)).ToLocalChecked()); 63 | } 64 | 65 | NODE_MODULE(asyncprogressworkersignal, Init) 66 | -------------------------------------------------------------------------------- /test/cpp/asyncprogressworkerstream.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | #include "sleep.h" // NOLINT(build/include_subdir) 12 | 13 | using namespace Nan; // NOLINT(build/namespaces) 14 | 15 | // Custom data type: This serves as an example of how external 16 | // libraries could be hooked in, populate their objects and send them to JS. 17 | struct data_t { 18 | int index; 19 | int data; 20 | }; 21 | 22 | // Unlike test/cpp/ayncprogressworker.cpp this test is explicitly templated. 23 | template<typename T> 24 | class ProgressWorker : public AsyncProgressWorkerBase<T> { 25 | public: 26 | ProgressWorker( 27 | Callback *callback 28 | , Callback *progress 29 | , int milliseconds 30 | , int iters) 31 | : AsyncProgressWorkerBase<T>(callback), progress(progress) 32 | , milliseconds(milliseconds), iters(iters) {} 33 | 34 | ~ProgressWorker() { 35 | delete progress; 36 | } 37 | 38 | void Execute ( 39 | const typename AsyncProgressWorkerBase<T>::ExecutionProgress& progress) { 40 | data_t data; 41 | for (int i = 0; i < iters; ++i) { 42 | data.index = i; 43 | data.data = i * 2; 44 | progress.Send(&data, 1); 45 | Sleep(milliseconds); 46 | } 47 | } 48 | 49 | void HandleProgressCallback(const T *data, size_t count) { 50 | HandleScope scope; 51 | v8::Local<v8::Object> obj = Nan::New<v8::Object>(); 52 | Nan::Set( 53 | obj, 54 | Nan::New("index").ToLocalChecked(), 55 | New<v8::Integer>(data->index)); 56 | Nan::Set( 57 | obj, 58 | Nan::New("data").ToLocalChecked(), 59 | New<v8::Integer>(data->data)); 60 | 61 | v8::Local<v8::Value> argv[] = { obj }; 62 | progress->Call(1, argv, this->async_resource); 63 | } 64 | 65 | private: 66 | Callback *progress; 67 | int milliseconds; 68 | int iters; 69 | }; 70 | 71 | NAN_METHOD(DoProgress) { 72 | Callback *progress = new Callback(To<v8::Function>(info[2]).ToLocalChecked()); 73 | Callback *callback = new Callback(To<v8::Function>(info[3]).ToLocalChecked()); 74 | AsyncQueueWorker(new ProgressWorker<data_t>( 75 | callback 76 | , progress 77 | , To<uint32_t>(info[0]).FromJust() 78 | , To<uint32_t>(info[1]).FromJust())); 79 | } 80 | 81 | NAN_MODULE_INIT(Init) { 82 | Set(target 83 | , New<v8::String>("a").ToLocalChecked() 84 | , GetFunction(New<v8::FunctionTemplate>(DoProgress)).ToLocalChecked()); 85 | } 86 | 87 | NODE_MODULE(asyncprogressworkerstream, Init) 88 | -------------------------------------------------------------------------------- /test/cpp/asyncresource.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | #include "sleep.h" // NOLINT(build/include_subdir) 12 | 13 | using namespace Nan; // NOLINT(build/namespaces) 14 | 15 | class DelayRequest : public AsyncResource { 16 | public: 17 | DelayRequest(int milliseconds_, v8::Local<v8::Function> callback_) 18 | : AsyncResource("nan:test.DelayRequest"), 19 | milliseconds(milliseconds_) { 20 | callback.Reset(callback_); 21 | request.data = this; 22 | } 23 | ~DelayRequest() { 24 | callback.Reset(); 25 | } 26 | 27 | Persistent<v8::Function> callback; 28 | uv_work_t request; 29 | int milliseconds; 30 | }; 31 | 32 | void Delay(uv_work_t* req) { 33 | DelayRequest *delay_request = static_cast<DelayRequest*>(req->data); 34 | Sleep(delay_request->milliseconds); 35 | } 36 | 37 | void AfterDelay(uv_work_t* req, int status) { 38 | HandleScope scope; 39 | 40 | DelayRequest *delay_request = static_cast<DelayRequest*>(req->data); 41 | v8::Local<v8::Function> callback = New(delay_request->callback); 42 | 43 | v8::Local<v8::Object> target = New<v8::Object>(); 44 | 45 | // Run the callback in the async context. 46 | delay_request->runInAsyncScope(target, callback, 0, NULL); 47 | 48 | delete delay_request; 49 | } 50 | 51 | NAN_METHOD(Delay) { 52 | int delay = To<int>(info[0]).FromJust(); 53 | v8::Local<v8::Function> cb = To<v8::Function>(info[1]).ToLocalChecked(); 54 | 55 | DelayRequest* delay_request = new DelayRequest(delay, cb); 56 | 57 | uv_queue_work( 58 | GetCurrentEventLoop() 59 | , &delay_request->request 60 | , Delay 61 | , reinterpret_cast<uv_after_work_cb>(AfterDelay)); 62 | } 63 | 64 | NAN_MODULE_INIT(Init) { 65 | Set(target, New<v8::String>("delay").ToLocalChecked(), 66 | GetFunction(New<v8::FunctionTemplate>(Delay)).ToLocalChecked()); 67 | } 68 | 69 | NODE_MODULE(asyncresource, Init) 70 | -------------------------------------------------------------------------------- /test/cpp/asyncworker.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | #include "sleep.h" // NOLINT(build/include_subdir) 12 | 13 | using namespace Nan; // NOLINT(build/namespaces) 14 | 15 | class SleepWorker : public AsyncWorker { 16 | public: 17 | SleepWorker(Callback *callback, int milliseconds) 18 | : AsyncWorker(callback, "nan:test.SleepWorker"), 19 | milliseconds(milliseconds) {} 20 | ~SleepWorker() {} 21 | 22 | void Execute () { 23 | Sleep(milliseconds); 24 | } 25 | 26 | private: 27 | int milliseconds; 28 | }; 29 | 30 | NAN_METHOD(DoSleep) { 31 | Callback *callback = new Callback(To<v8::Function>(info[1]).ToLocalChecked()); 32 | AsyncQueueWorker( 33 | new SleepWorker(callback, To<uint32_t>(info[0]).FromJust())); 34 | } 35 | 36 | NAN_MODULE_INIT(Init) { 37 | Set(target 38 | , New<v8::String>("a").ToLocalChecked() 39 | , GetFunction(New<v8::FunctionTemplate>(DoSleep)).ToLocalChecked()); 40 | } 41 | 42 | NODE_MODULE(asyncworker, Init) 43 | -------------------------------------------------------------------------------- /test/cpp/asyncworkererror.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | class ErrorWorker : public AsyncWorker { 14 | public: 15 | explicit ErrorWorker(Callback *callback) : AsyncWorker(callback) {} 16 | ~ErrorWorker() {} 17 | 18 | void Execute () { 19 | SetErrorMessage("Error"); 20 | } 21 | }; 22 | 23 | NAN_METHOD(Work) { 24 | Callback *callback = new Callback(To<v8::Function>(info[0]).ToLocalChecked()); 25 | AsyncQueueWorker(new ErrorWorker(callback)); 26 | info.GetReturnValue().SetUndefined(); 27 | } 28 | 29 | NAN_MODULE_INIT(Init) { 30 | Set(target 31 | , New("a").ToLocalChecked() 32 | , GetFunction(New<v8::FunctionTemplate>(Work)).ToLocalChecked()); 33 | } 34 | 35 | NODE_MODULE(asyncworkererror, Init) 36 | -------------------------------------------------------------------------------- /test/cpp/buffer.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | static const size_t DATA_SIZE = 26; 14 | 15 | static char data[DATA_SIZE]; 16 | 17 | void callback(char* data, void* hint) { 18 | free(data); 19 | } 20 | 21 | NAN_METHOD(New1) { 22 | char *dynamic_data = static_cast<char *>(malloc(DATA_SIZE)); 23 | for (unsigned char i = 0; i < DATA_SIZE; i++) { 24 | dynamic_data[i] = 'a' + i; 25 | } 26 | info.GetReturnValue().Set( 27 | NewBuffer(dynamic_data, DATA_SIZE, callback, 0).ToLocalChecked()); 28 | } 29 | 30 | NAN_METHOD(New2) { 31 | v8::Local<v8::Object> buf = NewBuffer(DATA_SIZE).ToLocalChecked(); 32 | char* pbuf = node::Buffer::Data(buf); 33 | for (unsigned char i = 0; i < DATA_SIZE; i++) { 34 | pbuf[i] = 'a' + i; 35 | } 36 | info.GetReturnValue().Set(buf); 37 | } 38 | 39 | NAN_METHOD(New3) { 40 | char *dynamic_data = static_cast<char *>(malloc(DATA_SIZE)); 41 | for (unsigned char i = 0; i < DATA_SIZE; i++) { 42 | dynamic_data[i] = 'a' + i; 43 | } 44 | info.GetReturnValue().Set( 45 | NewBuffer(dynamic_data, DATA_SIZE).ToLocalChecked()); 46 | } 47 | 48 | NAN_METHOD(Copy) { 49 | info.GetReturnValue().Set(CopyBuffer(data, DATA_SIZE).ToLocalChecked()); 50 | } 51 | 52 | 53 | NAN_MODULE_INIT(Init) { 54 | for (unsigned char i = 0; i < DATA_SIZE; i++) { 55 | data[i] = 'a' + i; 56 | } 57 | Set(target 58 | , New<v8::String>("new1").ToLocalChecked() 59 | , GetFunction(New<v8::FunctionTemplate>(New1)).ToLocalChecked() 60 | ); 61 | Set(target 62 | , New<v8::String>("new2").ToLocalChecked() 63 | , GetFunction(New<v8::FunctionTemplate>(New2)).ToLocalChecked() 64 | ); 65 | Set(target 66 | , New<v8::String>("new3").ToLocalChecked() 67 | , GetFunction(New<v8::FunctionTemplate>(New3)).ToLocalChecked() 68 | ); 69 | Set(target 70 | , New<v8::String>("copy").ToLocalChecked() 71 | , GetFunction(New<v8::FunctionTemplate>(Copy)).ToLocalChecked() 72 | ); 73 | } 74 | 75 | NODE_MODULE(buffer, Init) 76 | -------------------------------------------------------------------------------- /test/cpp/bufferworkerpersistent.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | #include "sleep.h" // NOLINT(build/include_subdir) 12 | 13 | using namespace Nan; // NOLINT(build/namespaces) 14 | 15 | class BufferWorker : public AsyncWorker { 16 | public: 17 | BufferWorker( 18 | Callback *callback 19 | , int milliseconds 20 | , v8::Local<v8::Object> &bufferHandle 21 | ) 22 | : AsyncWorker(callback), milliseconds(milliseconds) { 23 | SaveToPersistent("buffer", bufferHandle); 24 | SaveToPersistent(New("puffer").ToLocalChecked(), bufferHandle); 25 | SaveToPersistent(0u, bufferHandle); 26 | } 27 | 28 | ~BufferWorker() {} 29 | 30 | void Execute () { 31 | Sleep(milliseconds); 32 | } 33 | 34 | void HandleOKCallback () { 35 | HandleScope scope; 36 | 37 | v8::Local<v8::Value> handle = GetFromPersistent("buffer"); 38 | callback->Call(1, &handle, async_resource); 39 | 40 | handle = GetFromPersistent(New("puffer").ToLocalChecked()); 41 | callback->Call(1, &handle, async_resource); 42 | 43 | handle = GetFromPersistent(0u); 44 | callback->Call(1, &handle, async_resource); 45 | } 46 | 47 | private: 48 | int milliseconds; 49 | }; 50 | 51 | NAN_METHOD(DoSleep) { 52 | v8::Local<v8::Object> bufferHandle = To<v8::Object>(info[1]).ToLocalChecked(); 53 | Callback *callback = new Callback(To<v8::Function>(info[2]).ToLocalChecked()); 54 | assert(!callback->IsEmpty() && "Callback should not be empty"); 55 | AsyncQueueWorker(new BufferWorker( 56 | callback 57 | , To<uint32_t>(info[0]).FromJust() 58 | , bufferHandle)); 59 | } 60 | 61 | NAN_MODULE_INIT(Init) { 62 | Set(target 63 | , New<v8::String>("a").ToLocalChecked() 64 | , GetFunction(New<v8::FunctionTemplate>(DoSleep)).ToLocalChecked()); 65 | } 66 | 67 | NODE_MODULE(bufferworkerpersistent, Init) 68 | -------------------------------------------------------------------------------- /test/cpp/callbackcontext.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | #include "sleep.h" // NOLINT(build/include_subdir) 12 | 13 | using namespace Nan; // NOLINT(build/namespaces) 14 | 15 | class DelayRequest : public AsyncResource { 16 | public: 17 | DelayRequest(int milliseconds_, v8::Local<v8::Function> callback_) 18 | : AsyncResource("nan:test.DelayRequest"), 19 | callback(callback_), 20 | milliseconds(milliseconds_) { 21 | request.data = this; 22 | } 23 | ~DelayRequest() {} 24 | 25 | Callback callback; 26 | uv_work_t request; 27 | int milliseconds; 28 | }; 29 | 30 | void Delay(uv_work_t* req) { 31 | DelayRequest *delay_request = static_cast<DelayRequest*>(req->data); 32 | Sleep(delay_request->milliseconds); 33 | } 34 | 35 | void AfterDelay(uv_work_t* req, int status) { 36 | HandleScope scope; 37 | 38 | DelayRequest *delay_request = static_cast<DelayRequest*>(req->data); 39 | 40 | v8::Local<v8::Object> target = New<v8::Object>(); 41 | 42 | // Run the callback in the async context. 43 | delay_request->callback.Call(target, 0, NULL, delay_request); 44 | 45 | delete delay_request; 46 | } 47 | 48 | NAN_METHOD(Delay) { 49 | int delay = To<int>(info[0]).FromJust(); 50 | v8::Local<v8::Function> cb = To<v8::Function>(info[1]).ToLocalChecked(); 51 | 52 | DelayRequest* delay_request = new DelayRequest(delay, cb); 53 | 54 | uv_queue_work( 55 | GetCurrentEventLoop() 56 | , &delay_request->request 57 | , Delay 58 | , reinterpret_cast<uv_after_work_cb>(AfterDelay)); 59 | } 60 | 61 | NAN_MODULE_INIT(Init) { 62 | Set(target, New<v8::String>("delay").ToLocalChecked(), 63 | GetFunction(New<v8::FunctionTemplate>(Delay)).ToLocalChecked()); 64 | } 65 | 66 | NODE_MODULE(asyncresource, Init) 67 | -------------------------------------------------------------------------------- /test/cpp/error.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | #define X(NAME) \ 14 | NAN_METHOD(Throw ## NAME ## 1) { \ 15 | return Nan::Throw ## NAME("errmsg"); \ 16 | } \ 17 | \ 18 | NAN_METHOD(Throw ## NAME ## 2) { \ 19 | return Nan::Throw ## NAME(Nan::New("errmsg").ToLocalChecked()); \ 20 | } \ 21 | \ 22 | NAN_METHOD(Throw ## NAME ## 3) { \ 23 | return Nan::ThrowError(NAME("errmsg")); \ 24 | } \ 25 | \ 26 | NAN_METHOD(Throw ## NAME ## 4) { \ 27 | return Nan::ThrowError(NAME(Nan::New("errmsg").ToLocalChecked())); \ 28 | } 29 | 30 | X(Error) 31 | X(RangeError) 32 | X(ReferenceError) 33 | X(SyntaxError) 34 | X(TypeError) 35 | 36 | #undef X 37 | 38 | #define EXPORT_ERROR_FUNCTIONS(NAME) \ 39 | X(Throw ## NAME ## 1) \ 40 | X(Throw ## NAME ## 2) \ 41 | X(Throw ## NAME ## 3) \ 42 | X(Throw ## NAME ## 4) 43 | 44 | #define X(NAME) \ 45 | Nan::Set( \ 46 | target \ 47 | , Nan::New(#NAME).ToLocalChecked() \ 48 | , Nan::GetFunction(New<v8::FunctionTemplate>(NAME)).ToLocalChecked()); 49 | 50 | 51 | NAN_MODULE_INIT(Init) { 52 | EXPORT_ERROR_FUNCTIONS(Error) 53 | EXPORT_ERROR_FUNCTIONS(RangeError) 54 | EXPORT_ERROR_FUNCTIONS(ReferenceError) 55 | EXPORT_ERROR_FUNCTIONS(SyntaxError) 56 | EXPORT_ERROR_FUNCTIONS(TypeError) 57 | } 58 | 59 | #undef EXPORT_ERROR_FUNCTIONS 60 | #undef X 61 | 62 | NODE_MODULE(error, Init) 63 | -------------------------------------------------------------------------------- /test/cpp/gc.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | static bool prologue_called = false; 14 | static bool epilogue_called = false; 15 | 16 | NAN_GC_CALLBACK(gcPrologueCallback) { 17 | prologue_called = true; 18 | } 19 | 20 | NAN_GC_CALLBACK(gcEpilogueCallback) { 21 | epilogue_called = true; 22 | } 23 | 24 | NAN_METHOD(Hook) { 25 | AddGCPrologueCallback(gcPrologueCallback); 26 | AddGCEpilogueCallback(gcEpilogueCallback); 27 | info.GetReturnValue().SetUndefined(); 28 | } 29 | 30 | NAN_METHOD(Check) { 31 | HandleScope scope; 32 | info.GetReturnValue().Set( 33 | New(prologue_called && epilogue_called)); 34 | } 35 | 36 | NAN_MODULE_INIT(Init) { 37 | Set(target 38 | , New<v8::String>("hook").ToLocalChecked() 39 | , GetFunction(New<v8::FunctionTemplate>(Hook)).ToLocalChecked() 40 | ); 41 | Set(target 42 | , New<v8::String>("check").ToLocalChecked() 43 | , GetFunction(New<v8::FunctionTemplate>(Check)).ToLocalChecked() 44 | ); 45 | } 46 | 47 | NODE_MODULE(gc, Init) 48 | -------------------------------------------------------------------------------- /test/cpp/indexedinterceptors.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | #include <cstring> 11 | 12 | using namespace Nan; // NOLINT(build/namespaces) 13 | 14 | class IndexedInterceptor : public ObjectWrap { 15 | char buf[256]; 16 | 17 | public: 18 | IndexedInterceptor() { std::strncpy(this->buf, "foo", sizeof (this->buf)); } 19 | static NAN_MODULE_INIT(Init); 20 | static v8::Local<v8::Value> NewInstance (); 21 | static NAN_METHOD(New); 22 | 23 | static NAN_INDEX_GETTER(PropertyGetter); 24 | static NAN_INDEX_SETTER(PropertySetter); 25 | static NAN_INDEX_ENUMERATOR(PropertyEnumerator); 26 | static NAN_INDEX_DELETER(PropertyDeleter); 27 | static NAN_INDEX_QUERY(PropertyQuery); 28 | }; 29 | 30 | static Persistent<v8::FunctionTemplate> indexedinterceptors_constructor; 31 | 32 | NAN_METHOD(CreateNew) { 33 | info.GetReturnValue().Set(IndexedInterceptor::NewInstance()); 34 | } 35 | 36 | NAN_MODULE_INIT(IndexedInterceptor::Init) { 37 | v8::Local<v8::FunctionTemplate> tpl = 38 | Nan::New<v8::FunctionTemplate>(IndexedInterceptor::New); 39 | indexedinterceptors_constructor.Reset(tpl); 40 | tpl->SetClassName(Nan::New("IndexedInterceptor").ToLocalChecked()); 41 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 42 | v8::Local<v8::ObjectTemplate> inst = tpl->InstanceTemplate(); 43 | 44 | SetIndexedPropertyHandler( 45 | inst 46 | , IndexedInterceptor::PropertyGetter 47 | , IndexedInterceptor::PropertySetter 48 | , IndexedInterceptor::PropertyQuery 49 | , IndexedInterceptor::PropertyDeleter 50 | , IndexedInterceptor::PropertyEnumerator); 51 | 52 | v8::Local<v8::Function> createnew = 53 | Nan::GetFunction(Nan::New<v8::FunctionTemplate>(CreateNew)) 54 | .ToLocalChecked(); 55 | Set(target, Nan::New("create").ToLocalChecked(), createnew); 56 | } 57 | 58 | v8::Local<v8::Value> IndexedInterceptor::NewInstance () { 59 | EscapableHandleScope scope; 60 | v8::Local<v8::FunctionTemplate> constructorHandle = 61 | Nan::New(indexedinterceptors_constructor); 62 | v8::Local<v8::Object> instance = 63 | Nan::NewInstance(Nan::GetFunction(constructorHandle).ToLocalChecked()) 64 | .ToLocalChecked(); 65 | return scope.Escape(instance); 66 | } 67 | 68 | NAN_METHOD(IndexedInterceptor::New) { 69 | IndexedInterceptor* interceptor = new IndexedInterceptor(); 70 | interceptor->Wrap(info.This()); 71 | info.GetReturnValue().Set(info.This()); 72 | } 73 | 74 | 75 | NAN_INDEX_GETTER(IndexedInterceptor::PropertyGetter) { 76 | IndexedInterceptor* interceptor = 77 | ObjectWrap::Unwrap<IndexedInterceptor>(info.Holder()); 78 | if (index == 0) { 79 | info.GetReturnValue().Set(Nan::New(interceptor->buf).ToLocalChecked()); 80 | } else { 81 | info.GetReturnValue().Set(Nan::New("bar").ToLocalChecked()); 82 | } 83 | return Intercepted::Yes(); 84 | } 85 | 86 | NAN_INDEX_SETTER(IndexedInterceptor::PropertySetter) { 87 | IndexedInterceptor* interceptor = 88 | ObjectWrap::Unwrap<IndexedInterceptor>(info.Holder()); 89 | if (index == 0) { 90 | std::strncpy( 91 | interceptor->buf 92 | , *Nan::Utf8String(value) 93 | , sizeof (interceptor->buf)); 94 | info.GetReturnValue().Set(info.This()); 95 | } else { 96 | info.GetReturnValue().Set(info.This()); 97 | } 98 | return Intercepted::Yes(); 99 | } 100 | 101 | NAN_INDEX_ENUMERATOR(IndexedInterceptor::PropertyEnumerator) { 102 | v8::Local<v8::Array> arr = Nan::New<v8::Array>(); 103 | Set(arr, 0, Nan::New(42)); 104 | info.GetReturnValue().Set(arr); 105 | return Intercepted::Yes(); 106 | } 107 | 108 | NAN_INDEX_DELETER(IndexedInterceptor::PropertyDeleter) { 109 | IndexedInterceptor* interceptor = 110 | ObjectWrap::Unwrap<IndexedInterceptor>(info.Holder()); 111 | std::strncpy(interceptor->buf, "goober", sizeof (interceptor->buf)); 112 | info.GetReturnValue().Set(True()); 113 | return Intercepted::Yes(); 114 | } 115 | 116 | NAN_INDEX_QUERY(IndexedInterceptor::PropertyQuery) { 117 | if (index == 1) { 118 | info.GetReturnValue().Set(Nan::New<v8::Integer>(v8::DontEnum)); 119 | return Intercepted::Yes(); 120 | } 121 | if (index == 42) { 122 | info.GetReturnValue().Set(Nan::New(0)); 123 | return Intercepted::Yes(); 124 | } 125 | return Intercepted::Yes(); 126 | } 127 | 128 | NODE_MODULE(indexedinterceptors, IndexedInterceptor::Init) 129 | -------------------------------------------------------------------------------- /test/cpp/isolatedata.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | struct Dummy { 14 | int value; 15 | }; 16 | 17 | NAN_METHOD(SetAndGet) { 18 | Dummy *d0 = new Dummy; 19 | Dummy *d1 = NULL; 20 | 21 | v8::Isolate *isolate = v8::Isolate::GetCurrent(); 22 | 23 | SetIsolateData<Dummy>(isolate, d0); 24 | d1 = GetIsolateData<Dummy>(isolate); 25 | 26 | delete d1; 27 | 28 | info.GetReturnValue().Set(New<v8::Boolean>(d0 == d1)); 29 | } 30 | 31 | NAN_MODULE_INIT(Init) { 32 | Set(target 33 | , New<v8::String>("setAndGet").ToLocalChecked() 34 | , GetFunction(New<v8::FunctionTemplate>(SetAndGet)).ToLocalChecked() 35 | ); 36 | } 37 | 38 | NODE_MODULE(isolatedata, Init) 39 | -------------------------------------------------------------------------------- /test/cpp/json-parse.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | NAN_METHOD(Parse) { 12 | Nan::JSON NanJSON; 13 | 14 | Nan::MaybeLocal<v8::String> inp = Nan::To<v8::String>(info[0]); 15 | 16 | if (!inp.IsEmpty()) { 17 | Nan::MaybeLocal<v8::Value> result = NanJSON.Parse( 18 | inp.ToLocalChecked() 19 | ); 20 | 21 | if (!result.IsEmpty()) { 22 | info.GetReturnValue().Set(result.ToLocalChecked()); 23 | } 24 | } 25 | } 26 | 27 | NAN_MODULE_INIT(Init) { 28 | Nan::Set(target 29 | , Nan::New<v8::String>("parse").ToLocalChecked() 30 | , Nan::GetFunction(Nan::New<v8::FunctionTemplate>(Parse)).ToLocalChecked() 31 | ); 32 | } 33 | 34 | NODE_MODULE(parse, Init) 35 | -------------------------------------------------------------------------------- /test/cpp/json-stringify.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | #include <string> 11 | 12 | NAN_METHOD(Stringify) { 13 | if (info.Length() > 0) { 14 | Nan::MaybeLocal<v8::Object> maybe_obj = Nan::To<v8::Object>(info[0]); 15 | if (!maybe_obj.IsEmpty()) { 16 | Nan::JSON NanJSON; 17 | v8::Local<v8::Object> obj = maybe_obj.ToLocalChecked(); 18 | 19 | if (3 == info.Length()) { 20 | if (info[2]->IsNumber()) { 21 | int32_t len = Nan::To<int32_t>(info[2]).FromJust(); 22 | len = (len > 10) ? 10 : len; 23 | len = (len < 0) ? 0 : len; 24 | Nan::MaybeLocal<v8::String> maybe_gap = 25 | Nan::New<v8::String>(std::string(len, ' ')); 26 | 27 | if (!maybe_gap.IsEmpty()) { 28 | v8::Local<v8::String> gap = maybe_gap.ToLocalChecked(); 29 | 30 | Nan::MaybeLocal<v8::String> result = 31 | NanJSON.Stringify(obj, gap); 32 | 33 | if (!result.IsEmpty()) { 34 | info.GetReturnValue().Set(result.ToLocalChecked()); 35 | } 36 | } 37 | } else if (info[2]->IsString()) { 38 | Nan::MaybeLocal<v8::String> result = NanJSON.Stringify( 39 | obj, 40 | Nan::To<v8::String>(info[2]).ToLocalChecked() 41 | ); 42 | 43 | if (!result.IsEmpty()) { 44 | info.GetReturnValue().Set(result.ToLocalChecked()); 45 | } 46 | } else { 47 | Nan::MaybeLocal<v8::String> result = NanJSON.Stringify(obj); 48 | 49 | if (!result.IsEmpty()) { 50 | info.GetReturnValue().Set(result.ToLocalChecked()); 51 | } 52 | } 53 | } else { 54 | Nan::MaybeLocal<v8::String> result = NanJSON.Stringify(obj); 55 | 56 | if (!result.IsEmpty()) { 57 | info.GetReturnValue().Set(result.ToLocalChecked()); 58 | } 59 | } 60 | } 61 | } 62 | } 63 | 64 | NAN_MODULE_INIT(Init) { 65 | Nan::Set(target 66 | , Nan::New<v8::String>("stringify").ToLocalChecked() 67 | , Nan::GetFunction(Nan::New<v8::FunctionTemplate>(Stringify)) 68 | .ToLocalChecked() 69 | ); 70 | } 71 | 72 | NODE_MODULE(stringify, Init) 73 | -------------------------------------------------------------------------------- /test/cpp/makecallback.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | class MyObject : public node::ObjectWrap { 14 | public: 15 | static NAN_MODULE_INIT(Init); 16 | 17 | private: 18 | explicit MyObject(v8::Local<v8::Object> resource); 19 | ~MyObject(); 20 | 21 | AsyncResource async_resource; 22 | 23 | static NAN_METHOD(New); 24 | static NAN_METHOD(CallEmit); 25 | static Persistent<v8::Function> constructor; 26 | }; 27 | 28 | Persistent<v8::Function> MyObject::constructor; 29 | 30 | MyObject::MyObject(v8::Local<v8::Object> resource) 31 | : async_resource("nan:test:makecallback", resource) { 32 | } 33 | 34 | MyObject::~MyObject() { 35 | } 36 | 37 | NAN_MODULE_INIT(MyObject::Init) { 38 | // Prepare constructor template 39 | v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); 40 | tpl->SetClassName(Nan::New<v8::String>("MyObject").ToLocalChecked()); 41 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 42 | 43 | SetPrototypeMethod(tpl, "call_emit", CallEmit); 44 | 45 | v8::Local<v8::Function> function = GetFunction(tpl).ToLocalChecked(); 46 | constructor.Reset(function); 47 | Set(target, Nan::New("MyObject").ToLocalChecked(), function); 48 | } 49 | 50 | NAN_METHOD(MyObject::New) { 51 | if (info.IsConstructCall()) { 52 | MyObject* obj = new MyObject(info.This()); 53 | obj->Wrap(info.This()); 54 | info.GetReturnValue().Set(info.This()); 55 | } else { 56 | v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor); 57 | info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked()); 58 | } 59 | } 60 | 61 | NAN_METHOD(MyObject::CallEmit) { 62 | v8::Local<v8::Value> argv[1] = { 63 | Nan::New("event").ToLocalChecked(), // event name 64 | }; 65 | 66 | MyObject* obj = node::ObjectWrap::Unwrap<MyObject>(info.This()); 67 | obj->async_resource.runInAsyncScope(info.This(), "emit", 1, argv); 68 | info.GetReturnValue().SetUndefined(); 69 | } 70 | 71 | NODE_MODULE(makecallback, MyObject::Init) 72 | -------------------------------------------------------------------------------- /test/cpp/maybe.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2019 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_METHOD(Test) { 14 | info.GetReturnValue().Set(false); 15 | { 16 | Maybe<int> mb = Nothing<int>(); 17 | if (mb.IsJust()) return; 18 | if (!mb.IsNothing()) return; 19 | if (mb.To(NULL)) return; 20 | } 21 | { 22 | Maybe<int> mb = Just(42); 23 | if (!mb.IsJust()) return; 24 | if (mb.IsNothing()) return; 25 | if (42 != mb.FromJust()) return; 26 | if (42 != mb.ToChecked()) return; 27 | mb.Check(); 28 | int v; 29 | if (!mb.To(&v)) return; 30 | if (42 != v) return; 31 | } 32 | info.GetReturnValue().Set(true); 33 | } 34 | 35 | NAN_MODULE_INIT(Init) { 36 | SetMethod(target, "test", Test); 37 | } 38 | 39 | NODE_MODULE(maybe, Init) 40 | -------------------------------------------------------------------------------- /test/cpp/morenews.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_METHOD(NewNumber) { 14 | info.GetReturnValue().Set(New(0.5)); 15 | } 16 | 17 | NAN_METHOD(NewNegativeInteger) { 18 | info.GetReturnValue().Set(New(-1)); 19 | } 20 | 21 | NAN_METHOD(NewPositiveInteger) { 22 | info.GetReturnValue().Set(New(1)); 23 | } 24 | 25 | NAN_METHOD(NewUtf8String) { 26 | const char s[] = "strïng"; 27 | info.GetReturnValue().Set(New(s).ToLocalChecked()); 28 | } 29 | 30 | NAN_METHOD(NewLatin1String) { 31 | const uint8_t s[] = "str\xefng"; 32 | info.GetReturnValue().Set(NewOneByteString(s).ToLocalChecked()); 33 | } 34 | 35 | NAN_METHOD(NewUcs2String) { 36 | uint16_t s[] = {'s', 't', 'r', 0xef, 'n', 'g', '\0'}; 37 | info.GetReturnValue().Set(New(s).ToLocalChecked()); 38 | } 39 | 40 | static const uint16_t ws[] = {'s', 't', 'r', 0xef, 'n', 'g', '\0'}; 41 | static const char s[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'}; 42 | 43 | class ExtString : public v8::String::ExternalStringResource { 44 | public: 45 | ~ExtString() { } 46 | const uint16_t *data() const { return ws; } 47 | size_t length() const { return sizeof (ws) / sizeof (*ws) - 1; } 48 | }; 49 | 50 | 51 | class ExtAsciiString : public ExternalOneByteStringResource { 52 | public: 53 | ~ExtAsciiString() { } 54 | const char *data() const { return s; } 55 | size_t length() const { return sizeof (s) / sizeof (*s) - 1; } 56 | }; 57 | 58 | NAN_METHOD(NewExternalStringResource) { 59 | v8::Local<v8::String> ext = New(new ExtString()).ToLocalChecked(); 60 | info.GetReturnValue().Set(ext); 61 | } 62 | 63 | NAN_METHOD(NewExternalAsciiStringResource) { 64 | v8::Local<v8::String> ext = New(new ExtAsciiString()).ToLocalChecked(); 65 | info.GetReturnValue().Set(ext); 66 | } 67 | 68 | NAN_MODULE_INIT(Init) { 69 | Set(target 70 | , New("newNumber").ToLocalChecked() 71 | , GetFunction(New<v8::FunctionTemplate>(NewNumber)).ToLocalChecked() 72 | ); 73 | Set(target 74 | , New("newNegativeInteger").ToLocalChecked() 75 | , GetFunction(New<v8::FunctionTemplate>(NewNegativeInteger)) 76 | .ToLocalChecked() 77 | ); 78 | Set(target 79 | , New("newPositiveInteger").ToLocalChecked() 80 | , GetFunction(New<v8::FunctionTemplate>(NewPositiveInteger)) 81 | .ToLocalChecked() 82 | ); 83 | Set(target 84 | , New("newUtf8String").ToLocalChecked() 85 | , GetFunction(New<v8::FunctionTemplate>(NewUtf8String)).ToLocalChecked() 86 | ); 87 | Set(target 88 | , New("newLatin1String").ToLocalChecked() 89 | , GetFunction(New<v8::FunctionTemplate>(NewLatin1String)).ToLocalChecked() 90 | ); 91 | Set(target 92 | , New("newUcs2String").ToLocalChecked() 93 | , GetFunction(New<v8::FunctionTemplate>(NewUcs2String)).ToLocalChecked() 94 | ); 95 | Set(target 96 | , New("newExternalStringResource").ToLocalChecked() 97 | , GetFunction(New<v8::FunctionTemplate>(NewExternalStringResource)) 98 | .ToLocalChecked() 99 | ); 100 | Set(target 101 | , New("newExternalAsciiStringResource").ToLocalChecked() 102 | , GetFunction(New<v8::FunctionTemplate>(NewExternalAsciiStringResource)) 103 | .ToLocalChecked() 104 | ); 105 | } 106 | 107 | NODE_MODULE(morenews, Init) 108 | -------------------------------------------------------------------------------- /test/cpp/multifile1.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | #include "./multifile2.h" 11 | 12 | using namespace Nan; // NOLINT(build/namespaces) 13 | 14 | NAN_MODULE_INIT(Init) { 15 | Set(target 16 | , New<v8::String>("r").ToLocalChecked() 17 | , GetFunction(New<v8::FunctionTemplate>(ReturnString)).ToLocalChecked() 18 | ); 19 | } 20 | 21 | NODE_MODULE(multifile, Init) 22 | -------------------------------------------------------------------------------- /test/cpp/multifile2.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | #include "multifile2.h" // NOLINT(build/include_subdir) 11 | 12 | using namespace Nan; // NOLINT(build/namespaces) 13 | 14 | NAN_METHOD(ReturnString) { 15 | v8::Local<v8::String> s = New(*Utf8String(info[0])).ToLocalChecked(); 16 | info.GetReturnValue().Set(s); 17 | } 18 | -------------------------------------------------------------------------------- /test/cpp/multifile2.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef TEST_CPP_MULTIFILE2_H_ 10 | #define TEST_CPP_MULTIFILE2_H_ 11 | 12 | #include <nan.h> 13 | 14 | using namespace Nan; // NOLINT(build/namespaces) 15 | 16 | NAN_METHOD(ReturnString); 17 | 18 | #endif // TEST_CPP_MULTIFILE2_H_ 19 | -------------------------------------------------------------------------------- /test/cpp/nancallback.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_METHOD(GlobalContext) { 14 | AsyncResource resource("nan:test.nancallback"); 15 | Callback(To<v8::Function>(info[0]).ToLocalChecked()).Call(0, NULL, &resource); 16 | } 17 | 18 | NAN_METHOD(SpecificContext) { 19 | AsyncResource resource("nan:test.nancallback"); 20 | Callback cb(To<v8::Function>(info[0]).ToLocalChecked()); 21 | cb.Call(GetCurrentContext()->Global(), 0, NULL, &resource); 22 | } 23 | 24 | NAN_METHOD(CustomReceiver) { 25 | AsyncResource resource("nan:test.nancallback"); 26 | Callback cb(To<v8::Function>(info[0]).ToLocalChecked()); 27 | cb.Call(To<v8::Object>(info[1]).ToLocalChecked(), 0, NULL, &resource); 28 | } 29 | 30 | NAN_METHOD(CompareCallbacks) { 31 | Callback cb1(To<v8::Function>(info[0]).ToLocalChecked()); 32 | Callback cb2(To<v8::Function>(info[1]).ToLocalChecked()); 33 | Callback cb3(To<v8::Function>(info[2]).ToLocalChecked()); 34 | 35 | info.GetReturnValue().Set(New<v8::Boolean>(cb1 == cb2 && cb1 != cb3)); 36 | } 37 | 38 | NAN_METHOD(CallDirect) { 39 | Callback cb(To<v8::Function>(info[0]).ToLocalChecked()); 40 | Call(*cb, GetCurrentContext()->Global(), 0, NULL); 41 | } 42 | 43 | NAN_METHOD(CallAsFunction) { 44 | AsyncResource resource("nan:test.nancallback"); 45 | Callback(To<v8::Function>(info[0]).ToLocalChecked())(&resource); 46 | } 47 | 48 | NAN_METHOD(ResetUnset) { 49 | Callback callback; 50 | callback.Reset(); 51 | info.GetReturnValue().Set(callback.IsEmpty()); 52 | } 53 | 54 | NAN_METHOD(ResetSet) { 55 | Callback callback(To<v8::Function>(info[0]).ToLocalChecked()); 56 | callback.Reset(); 57 | info.GetReturnValue().Set(callback.IsEmpty()); 58 | } 59 | 60 | NAN_METHOD(CallRetval) { 61 | AsyncResource resource("nan:test.nancallback"); 62 | Callback callback(To<v8::Function>(info[0]).ToLocalChecked()); 63 | v8::Local<v8::Value> result = 64 | callback.Call(0, NULL, &resource).ToLocalChecked(); 65 | if (result->IsNumber()) { 66 | info.GetReturnValue().Set(Nan::True()); 67 | } else { 68 | info.GetReturnValue().Set(Nan::False()); 69 | } 70 | } 71 | 72 | NAN_MODULE_INIT(Init) { 73 | Set(target 74 | , New<v8::String>("globalContext").ToLocalChecked() 75 | , GetFunction(New<v8::FunctionTemplate>(GlobalContext)).ToLocalChecked() 76 | ); 77 | Set(target 78 | , New<v8::String>("specificContext").ToLocalChecked() 79 | , GetFunction(New<v8::FunctionTemplate>(SpecificContext)).ToLocalChecked() 80 | ); 81 | Set(target 82 | , New<v8::String>("customReceiver").ToLocalChecked() 83 | , GetFunction(New<v8::FunctionTemplate>(CustomReceiver)).ToLocalChecked() 84 | ); 85 | Set(target 86 | , New<v8::String>("compareCallbacks").ToLocalChecked() 87 | , GetFunction(New<v8::FunctionTemplate>(CompareCallbacks)).ToLocalChecked() 88 | ); 89 | Set(target 90 | , New<v8::String>("callDirect").ToLocalChecked() 91 | , GetFunction(New<v8::FunctionTemplate>(CallDirect)).ToLocalChecked() 92 | ); 93 | Set(target 94 | , New<v8::String>("callAsFunction").ToLocalChecked() 95 | , GetFunction(New<v8::FunctionTemplate>(CallAsFunction)).ToLocalChecked() 96 | ); 97 | Set(target 98 | , New<v8::String>("resetUnset").ToLocalChecked() 99 | , GetFunction(New<v8::FunctionTemplate>(ResetUnset)).ToLocalChecked() 100 | ); 101 | Set(target 102 | , New<v8::String>("resetSet").ToLocalChecked() 103 | , GetFunction(New<v8::FunctionTemplate>(ResetSet)).ToLocalChecked() 104 | ); 105 | Set(target 106 | , New<v8::String>("callRetval").ToLocalChecked() 107 | , GetFunction(New<v8::FunctionTemplate>(CallRetval)).ToLocalChecked() 108 | ); 109 | } 110 | 111 | NODE_MODULE(nancallback, Init) 112 | -------------------------------------------------------------------------------- /test/cpp/objectwraphandle.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | class MyObject : public ObjectWrap { 14 | public: 15 | static NAN_MODULE_INIT(Init) { 16 | v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); 17 | tpl->SetClassName(Nan::New("MyObject").ToLocalChecked()); 18 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 19 | 20 | SetPrototypeMethod(tpl, "getHandle", GetHandle); 21 | SetPrototypeMethod(tpl, "getHandleConst", GetHandleConst); 22 | SetPrototypeMethod(tpl, "getValue", GetValue); 23 | 24 | constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); 25 | Set(target, Nan::New("MyObject").ToLocalChecked(), 26 | Nan::GetFunction(tpl).ToLocalChecked()); 27 | } 28 | 29 | private: 30 | explicit MyObject(double value = 0) : value_(value) {} 31 | ~MyObject() {} 32 | 33 | static NAN_METHOD(New) { 34 | if (info.IsConstructCall()) { 35 | double value = 36 | info[0]->IsUndefined() ? 0 : Nan::To<double>(info[0]).FromJust(); 37 | MyObject *obj = new MyObject(value); 38 | obj->Wrap(info.This()); 39 | info.GetReturnValue().Set(info.This()); 40 | } else { 41 | const int argc = 1; 42 | v8::Local<v8::Value> argv[argc] = {info[0]}; 43 | v8::Local<v8::Function> cons = Nan::New(constructor()); 44 | info.GetReturnValue().Set( 45 | Nan::NewInstance(cons, argc, argv).ToLocalChecked()); 46 | } 47 | } 48 | 49 | static NAN_METHOD(GetHandle) { 50 | MyObject* obj = ObjectWrap::Unwrap<MyObject>(info.Holder()); 51 | info.GetReturnValue().Set(obj->handle()); 52 | } 53 | 54 | static NAN_METHOD(GetHandleConst) { 55 | MyObject const *obj = ObjectWrap::Unwrap<MyObject>(info.Holder()); 56 | info.GetReturnValue().Set(obj->handle()); 57 | } 58 | 59 | static NAN_METHOD(GetValue) { 60 | MyObject* obj = ObjectWrap::Unwrap<MyObject>(info.Holder()); 61 | info.GetReturnValue().Set(obj->value_); 62 | } 63 | 64 | static inline Persistent<v8::Function> & constructor() { 65 | static Persistent<v8::Function> my_constructor; 66 | return my_constructor; 67 | } 68 | 69 | double value_; 70 | }; 71 | 72 | NODE_MODULE(objectwraphandle, MyObject::Init) 73 | -------------------------------------------------------------------------------- /test/cpp/persistent.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | #include <cstring> // memset() 11 | 12 | using namespace Nan; // NOLINT(build/namespaces) 13 | 14 | static Persistent<v8::String> persistentTest1; 15 | 16 | NAN_METHOD(Save1) { 17 | persistentTest1.Reset(To<v8::String>(info[0]).ToLocalChecked()); 18 | } 19 | 20 | NAN_METHOD(Get1) { 21 | info.GetReturnValue().Set(New(persistentTest1)); 22 | } 23 | 24 | NAN_METHOD(Dispose1) { 25 | persistentTest1.Reset(); 26 | } 27 | 28 | NAN_METHOD(ToPersistentAndBackAgain) { 29 | Persistent<v8::Object> persistent(To<v8::Object>(info[0]).ToLocalChecked()); 30 | v8::Local<v8::Object> object = New(persistent); 31 | persistent.Reset(); 32 | memset(&persistent, -1, sizeof(persistent)); // Clobber it good. 33 | info.GetReturnValue().Set(object); 34 | } 35 | 36 | NAN_METHOD(PersistentToPersistent) { 37 | Persistent<v8::String> persistent(To<v8::String>(info[0]).ToLocalChecked()); 38 | persistentTest1.Reset(persistent); 39 | persistent.Reset(); 40 | info.GetReturnValue().Set(New(persistentTest1)); 41 | persistentTest1.Reset(); 42 | } 43 | 44 | NAN_METHOD(CopyablePersistent) { 45 | CopyablePersistentTraits<v8::String>::CopyablePersistent p; 46 | p = persistentTest1; 47 | info.GetReturnValue().Set(New(p)); 48 | } 49 | 50 | template<typename T> Global<T> passer(v8::Local<T> handle) { 51 | return Global<T>(handle).Pass(); 52 | } 53 | 54 | NAN_METHOD(PassGlobal) { 55 | info.GetReturnValue().Set(passer(New(42))); 56 | } 57 | 58 | NAN_MODULE_INIT(Init) { 59 | Set(target 60 | , New<v8::String>("save1").ToLocalChecked() 61 | , GetFunction(New<v8::FunctionTemplate>(Save1)).ToLocalChecked() 62 | ); 63 | Set(target 64 | , New<v8::String>("get1").ToLocalChecked() 65 | , GetFunction(New<v8::FunctionTemplate>(Get1)).ToLocalChecked() 66 | ); 67 | Set(target 68 | , New<v8::String>("dispose1").ToLocalChecked() 69 | , GetFunction(New<v8::FunctionTemplate>(Dispose1)).ToLocalChecked() 70 | ); 71 | Set(target 72 | , New<v8::String>("toPersistentAndBackAgain").ToLocalChecked() 73 | , GetFunction(New<v8::FunctionTemplate>(ToPersistentAndBackAgain)) 74 | .ToLocalChecked() 75 | ); 76 | Set(target 77 | , New<v8::String>("persistentToPersistent").ToLocalChecked() 78 | , GetFunction(New<v8::FunctionTemplate>(PersistentToPersistent)) 79 | .ToLocalChecked() 80 | ); 81 | Set(target 82 | , New<v8::String>("copyablePersistent").ToLocalChecked() 83 | , GetFunction(New<v8::FunctionTemplate>(CopyablePersistent)) 84 | .ToLocalChecked() 85 | ); 86 | Set(target 87 | , New<v8::String>("passGlobal").ToLocalChecked() 88 | , GetFunction(New<v8::FunctionTemplate>(PassGlobal)) 89 | .ToLocalChecked() 90 | ); 91 | } 92 | 93 | NODE_MODULE(persistent, Init) 94 | -------------------------------------------------------------------------------- /test/cpp/private.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_METHOD(HasPrivateYes) { 14 | v8::Local<v8::Object> object = New<v8::Object>(); 15 | v8::Local<v8::String> key = New("key").ToLocalChecked(); 16 | v8::Local<v8::String> value = New("value").ToLocalChecked(); 17 | Maybe<bool> mb = SetPrivate(object, key, value); 18 | bool v1 = mb.IsJust() ? mb.FromJust() : false; 19 | mb = HasPrivate(object, key); 20 | bool v2 = mb.IsJust() ? mb.FromJust() : false; 21 | MaybeLocal<v8::Value> mv = GetPrivate(object, key); 22 | bool v3 = mv.IsEmpty() ? false : 23 | !strcmp(*Utf8String(mv.ToLocalChecked()), "value"); 24 | info.GetReturnValue().Set(v1 && v2 && v3); 25 | } 26 | 27 | NAN_METHOD(HasPrivateNo) { 28 | v8::Local<v8::Object> object = New<v8::Object>(); 29 | Maybe<bool> mb = HasPrivate(object, New("key").ToLocalChecked()); 30 | bool v1 = mb.IsJust() ? !mb.FromJust() : false; 31 | MaybeLocal<v8::Value> q = GetPrivate(object, New("key").ToLocalChecked()); 32 | bool v2 = !q.IsEmpty() ? q.ToLocalChecked()->IsUndefined() : false; 33 | info.GetReturnValue().Set(v1 && v2); 34 | } 35 | 36 | NAN_METHOD(DeletePrivateNo) { 37 | v8::Local<v8::Object> object = New<v8::Object>(); 38 | v8::Local<v8::String> key = New("key").ToLocalChecked(); 39 | v8::Local<v8::String> value = New("value").ToLocalChecked(); 40 | Maybe<bool> mb = DeletePrivate(object, key); 41 | bool v1 = mb.IsJust() ? mb.FromJust() : false; 42 | mb = SetPrivate(object, key, value); 43 | bool v2 = mb.IsJust() ? mb.FromJust() : false; 44 | mb = DeletePrivate(object, key); 45 | bool v3 = mb.IsJust() ? mb.FromJust() : false; 46 | info.GetReturnValue().Set(v1 && v2 && v3); 47 | } 48 | 49 | NAN_METHOD(NoConflict) { 50 | v8::Local<v8::Object> object = New<v8::Object>(); 51 | v8::Local<v8::String> key = New("key").ToLocalChecked(); 52 | v8::Local<v8::String> value = New("value").ToLocalChecked(); 53 | v8::Local<v8::String> other_value = New("other_value").ToLocalChecked(); 54 | SetPrivate(object, key, value); 55 | Set(object, key, other_value); 56 | v8::Local<v8::Value> got = GetPrivate(object, key).ToLocalChecked(); 57 | bool v1 = To<v8::String>(got).ToLocalChecked()->StrictEquals(value); 58 | v8::Local<v8::Value> got_other = Get(object, key).ToLocalChecked(); 59 | bool v2 = got_other->StrictEquals(other_value); 60 | DeletePrivate(object, key); 61 | got_other = Get(object, key).ToLocalChecked(); 62 | bool v3 = got_other->StrictEquals(other_value); 63 | info.GetReturnValue().Set(v1 && v2 && v3); 64 | } 65 | 66 | NAN_MODULE_INIT(Init) { 67 | Set(target 68 | , New<v8::String>("hasPrivateYes").ToLocalChecked() 69 | , GetFunction(New<v8::FunctionTemplate>(HasPrivateYes)).ToLocalChecked() 70 | ); 71 | Set(target 72 | , New<v8::String>("hasPrivateNo").ToLocalChecked() 73 | , GetFunction(New<v8::FunctionTemplate>(HasPrivateNo)).ToLocalChecked() 74 | ); 75 | Set(target 76 | , New<v8::String>("deletePrivateNo").ToLocalChecked() 77 | , GetFunction(New<v8::FunctionTemplate>(DeletePrivateNo)).ToLocalChecked() 78 | ); 79 | Set(target 80 | , New<v8::String>("noConflict").ToLocalChecked() 81 | , GetFunction(New<v8::FunctionTemplate>(NoConflict)).ToLocalChecked() 82 | ); 83 | } 84 | 85 | NODE_MODULE(private, Init) 86 | -------------------------------------------------------------------------------- /test/cpp/returnemptystring.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_METHOD(ReturnEmptyString) { 14 | info.GetReturnValue().SetEmptyString(); 15 | } 16 | 17 | NAN_MODULE_INIT(Init) { 18 | Set(target 19 | , New<v8::String>("r").ToLocalChecked() 20 | , GetFunction(New<v8::FunctionTemplate>(ReturnEmptyString)).ToLocalChecked() 21 | ); 22 | } 23 | 24 | NODE_MODULE(returnemptystring, Init) 25 | 26 | -------------------------------------------------------------------------------- /test/cpp/returnnull.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | NAN_METHOD(ReturnNull) { 12 | info.GetReturnValue().SetNull(); 13 | } 14 | 15 | NAN_MODULE_INIT(Init) { 16 | Nan::Set(target 17 | , Nan::New<v8::String>("r").ToLocalChecked() 18 | , Nan::GetFunction(Nan::New<v8::FunctionTemplate>(ReturnNull)) 19 | .ToLocalChecked() 20 | ); 21 | } 22 | 23 | NODE_MODULE(returnnull, Init) 24 | 25 | -------------------------------------------------------------------------------- /test/cpp/returnundefined.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_METHOD(ReturnUndefined) { 14 | info.GetReturnValue().SetUndefined(); 15 | } 16 | 17 | NAN_MODULE_INIT(Init) { 18 | Set(target 19 | , New<v8::String>("r").ToLocalChecked() 20 | , GetFunction(New<v8::FunctionTemplate>(ReturnUndefined)).ToLocalChecked() 21 | ); 22 | } 23 | 24 | NODE_MODULE(returnundefined, Init) 25 | 26 | -------------------------------------------------------------------------------- /test/cpp/returnvalue.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | static Global<v8::Boolean> global; 14 | 15 | NAN_METHOD(ReturnAValue) { 16 | const FunctionCallbackInfo<v8::Value> &cbinfo = info; 17 | ReturnValue<v8::Value> ret = cbinfo.GetReturnValue(); 18 | if (cbinfo.Length() == 1) { 19 | ret.Set(To<v8::String>(info[0]).ToLocalChecked()); 20 | } else { 21 | ret.Set(New("default").ToLocalChecked()); 22 | } 23 | } 24 | 25 | NAN_METHOD(ReturnPrimitive) { 26 | info.GetReturnValue().Set(true); 27 | } 28 | 29 | NAN_METHOD(ReturnGlobal) { 30 | info.GetReturnValue().Set(global); 31 | global.Reset(); 32 | } 33 | 34 | NAN_METHOD(ReturnUnsigned) { 35 | info.GetReturnValue().Set(0x80000000u); 36 | } 37 | 38 | NAN_MODULE_INIT(Init) { 39 | global.Reset(New(true)); 40 | 41 | Set(target 42 | , New<v8::String>("r").ToLocalChecked() 43 | , GetFunction(New<v8::FunctionTemplate>(ReturnAValue)).ToLocalChecked() 44 | ); 45 | Set(target 46 | , New<v8::String>("p").ToLocalChecked() 47 | , GetFunction(New<v8::FunctionTemplate>(ReturnPrimitive)).ToLocalChecked() 48 | ); 49 | Set(target 50 | , New<v8::String>("q").ToLocalChecked() 51 | , GetFunction(New<v8::FunctionTemplate>(ReturnGlobal)).ToLocalChecked() 52 | ); 53 | Set(target 54 | , New<v8::String>("u").ToLocalChecked() 55 | , GetFunction(New<v8::FunctionTemplate>(ReturnUnsigned)).ToLocalChecked() 56 | ); 57 | } 58 | 59 | NODE_MODULE(returnvalue, Init) 60 | -------------------------------------------------------------------------------- /test/cpp/setcallhandler.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_METHOD(CallHandler) { 14 | info.GetReturnValue().Set(12); 15 | } 16 | 17 | NAN_METHOD(CallHandlerSetter) { 18 | v8::Local<v8::FunctionTemplate> tpl = New<v8::FunctionTemplate>(); 19 | SetCallHandler(tpl, CallHandler); 20 | info.GetReturnValue().Set(GetFunction(tpl).ToLocalChecked()); 21 | } 22 | 23 | NAN_METHOD(CallAsFunctionHandler) { 24 | info.GetReturnValue().Set(15); 25 | } 26 | 27 | NAN_METHOD(CallAsFunctionHandlerSetter) { 28 | v8::Local<v8::ObjectTemplate> tpl = New<v8::ObjectTemplate>(); 29 | SetCallAsFunctionHandler(tpl, CallAsFunctionHandler); 30 | info.GetReturnValue().Set(NewInstance(tpl).ToLocalChecked()); 31 | } 32 | 33 | NAN_MODULE_INIT(Init) { 34 | Set(target 35 | , New("a").ToLocalChecked() 36 | , GetFunction(New<v8::FunctionTemplate>(CallHandlerSetter)).ToLocalChecked() 37 | ); 38 | Set(target 39 | , New("b").ToLocalChecked() 40 | , GetFunction(New<v8::FunctionTemplate>(CallAsFunctionHandlerSetter)) 41 | .ToLocalChecked() 42 | ); 43 | } 44 | 45 | NODE_MODULE(setcallhandler, Init) 46 | 47 | -------------------------------------------------------------------------------- /test/cpp/settemplate.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | class MyObject : public node::ObjectWrap { 14 | public: 15 | static NAN_MODULE_INIT(Init); 16 | 17 | private: 18 | MyObject(); 19 | ~MyObject(); 20 | 21 | static NAN_METHOD(New); 22 | static Persistent<v8::Function> constructor; 23 | }; 24 | 25 | Persistent<v8::Function> MyObject::constructor; 26 | 27 | MyObject::MyObject() { 28 | } 29 | 30 | MyObject::~MyObject() { 31 | } 32 | 33 | void Foo(FunctionCallbackInfo<v8::Value> const&) {} 34 | 35 | NAN_MODULE_INIT(MyObject::Init) { 36 | // Prepare constructor template 37 | v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); 38 | tpl->SetClassName(Nan::New<v8::String>("MyObject").ToLocalChecked()); 39 | tpl->InstanceTemplate()->SetInternalFieldCount(1); 40 | 41 | // Prototype 42 | SetPrototypeTemplate( 43 | tpl 44 | , "prototypeProp" 45 | , Nan::New<v8::String>("a prototype property").ToLocalChecked()); 46 | 47 | // Instance 48 | SetInstanceTemplate( 49 | tpl 50 | , "instanceProp" 51 | , Nan::New<v8::String>("an instance property").ToLocalChecked()); 52 | 53 | // PropertyAttributes 54 | SetInstanceTemplate( 55 | tpl 56 | , Nan::New<v8::String>("none").ToLocalChecked() 57 | , Nan::New<v8::String>("none").ToLocalChecked() 58 | , v8::None); 59 | SetInstanceTemplate( 60 | tpl 61 | , Nan::New<v8::String>("readOnly").ToLocalChecked() 62 | , Nan::New<v8::String>("readOnly").ToLocalChecked() 63 | , v8::ReadOnly); 64 | SetInstanceTemplate( 65 | tpl 66 | , Nan::New<v8::String>("dontEnum").ToLocalChecked() 67 | , Nan::New<v8::String>("dontEnum").ToLocalChecked() 68 | , v8::DontEnum); 69 | SetInstanceTemplate( 70 | tpl 71 | , Nan::New<v8::String>("dontDelete").ToLocalChecked() 72 | , Nan::New<v8::String>("dontDelete").ToLocalChecked() 73 | , v8::DontDelete); 74 | 75 | v8::Local<v8::Function> function = Nan::GetFunction(tpl).ToLocalChecked(); 76 | constructor.Reset(function); 77 | Set(target 78 | , Nan::New<v8::String>("MyObject").ToLocalChecked() 79 | , function); 80 | 81 | 82 | //=== SetMethod ============================================================== 83 | 84 | v8::Local<v8::Object> obj = Nan::New<v8::Object>(); 85 | SetMethod(obj, "foo", Foo); 86 | 87 | // https://github.com/nodejs/nan/issues/564 88 | v8::Local<v8::Function> func = Nan::New<v8::Function>(Foo); 89 | SetMethod(func, "foo", Foo); 90 | 91 | v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(Foo); 92 | SetMethod(t, "foo", Foo); 93 | } 94 | 95 | NAN_METHOD(MyObject::New) { 96 | if (info.IsConstructCall()) { 97 | MyObject* obj = new MyObject(); 98 | obj->Wrap(info.This()); 99 | info.GetReturnValue().Set(info.This()); 100 | } else { 101 | v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor); 102 | info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked()); 103 | } 104 | } 105 | 106 | NODE_MODULE(settemplate, MyObject::Init) 107 | -------------------------------------------------------------------------------- /test/cpp/sleep.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #ifndef TEST_CPP_SLEEP_H_ 10 | #define TEST_CPP_SLEEP_H_ 11 | 12 | #ifndef _WIN32 13 | #include <unistd.h> 14 | #define Sleep(x) usleep((x)*1000) 15 | #endif 16 | 17 | #endif // TEST_CPP_SLEEP_H_ 18 | -------------------------------------------------------------------------------- /test/cpp/strings.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_METHOD(ReturnUtf8String) { 14 | info.GetReturnValue().Set(New(*Utf8String(info[0])).ToLocalChecked()); 15 | } 16 | 17 | NAN_METHOD(HeapString) { 18 | Utf8String *s = new Utf8String(info[0]); 19 | v8::Local<v8::String> res = New(**s).ToLocalChecked(); 20 | delete s; 21 | info.GetReturnValue().Set(res); 22 | } 23 | 24 | NAN_METHOD(EncodeHex) { 25 | info.GetReturnValue().Set(Encode("hello", 5, HEX)); 26 | } 27 | 28 | NAN_METHOD(EncodeUCS2) { 29 | info.GetReturnValue().Set(Encode(u"hello", 10, UCS2)); 30 | } 31 | 32 | Persistent<v8::FunctionTemplate> returnUtf8String_persistent; 33 | Persistent<v8::FunctionTemplate> heapString_persistent; 34 | Persistent<v8::FunctionTemplate> encodeHex_persistent; 35 | Persistent<v8::FunctionTemplate> encodeUCS2_persistent; 36 | 37 | NAN_MODULE_INIT(Init) { 38 | v8::Local<v8::FunctionTemplate> returnUtf8String = 39 | New<v8::FunctionTemplate>(ReturnUtf8String); 40 | 41 | returnUtf8String_persistent.Reset(returnUtf8String); 42 | 43 | Set(target 44 | , New("returnUtf8String").ToLocalChecked() 45 | , GetFunction(returnUtf8String).ToLocalChecked() 46 | ).FromJust(); 47 | 48 | v8::Local<v8::FunctionTemplate> heapString = 49 | New<v8::FunctionTemplate>(HeapString); 50 | 51 | heapString_persistent.Reset(heapString); 52 | 53 | Set(target 54 | , New("heapString").ToLocalChecked() 55 | , GetFunction(heapString).ToLocalChecked() 56 | ).FromJust(); 57 | 58 | v8::Local<v8::FunctionTemplate> encodeHex = 59 | New<v8::FunctionTemplate>(EncodeHex); 60 | 61 | encodeHex_persistent.Reset(encodeHex); 62 | 63 | Set(target 64 | , New("encodeHex").ToLocalChecked() 65 | , GetFunction(encodeHex).ToLocalChecked() 66 | ).FromJust(); 67 | 68 | v8::Local<v8::FunctionTemplate> encodeUCS2 = 69 | New<v8::FunctionTemplate>(EncodeUCS2); 70 | 71 | encodeUCS2_persistent.Reset(encodeUCS2); 72 | 73 | Set(target 74 | , New("encodeUCS2").ToLocalChecked() 75 | , GetFunction(encodeUCS2).ToLocalChecked() 76 | ).FromJust(); 77 | } 78 | 79 | NODE_MODULE(strings, Init) 80 | -------------------------------------------------------------------------------- /test/cpp/symbols.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_MODULE_INIT(Init) { 14 | Set(target 15 | , New<v8::String>("key").ToLocalChecked() 16 | , New<v8::String>("a property").ToLocalChecked() 17 | ); 18 | } 19 | 20 | NODE_MODULE(symbols, Init) 21 | -------------------------------------------------------------------------------- /test/cpp/threadlocal.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | #define _(e) NAN_TEST_EXPRESSION(e) 14 | 15 | // Based on test-thread.c from libuv. 16 | 17 | class TlsTest : public AsyncWorker { 18 | public: 19 | explicit TlsTest(Tap *t) : AsyncWorker(NULL), t(t), i(0) { 20 | t->plan(7); 21 | t->ok(_(0 == nauv_key_create(&tls_key))); 22 | t->ok(_(NULL == nauv_key_get(&tls_key))); 23 | nauv_key_set(&tls_key, this); 24 | t->ok(_(this == nauv_key_get(&tls_key))); 25 | } 26 | void Execute() { 27 | ok(_(NULL == nauv_key_get(&tls_key))); 28 | nauv_key_set(&tls_key, &i); 29 | ok(_(&i == nauv_key_get(&tls_key))); 30 | nauv_key_set(&tls_key, NULL); 31 | ok(_(NULL == nauv_key_get(&tls_key))); 32 | } 33 | void WorkComplete() { 34 | HandleScope scope; 35 | for (unsigned j = 0; j < i; ++j) 36 | t->ok(res[j].ok, res[j].msg); 37 | nauv_key_delete(&tls_key); 38 | t->ok(_(NULL == ErrorMessage())); 39 | t->end(); 40 | delete t; 41 | } 42 | 43 | private: 44 | nauv_key_t tls_key; 45 | 46 | Tap *t; 47 | struct { bool ok; const char* msg; } res[3]; 48 | unsigned i; 49 | void ok(bool isOk, const char *msg) { 50 | assert(i < sizeof(res)/sizeof(res[0])); 51 | res[i].ok = isOk; 52 | res[i].msg = msg; 53 | ++i; 54 | } 55 | }; 56 | 57 | NAN_METHOD(thread_local_storage) { 58 | Tap *t = new Tap(info[0]); 59 | AsyncQueueWorker(new TlsTest(t)); 60 | info.GetReturnValue().SetUndefined(); 61 | } 62 | 63 | NAN_MODULE_INIT(Init) { 64 | Set(target 65 | , New<v8::String>("thread_local_storage").ToLocalChecked() 66 | , GetFunction(New<v8::FunctionTemplate>(thread_local_storage)) 67 | .ToLocalChecked() 68 | ); 69 | } 70 | 71 | NODE_MODULE(threadlocal, Init) 72 | -------------------------------------------------------------------------------- /test/cpp/trycatch.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | NAN_METHOD(TryCatchTest) { 14 | TryCatch try_catch; 15 | v8::Local<v8::String> s = New("throw 'waaa'").ToLocalChecked(); 16 | v8::Local<UnboundScript> script = New<UnboundScript>(s).ToLocalChecked(); 17 | MaybeLocal<v8::Value> result = RunScript(script); 18 | if (result.IsEmpty()) { 19 | assert(try_catch.HasCaught()); 20 | try_catch.ReThrow(); 21 | } 22 | } 23 | 24 | NAN_MODULE_INIT(Init) { 25 | Set(target 26 | , New<v8::String>("r").ToLocalChecked() 27 | , GetFunction(New<v8::FunctionTemplate>(TryCatchTest)).ToLocalChecked() 28 | ); 29 | } 30 | 31 | NODE_MODULE(trycatch, Init) 32 | -------------------------------------------------------------------------------- /test/cpp/typedarrays.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | #include <stdint.h> 12 | 13 | using namespace Nan; // NOLINT(build/namespaces) 14 | 15 | NAN_METHOD(ReadU8) { 16 | TypedArrayContents<uint8_t> data(info[0]); 17 | 18 | v8::Local<v8::Array> result = New<v8::Array>(data.length()); 19 | for (size_t i=0; i < data.length(); i++) { 20 | Set(result, i, New<v8::Number>((*data)[i])); 21 | } 22 | 23 | info.GetReturnValue().Set(result); 24 | } 25 | 26 | NAN_METHOD(ReadI32) { 27 | TypedArrayContents<int32_t> data(info[0]); 28 | 29 | v8::Local<v8::Array> result = New<v8::Array>(data.length()); 30 | for (size_t i=0; i < data.length(); i++) { 31 | Set(result, i, New<v8::Number>((*data)[i])); 32 | } 33 | 34 | info.GetReturnValue().Set(result); 35 | } 36 | 37 | NAN_METHOD(ReadFloat) { 38 | TypedArrayContents<float> data(info[0]); 39 | 40 | v8::Local<v8::Array> result = New<v8::Array>(data.length());\ 41 | for (size_t i=0; i < data.length(); i++) { 42 | Set(result, i, New<v8::Number>((*data)[i])); 43 | } 44 | 45 | info.GetReturnValue().Set(result); 46 | } 47 | 48 | NAN_METHOD(ReadDouble) { 49 | TypedArrayContents<double> data(info[0]); 50 | 51 | v8::Local<v8::Array> result = New<v8::Array>(data.length()); 52 | for (size_t i=0; i < data.length(); i++) { 53 | Set(result, i, New<v8::Number>((*data)[i])); 54 | } 55 | 56 | info.GetReturnValue().Set(result); 57 | } 58 | 59 | NAN_MODULE_INIT(Init) { 60 | NAN_EXPORT(target, ReadU8); 61 | NAN_EXPORT(target, ReadI32); 62 | NAN_EXPORT(target, ReadFloat); 63 | NAN_EXPORT(target, ReadDouble); 64 | } 65 | 66 | NODE_MODULE(typedarrays, Init) 67 | -------------------------------------------------------------------------------- /test/cpp/weak.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | static AsyncResource* async_resource; 14 | static Persistent<v8::Function> cb; 15 | 16 | void weakCallback( 17 | const WeakCallbackInfo<int> &data) { // NOLINT(runtime/references) 18 | HandleScope scope; 19 | int *parameter = data.GetParameter(); 20 | v8::Local<v8::Value> val = New(*parameter); 21 | async_resource->runInAsyncScope( 22 | GetCurrentContext()->Global(), New(cb), 1, &val); 23 | delete async_resource; 24 | delete parameter; 25 | } 26 | 27 | v8::Local<v8::String> wrap(v8::Local<v8::Function> func) { 28 | EscapableHandleScope scope; 29 | v8::Local<v8::String> lstring = New<v8::String>("result").ToLocalChecked(); 30 | int *parameter = new int(42); 31 | Persistent<v8::Function> persistent(func); 32 | persistent.SetWeak(parameter, weakCallback, WeakCallbackType::kParameter); 33 | assert(persistent.IsWeak()); 34 | return scope.Escape(lstring); 35 | } 36 | 37 | NAN_METHOD(Hustle) { 38 | async_resource = new AsyncResource("nan:test:weak"); 39 | cb.Reset(To<v8::Function>(info[1]).ToLocalChecked()); 40 | info.GetReturnValue().Set(wrap(To<v8::Function>(info[0]).ToLocalChecked())); 41 | } 42 | 43 | inline void WeakExternalCallback(const WeakCallbackInfo<void>&) {} 44 | 45 | NAN_METHOD(WeakExternal) { 46 | void* baton = &baton; // Actual value doesn't really matter. 47 | Persistent<v8::External> external(New<v8::External>(baton)); 48 | external.SetWeak(baton, WeakExternalCallback, WeakCallbackType::kParameter); 49 | } 50 | 51 | NAN_MODULE_INIT(Init) { 52 | Set(target 53 | , New<v8::String>("hustle").ToLocalChecked() 54 | , GetFunction(New<v8::FunctionTemplate>(Hustle)).ToLocalChecked() 55 | ); 56 | Set(target 57 | , New<v8::String>("weakExternal").ToLocalChecked() 58 | , GetFunction(New<v8::FunctionTemplate>(WeakExternal)).ToLocalChecked() 59 | ); 60 | } 61 | 62 | NODE_MODULE(weak, Init) 63 | -------------------------------------------------------------------------------- /test/cpp/weak2.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | #include <nan.h> 10 | 11 | using namespace Nan; // NOLINT(build/namespaces) 12 | 13 | static AsyncResource* async_resource; 14 | static Persistent<v8::Function> cb; 15 | void weakCallback( 16 | const WeakCallbackInfo<int> &data) { // NOLINT(runtime/references) 17 | HandleScope scope; 18 | int *parameter = static_cast<int*>(data.GetInternalField(0)); 19 | v8::Local<v8::Value> val = New(*parameter); 20 | async_resource->runInAsyncScope( 21 | GetCurrentContext()->Global(), New(cb), 1, &val); 22 | delete async_resource; 23 | delete parameter; 24 | } 25 | 26 | v8::Local<v8::String> wrap() { 27 | EscapableHandleScope scope; 28 | v8::Local<v8::String> lstring = New("result").ToLocalChecked(); 29 | v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); 30 | otpl->SetInternalFieldCount(1); 31 | v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); 32 | SetInternalFieldPointer(obj, 0, new int(42)); 33 | Persistent<v8::Object> persistent(obj); 34 | persistent.SetWeak( 35 | static_cast<int*>(0) 36 | , weakCallback 37 | , WeakCallbackType::kInternalFields); 38 | assert(persistent.IsWeak()); 39 | return scope.Escape(lstring); 40 | } 41 | 42 | NAN_METHOD(Hustle) { 43 | async_resource = new AsyncResource("nan:test:weak2"); 44 | cb.Reset(To<v8::Function>(info[0]).ToLocalChecked()); 45 | info.GetReturnValue().Set(wrap()); 46 | } 47 | 48 | NAN_MODULE_INIT(Init) { 49 | Set(target 50 | , New<v8::String>("hustle").ToLocalChecked() 51 | , GetFunction(New<v8::FunctionTemplate>(Hustle)).ToLocalChecked() 52 | ); 53 | } 54 | 55 | NODE_MODULE(weak2, Init) 56 | -------------------------------------------------------------------------------- /test/js/accessors-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'accessors' }); 12 | const nodeVersion = parseInt(process.versions.node.split('.')[0]); 13 | 14 | test('accessors', function (t) { 15 | var settergetter = bindings.create() 16 | var derived = Object.create(settergetter) 17 | if(nodeVersion > 22){ 18 | t.plan(9) 19 | t.equal(settergetter.prop1, 'this is property 1') 20 | t.ok(settergetter.prop2 === '') 21 | settergetter.prop2 = 'setting a value' 22 | t.equal(settergetter.prop2, 'setting a value') 23 | t.equal(settergetter.log(), 24 | 'New()\n' + 25 | 'Prop1:GETTER(this is property 1)\n' + 26 | 'Prop2:GETTER()\n' + 27 | 'Prop2:SETTER(setting a value)\n' + 28 | 'Prop2:GETTER(setting a value)\n' 29 | ) 30 | t.equal(derived.prop1, 'this is property 1') 31 | derived.prop2 = 'setting a new value' 32 | t.equal(derived.prop2, 'setting a new value') 33 | t.equal(settergetter.prop2, 'setting a value') 34 | settergetter.prop2 = 'setting another value' 35 | t.equal(settergetter.prop2, 'setting another value') 36 | t.equal(derived.prop2, 'setting a new value') 37 | 38 | } 39 | else{ 40 | t.plan(7) 41 | t.equal(settergetter.prop1, 'this is property 1') 42 | t.ok(settergetter.prop2 === '') 43 | settergetter.prop2 = 'setting a value' 44 | t.equal(settergetter.prop2, 'setting a value') 45 | t.equal(settergetter.log(), 46 | 'New()\n' + 47 | 'Prop1:GETTER(this is property 1)\n' + 48 | 'Prop2:GETTER()\n' + 49 | 'Prop2:SETTER(setting a value)\n' + 50 | 'Prop2:GETTER(setting a value)\n' 51 | ) 52 | t.equal(derived.prop1, 'this is property 1') 53 | derived.prop2 = 'setting a new value' 54 | t.equal(derived.prop2, 'setting a new value') 55 | t.equal(settergetter.prop2, 'setting a new value') 56 | 57 | } 58 | }) 59 | -------------------------------------------------------------------------------- /test/js/accessors2-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'accessors2' }); 12 | 13 | test('accessors2', function (t) { 14 | t.plan(4) 15 | var settergetter = bindings.create() 16 | t.equal(settergetter.prop1, 'this is property 1') 17 | t.ok(settergetter.prop2 === '') 18 | settergetter.prop2 = 'setting a value' 19 | t.equal(settergetter.prop2, 'setting a value') 20 | t.equal(settergetter.log(), 21 | 'New()\n' + 22 | 'Prop1:GETTER(this is property 1)\n' + 23 | 'Prop2:GETTER()\n' + 24 | 'Prop2:SETTER(setting a value)\n' + 25 | 'Prop2:GETTER(setting a value)\n' 26 | ) 27 | }) 28 | -------------------------------------------------------------------------------- /test/js/asyncprogressqueueworker-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'asyncprogressqueueworker' }); 12 | 13 | test('asyncprogressqueueworker', function (t) { 14 | // test with no sleep 15 | var worker = bindings.doProgress 16 | , progressed = 0 17 | worker(5, function(i) { 18 | t.ok(i === progressed, 'got the progress updates #' + i); 19 | progressed++; 20 | }, function () { 21 | t.ok(progressed === 5, 'got all progress updates') 22 | t.end() 23 | }) 24 | }) 25 | -------------------------------------------------------------------------------- /test/js/asyncprogressqueueworkerstream-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'asyncprogressqueueworkerstream' }) 12 | , util = require('util'); 13 | 14 | const nodeVersion = process.versions.node.split('.') 15 | var Readable 16 | if (nodeVersion[0] == 0 && nodeVersion[1] <= 8) 17 | Readable = require('readable-stream') 18 | else 19 | Readable = require('stream').Readable 20 | 21 | function StreamProgressWorker(t) { 22 | Readable.call(this, {objectMode: true}) 23 | var self = this 24 | // initialize stream from cpp on next tick 25 | process.nextTick(function () { 26 | var worker = bindings.doProgress 27 | worker(5, function(i) { 28 | self.push(i) 29 | }, function () { 30 | self.push(null) 31 | }) 32 | }) 33 | } 34 | util.inherits(StreamProgressWorker, Readable) 35 | 36 | StreamProgressWorker.prototype._read = function (data) { 37 | 38 | }; 39 | 40 | 41 | test('asyncprogressqueueworker', function (t) { 42 | var stream = new StreamProgressWorker(t) 43 | var progressed = 0; 44 | 45 | stream 46 | .on('end', function() { 47 | t.ok(progressed === 5, 'cpp should have sent 5 objects') 48 | t.end() 49 | }) 50 | .on('data', function(data) { 51 | progressed++ 52 | console.log(data); 53 | }) 54 | }) 55 | -------------------------------------------------------------------------------- /test/js/asyncprogressworker-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'asyncprogressworker' }); 12 | 13 | test('asyncprogressworker', function (t) { 14 | // test with 100 ms sleep 15 | var worker = bindings.a 16 | , progressed = 0 17 | worker(100, 5, function(i) { 18 | t.ok(i === progressed, 'got the progress updates #' + i); 19 | progressed++; 20 | }, function () { 21 | t.ok(progressed === 5, 'got all progress updates') 22 | t.end() 23 | }) 24 | }) 25 | -------------------------------------------------------------------------------- /test/js/asyncprogressworkersignal-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'asyncprogressworkersignal' }); 12 | 13 | test('asyncprogressworkersignal', function (t) { 14 | var worker = bindings.a 15 | , progressed = 0 16 | worker(100, 5, function(i) { 17 | t.ok(i === true, 'data being left at NULL'); 18 | progressed++; 19 | }, function () { 20 | t.ok(progressed === 5, 'got all progress updates') 21 | t.end() 22 | }) 23 | }) 24 | -------------------------------------------------------------------------------- /test/js/asyncprogressworkerstream-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'asyncprogressworkerstream' }) 12 | , util = require('util'); 13 | 14 | const nodeVersion = process.versions.node.split('.') 15 | var Readable 16 | if (nodeVersion[0] == 0 && nodeVersion[1] <= 8) 17 | Readable = require('readable-stream') 18 | else 19 | Readable = require('stream').Readable 20 | 21 | function StreamProgressWorker(t) { 22 | Readable.call(this, {objectMode: true}) 23 | var self = this 24 | // initialize stream from cpp on next tick 25 | process.nextTick(function () { 26 | var worker = bindings.a 27 | worker(100, 5, function(i) { 28 | self.push(i) 29 | }, function () { 30 | self.push(null) 31 | }) 32 | }) 33 | } 34 | util.inherits(StreamProgressWorker, Readable) 35 | 36 | StreamProgressWorker.prototype._read = function (data) { 37 | 38 | }; 39 | 40 | 41 | test('asyncprogressworker', function (t) { 42 | var stream = new StreamProgressWorker(t) 43 | var progressed = 0; 44 | 45 | stream 46 | .on('end', function() { 47 | t.ok(progressed === 5, 'cpp should have sent 5 objects') 48 | t.end() 49 | }) 50 | .on('data', function(data) { 51 | progressed++ 52 | console.log(data); 53 | }) 54 | }) 55 | -------------------------------------------------------------------------------- /test/js/asyncresource-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const version = process.versions.node.split('.'); 10 | if (version[0] < 9) { 11 | process.exit(0); 12 | } 13 | 14 | try { 15 | require('async_hooks'); 16 | } catch (e) { 17 | process.exit(0); 18 | } 19 | 20 | const test = require('tap').test 21 | , testRoot = require('path').resolve(__dirname, '..') 22 | , delay = require('bindings')({ module_root: testRoot, bindings: 'asyncresource' }).delay 23 | , asyncHooks = require('async_hooks'); 24 | 25 | test('asyncresource', function (t) { 26 | t.plan(7); 27 | 28 | var resourceAsyncId; 29 | var originalExecutionAsyncId; 30 | var beforeCalled = false; 31 | var afterCalled = false; 32 | var destroyCalled = false; 33 | 34 | var hooks = asyncHooks.createHook({ 35 | init: function(asyncId, type, triggerAsyncId, resource) { 36 | if (type === 'nan:test.DelayRequest') { 37 | resourceAsyncId = asyncId; 38 | } 39 | }, 40 | before: function(asyncId) { 41 | if (asyncId === resourceAsyncId) { 42 | beforeCalled = true; 43 | } 44 | }, 45 | after: function(asyncId) { 46 | if (asyncId === resourceAsyncId) { 47 | afterCalled = true; 48 | } 49 | }, 50 | destroy: function(asyncId) { 51 | if (asyncId === resourceAsyncId) { 52 | destroyCalled = true; 53 | } 54 | } 55 | 56 | }); 57 | hooks.enable(); 58 | 59 | originalExecutionAsyncId = asyncHooks.executionAsyncId(); 60 | delay(1000, function() { 61 | t.equal(asyncHooks.executionAsyncId(), resourceAsyncId, 62 | 'callback should have the correct execution context'); 63 | t.equal(asyncHooks.triggerAsyncId(), originalExecutionAsyncId, 64 | 'callback should have the correct trigger context'); 65 | t.ok(beforeCalled, 'before should have been called'); 66 | t.notOk(afterCalled, 'after should not have been called yet'); 67 | setTimeout(function() { 68 | t.ok(afterCalled, 'after should have been called'); 69 | t.ok(destroyCalled, 'destroy should have been called'); 70 | t.equal(asyncHooks.triggerAsyncId(), resourceAsyncId, 71 | 'setTimeout should have been triggered by the async resource'); 72 | hooks.disable(); 73 | }, 1); 74 | }); 75 | }); 76 | -------------------------------------------------------------------------------- /test/js/asyncworker-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const version = process.versions.node.split('.'); 10 | const test = require('tap').test 11 | , testRoot = require('path').resolve(__dirname, '..') 12 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'asyncworker' }); 13 | 14 | test('asyncworker', function (t) { 15 | var worker = bindings.a 16 | , ticks = 0 17 | , called = false 18 | t.type(worker, 'function') 19 | function tick () { 20 | ticks++ 21 | if (!called) 22 | setTimeout(tick, 0) 23 | } 24 | setTimeout(tick, 0) 25 | worker(200, function () { 26 | called = true 27 | t.ok(ticks > 6, 'got plenty of ticks! (' + ticks + ')') 28 | t.end() 29 | }) 30 | }); 31 | 32 | test('asyncworker context', function (t) { 33 | var asyncHooks; 34 | if (version[0] < 9) { 35 | t.ok(true); 36 | t.end(); 37 | return; 38 | } 39 | 40 | try { 41 | asyncHooks = require('async_hooks'); 42 | } catch (e) { 43 | t.ok(true); 44 | t.end(); 45 | return; 46 | } 47 | 48 | t.plan(7); 49 | 50 | var sleep = bindings.a; 51 | var resourceAsyncId; 52 | var originalExecutionAsyncId; 53 | var beforeCalled = false; 54 | var afterCalled = false; 55 | var destroyCalled = false; 56 | 57 | var hooks = asyncHooks.createHook({ 58 | init: function(asyncId, type, triggerAsyncId, resource) { 59 | if (type === 'nan:test.SleepWorker') { 60 | resourceAsyncId = asyncId; 61 | } 62 | }, 63 | before: function(asyncId) { 64 | if (asyncId === resourceAsyncId) { 65 | beforeCalled = true; 66 | } 67 | }, 68 | after: function(asyncId) { 69 | if (asyncId === resourceAsyncId) { 70 | afterCalled = true; 71 | } 72 | }, 73 | destroy: function(asyncId) { 74 | if (asyncId === resourceAsyncId) { 75 | destroyCalled = true; 76 | } 77 | } 78 | 79 | }); 80 | hooks.enable(); 81 | 82 | originalExecutionAsyncId = asyncHooks.executionAsyncId(); 83 | sleep(200, function() { 84 | t.equal(asyncHooks.executionAsyncId(), resourceAsyncId, 85 | 'callback should have the correct execution context'); 86 | t.equal(asyncHooks.triggerAsyncId(), originalExecutionAsyncId, 87 | 'callback should have the correct trigger context'); 88 | t.ok(beforeCalled, 'before should have been called'); 89 | t.notOk(afterCalled, 'after should not have been called yet'); 90 | setTimeout(function() { 91 | t.ok(afterCalled, 'after should have been called'); 92 | t.ok(destroyCalled, 'destroy should have been called'); 93 | t.equal(asyncHooks.triggerAsyncId(), resourceAsyncId, 94 | 'setTimeout should have been triggered by the async resource'); 95 | hooks.disable(); 96 | }, 1); 97 | }); 98 | }); 99 | 100 | -------------------------------------------------------------------------------- /test/js/asyncworkererror-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'asyncworkererror' }); 12 | 13 | test('asyncworkererror', function (t) { 14 | var worker = bindings.a 15 | t.type(worker, 'function') 16 | worker(function (err) { 17 | t.ok(err) 18 | t.equal(err.message, 'Error') 19 | t.end() 20 | }) 21 | }) 22 | -------------------------------------------------------------------------------- /test/js/buffer-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'buffer' }); 12 | 13 | test('buffer', function (t) { 14 | t.plan(8); 15 | t.type(bindings.new1, 'function'); 16 | t.type(bindings.new2, 'function'); 17 | t.type(bindings.new3, 'function'); 18 | t.type(bindings.copy, 'function'); 19 | t.equal(bindings.new1().toString(), 'abcdefghijklmnopqrstuvwxyz'); 20 | t.equal(bindings.new2().toString(), 'abcdefghijklmnopqrstuvwxyz'); 21 | t.equal(bindings.new3().toString(), 'abcdefghijklmnopqrstuvwxyz'); 22 | t.equal(bindings.copy().toString(), 'abcdefghijklmnopqrstuvwxyz'); 23 | }); 24 | -------------------------------------------------------------------------------- /test/js/bufferworkerpersistent-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'bufferworkerpersistent' }) 12 | , crypto = require('crypto'); 13 | 14 | test('bufferworkerpersistent', function (t) { 15 | var worker = bindings.a 16 | , called = 0 17 | , buf = crypto.randomBytes(256) 18 | , bufHex = buf.toString('hex') 19 | 20 | t.plan(7); 21 | 22 | t.type(worker, 'function') 23 | 24 | worker(200, buf, function (_buf) { 25 | t.ok(Buffer.isBuffer(_buf), 'is buffer arg') 26 | t.equal(_buf.toString('hex'), bufHex) 27 | }) 28 | 29 | buf = null // unref 30 | }) 31 | -------------------------------------------------------------------------------- /test/js/callbackcontext-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const bindingName = 'callbackcontext'; 10 | 11 | const version = process.versions.node.split('.'); 12 | if (version[0] < 9) { 13 | console.log('1..0 # Skipped: ' + bindingName); 14 | process.exit(0); 15 | } 16 | 17 | try { 18 | require('async_hooks'); 19 | } catch (e) { 20 | console.log('1..0 # Skipped: ' + bindingName); 21 | process.exit(0); 22 | } 23 | 24 | const test = require('tap').test 25 | , testRoot = require('path').resolve(__dirname, '..') 26 | , delay = require('bindings')({ module_root: testRoot, bindings: bindingName }).delay 27 | , asyncHooks = require('async_hooks'); 28 | 29 | test(bindingName, function (t) { 30 | t.plan(7); 31 | 32 | var resourceAsyncId; 33 | var originalExecutionAsyncId; 34 | var beforeCalled = false; 35 | var afterCalled = false; 36 | var destroyCalled = false; 37 | 38 | var hooks = asyncHooks.createHook({ 39 | init: function(asyncId, type, triggerAsyncId, resource) { 40 | if (type === 'nan:test.DelayRequest') { 41 | resourceAsyncId = asyncId; 42 | } 43 | }, 44 | before: function(asyncId) { 45 | if (asyncId === resourceAsyncId) { 46 | beforeCalled = true; 47 | } 48 | }, 49 | after: function(asyncId) { 50 | if (asyncId === resourceAsyncId) { 51 | afterCalled = true; 52 | } 53 | }, 54 | destroy: function(asyncId) { 55 | if (asyncId === resourceAsyncId) { 56 | destroyCalled = true; 57 | } 58 | } 59 | 60 | }); 61 | hooks.enable(); 62 | 63 | originalExecutionAsyncId = asyncHooks.executionAsyncId(); 64 | delay(1000, function() { 65 | t.equal(asyncHooks.executionAsyncId(), resourceAsyncId, 66 | 'callback should have the correct execution context'); 67 | t.equal(asyncHooks.triggerAsyncId(), originalExecutionAsyncId, 68 | 'callback should have the correct trigger context'); 69 | t.ok(beforeCalled, 'before should have been called'); 70 | t.notOk(afterCalled, 'after should not have been called yet'); 71 | setTimeout(function() { 72 | t.ok(afterCalled, 'after should have been called'); 73 | t.ok(destroyCalled, 'destroy should have been called'); 74 | t.equal(asyncHooks.triggerAsyncId(), resourceAsyncId, 75 | 'setTimeout should have been triggered by the async resource'); 76 | hooks.disable(); 77 | }, 1); 78 | }); 79 | }); 80 | -------------------------------------------------------------------------------- /test/js/converters-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'converters' }); 12 | 13 | test('converters', function (t) { 14 | t.plan(32); 15 | 16 | var converters = bindings; 17 | t.type(converters.toBoolean, 'function'); 18 | t.type(converters.toNumber, 'function'); 19 | t.type(converters.toString, 'function'); 20 | t.type(converters.toDetailString, 'function'); 21 | t.type(converters.toFunction, 'function'); 22 | t.type(converters.toObject, 'function'); 23 | t.type(converters.toInteger, 'function'); 24 | t.type(converters.toUint32, 'function'); 25 | t.type(converters.toInt32, 'function'); 26 | t.type(converters.toArrayIndex, 'function'); 27 | t.type(converters.booleanValue, 'function'); 28 | t.type(converters.numberValue, 'function'); 29 | t.type(converters.integerValue, 'function'); 30 | t.type(converters.uint32Value, 'function'); 31 | t.type(converters.int32Value, 'function'); 32 | t.equal(converters.toBoolean(true), true); 33 | t.equal(converters.toNumber(15.3), 15.3); 34 | t.equal(converters.toString('sol'), 'sol'); 35 | t.equal(converters.toDetailString('sol'), 'sol'); 36 | t.equal(converters.toFunction(test), test); 37 | t.strictDeepEqual(converters.toObject({prop : 'x'}), {prop : 'x'}); 38 | t.equal(converters.toInteger(12), 12); 39 | t.equal(converters.toUint32(12), 12); 40 | t.equal(converters.toInt32(-12), -12); 41 | t.equal(converters.toArrayIndex('12'), 12); 42 | t.equal(converters.booleanValue(true), true); 43 | t.equal(converters.numberValue(15.3), 15.3); 44 | t.equal(converters.integerValue(12), 12); 45 | t.equal(converters.uint32Value(12), 12); 46 | t.equal(converters.int32Value(-12), -12); 47 | 48 | var conversionFailed = {}; 49 | t.equal(converters.toFunction(null, conversionFailed), conversionFailed); 50 | t.equal(converters.toFunction({}, conversionFailed), conversionFailed); 51 | }); 52 | -------------------------------------------------------------------------------- /test/js/error-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'error' }); 12 | 13 | const errors = ['Error', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError']; 14 | 15 | test('error', function (t) { 16 | t.plan(4 * errors.length * 3); 17 | errors.forEach(function (val) { 18 | var i; 19 | for (i = 1; i <= 4; i++) { 20 | t.type(bindings['Throw' + val + i], 'function'); 21 | try { 22 | bindings['Throw' + val + i](); 23 | } catch (err) { 24 | t.type(err, val); 25 | t.equal(err.message, 'errmsg'); 26 | } 27 | } 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /test/js/gc-fn.js: -------------------------------------------------------------------------------- 1 | if (global.gc) { 2 | module.exports = global.gc; 3 | return; 4 | } 5 | 6 | var v8 = require('v8'); 7 | var vm = require('vm'); 8 | 9 | v8.setFlagsFromString('--expose_gc'); 10 | module.exports = vm.runInNewContext('gc'); 11 | -------------------------------------------------------------------------------- /test/js/gc-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'gc' }) 12 | , gc = require('./gc-fn'); 13 | 14 | test('gc', function (t) { 15 | t.plan(3); 16 | 17 | t.type(bindings.hook, 'function'); 18 | t.type(bindings.check, 'function'); 19 | 20 | bindings.hook(); 21 | gc(); 22 | t.ok(bindings.check()); 23 | }); 24 | -------------------------------------------------------------------------------- /test/js/indexedinterceptors-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'indexedinterceptors' }); 12 | 13 | test('indexedinterceptors', function (t) { 14 | t.plan(5); 15 | var interceptor = bindings.create(); 16 | t.equal(interceptor[2], 'bar'); 17 | interceptor[0] = 'setting a value'; 18 | t.equal(interceptor[0], 'setting a value'); 19 | delete interceptor[0]; 20 | t.equal(interceptor[0], 'goober'); 21 | t.ok(Object.prototype.hasOwnProperty.call(interceptor, 1)); 22 | t.equal(Object.keys(interceptor)[0], '42'); 23 | }); 24 | -------------------------------------------------------------------------------- /test/js/isolatedata-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'isolatedata' }); 12 | 13 | test('isolatedata', function (t) { 14 | t.plan(2); 15 | 16 | var isolatedata = bindings; 17 | t.type(isolatedata.setAndGet, 'function'); 18 | t.ok(isolatedata.setAndGet); 19 | }); 20 | -------------------------------------------------------------------------------- /test/js/json-parse-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'parse' }); 12 | 13 | test('parse', function (t) { 14 | t.plan(8); 15 | t.type(bindings.parse, 'function'); 16 | t.deepEqual( 17 | bindings.parse('{ "a": "JSON", "string": "value" }'), 18 | JSON.parse('{ "a": "JSON", "string": "value" }') 19 | ); 20 | t.deepEqual( 21 | bindings.parse('[ 1, 2, 3 ]'), 22 | JSON.parse('[ 1, 2, 3 ]') 23 | ); 24 | t.equal( 25 | bindings.parse('57'), 26 | JSON.parse('57') 27 | ); 28 | t.equal( 29 | bindings.parse('3.14159'), 30 | JSON.parse('3.14159') 31 | ); 32 | t.equal( 33 | bindings.parse('true'), 34 | JSON.parse('true') 35 | ); 36 | t.equal( 37 | bindings.parse('false'), 38 | JSON.parse('false') 39 | ); 40 | t.equal( 41 | bindings.parse('"some string"'), 42 | JSON.parse('"some string"') 43 | ); 44 | }); 45 | -------------------------------------------------------------------------------- /test/js/json-stringify-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'stringify' }); 12 | 13 | test('stringify', function (t) { 14 | t.plan(22); 15 | t.type(bindings.stringify, 'function'); 16 | t.equal( 17 | bindings.stringify({ "a": "JSON", "object": "value" }), 18 | JSON.stringify({ "a": "JSON", "object": "value" }) 19 | ); 20 | t.equal( 21 | bindings.stringify({ "a": "JSON", "object": "value" }, null, 2), 22 | JSON.stringify({ "a": "JSON", "object": "value" }, null, 2) 23 | ); 24 | t.equal( 25 | bindings.stringify({ "a": "JSON", "object": "value" }, null, '++'), 26 | JSON.stringify({ "a": "JSON", "object": "value" }, null, '++') 27 | ); 28 | t.equal( 29 | bindings.stringify([ 1, 2, 3 ]), 30 | JSON.stringify([ 1, 2, 3 ]) 31 | ); 32 | t.equal( 33 | bindings.stringify([ 1, 2, 3 ], null, 2), 34 | JSON.stringify([ 1, 2, 3 ], null, 2) 35 | ); 36 | t.equal( 37 | bindings.stringify([ 1, 2, 3 ], null, '++'), 38 | JSON.stringify([ 1, 2, 3 ], null, '++') 39 | ); 40 | t.equal( 41 | bindings.stringify("a string"), 42 | JSON.stringify("a string") 43 | ); 44 | t.equal( 45 | bindings.stringify("a string", null, 2), 46 | JSON.stringify("a string", null, 2) 47 | ); 48 | t.equal( 49 | bindings.stringify("a string", null, '++'), 50 | JSON.stringify("a string", null, '++') 51 | ); 52 | t.equal( 53 | bindings.stringify(3.14159), 54 | JSON.stringify(3.14159) 55 | ); 56 | t.equal( 57 | bindings.stringify(3.14159, null, 2), 58 | JSON.stringify(3.14159, null, 2) 59 | ); 60 | t.equal( 61 | bindings.stringify(3.14159, null, '++'), 62 | JSON.stringify(3.14159, null, '++') 63 | ); 64 | t.equal( 65 | bindings.stringify(-31), 66 | JSON.stringify(-31) 67 | ); 68 | t.equal( 69 | bindings.stringify(-31, null, 2), 70 | JSON.stringify(-31, null, 2) 71 | ); 72 | t.equal( 73 | bindings.stringify(-31, null, '++'), 74 | JSON.stringify(-31, null, '++') 75 | ); 76 | t.equal( 77 | bindings.stringify(true), 78 | JSON.stringify(true) 79 | ); 80 | t.equal( 81 | bindings.stringify(true, null, 2), 82 | JSON.stringify(true, null, 2) 83 | ); 84 | t.equal( 85 | bindings.stringify(true, null, '++'), 86 | JSON.stringify(true, null, '++') 87 | ); 88 | t.equal( 89 | bindings.stringify(false), 90 | JSON.stringify(false) 91 | ); 92 | t.equal( 93 | bindings.stringify(false, null, 2), 94 | JSON.stringify(false, null, 2) 95 | ); 96 | t.equal( 97 | bindings.stringify(false, null, '++'), 98 | JSON.stringify(false, null, '++') 99 | ); 100 | }); 101 | -------------------------------------------------------------------------------- /test/js/makecallback-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , MyObject = require('bindings')({ module_root: testRoot, bindings: 'makecallback' }).MyObject 12 | , EventEmitter = require('events').EventEmitter; 13 | 14 | // extend prototype 15 | function inherits(target, source) { 16 | for (var k in source.prototype) { 17 | target.prototype[k] = source.prototype[k]; 18 | } 19 | } 20 | 21 | inherits(MyObject, EventEmitter); 22 | 23 | test('makecallback', function (t) { 24 | t.plan(1); 25 | 26 | var obj = new MyObject(); 27 | obj.on('event', function() { 28 | t.ok(true); 29 | }); 30 | 31 | obj.call_emit(); 32 | }); 33 | -------------------------------------------------------------------------------- /test/js/maybe-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2019 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'maybe' }) 12 | 13 | test('maybe', function (t) { 14 | t.plan(1); 15 | t.ok(bindings.test()); 16 | }); 17 | -------------------------------------------------------------------------------- /test/js/methodswithdata-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2019 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'methodswithdata' }) 12 | const nodeVersion = parseInt(process.versions.node.split('.')[0]); 13 | 14 | test('SetMethod with data', function (t) { 15 | t.plan(1); 16 | t.ok(bindings.testWithData()); 17 | }); 18 | 19 | test('accessors with data', function (t) { 20 | var settergetter = bindings.create() 21 | var derived = Object.create(settergetter) 22 | if (nodeVersion > 22) { 23 | t.plan(9) 24 | t.equal(settergetter.prop1, 'this is property 1') 25 | t.ok(settergetter.prop2 === '') 26 | settergetter.prop2 = 'setting a value' 27 | t.equal(settergetter.prop2, 'setting a value') 28 | t.equal(settergetter.log(), 29 | 'New()\n' + 30 | 'Prop1:GETTER(this is property 1)\n' + 31 | 'Prop2:GETTER()\n' + 32 | 'Prop2:SETTER(setting a value)\n' + 33 | 'Prop2:GETTER(setting a value)\n' 34 | ) 35 | t.equal(derived.prop1, 'this is property 1') 36 | derived.prop2 = 'setting a new value' 37 | t.equal(derived.prop2, 'setting a new value') 38 | t.equal(settergetter.prop2, 'setting a value') 39 | settergetter.prop2 = 'setting another value' 40 | t.equal(settergetter.prop2, 'setting another value') 41 | t.equal(derived.prop2, 'setting a new value') 42 | } else { 43 | t.plan(7) 44 | t.equal(settergetter.prop1, 'this is property 1') 45 | t.ok(settergetter.prop2 === '') 46 | settergetter.prop2 = 'setting a value' 47 | t.equal(settergetter.prop2, 'setting a value') 48 | t.equal(settergetter.log(), 49 | 'New()\n' + 50 | 'Prop1:GETTER(this is property 1)\n' + 51 | 'Prop2:GETTER()\n' + 52 | 'Prop2:SETTER(setting a value)\n' + 53 | 'Prop2:GETTER(setting a value)\n' 54 | ) 55 | t.equal(derived.prop1, 'this is property 1') 56 | derived.prop2 = 'setting a new value' 57 | t.equal(derived.prop2, 'setting a new value') 58 | t.equal(settergetter.prop2, 'setting a new value') 59 | 60 | } 61 | }) 62 | -------------------------------------------------------------------------------- /test/js/morenews-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'morenews' }); 12 | 13 | test('morenews', function (t) { 14 | t.plan(16); 15 | t.type(bindings.newNumber, 'function'); 16 | t.type(bindings.newPositiveInteger, 'function'); 17 | t.type(bindings.newNegativeInteger, 'function'); 18 | t.type(bindings.newUtf8String, 'function'); 19 | t.type(bindings.newLatin1String, 'function'); 20 | t.type(bindings.newUcs2String, 'function'); 21 | t.type(bindings.newExternalStringResource, 'function'); 22 | t.type(bindings.newExternalAsciiStringResource, 'function'); 23 | 24 | t.equal(bindings.newNumber(), 0.5); 25 | t.equal(bindings.newPositiveInteger(), 1); 26 | t.equal(bindings.newNegativeInteger(), -1); 27 | t.equal(bindings.newUtf8String(), 'strïng'); 28 | t.equal(bindings.newLatin1String(), 'strïng'); 29 | t.equal(bindings.newUcs2String(), 'strïng'); 30 | t.equals(bindings.newExternalStringResource(), 'strïng'); 31 | t.equals(bindings.newExternalAsciiStringResource(), 'string'); 32 | }); 33 | -------------------------------------------------------------------------------- /test/js/multifile-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'multifile' }); 12 | 13 | // same as fromv8string test but split over multiple compile units 14 | // just to test that there aren't any conflicts from including nan.h 15 | // more than once in project files 16 | test('multifile', function (t) { 17 | t.plan(2); 18 | 19 | var r = bindings.r 20 | t.type(r, 'function'); 21 | t.equal(r('a string value'), 'a string value'); 22 | }); 23 | -------------------------------------------------------------------------------- /test/js/namedinterceptors-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'namedinterceptors' }); 12 | 13 | test('namedinterceptors', function (t) { 14 | t.plan(5); 15 | var interceptor = bindings.create(); 16 | t.equal(interceptor.prop, 'foo'); 17 | interceptor.prop = 'setting a value'; 18 | t.equal(interceptor.prop, 'setting a value'); 19 | delete interceptor.something; 20 | t.equal(interceptor.prop, 'goober'); 21 | t.ok(Object.prototype.hasOwnProperty.call(interceptor, "thing")); 22 | t.ok(Object.keys(interceptor)[0] === 'value'); 23 | }); 24 | -------------------------------------------------------------------------------- /test/js/nancallback-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'nancallback' }) 12 | , round = Math.round; 13 | 14 | test('nancallback', function (t) { 15 | t.plan(19) 16 | 17 | var persistent = bindings; 18 | t.type(persistent.globalContext, 'function'); 19 | t.type(persistent.specificContext, 'function'); 20 | t.type(persistent.customReceiver, 'function'); 21 | t.type(persistent.compareCallbacks, 'function'); 22 | t.type(persistent.callDirect, 'function'); 23 | t.type(persistent.callAsFunction, 'function'); 24 | t.type(persistent.resetUnset, 'function'); 25 | t.type(persistent.resetSet, 'function'); 26 | t.type(persistent.callRetval, 'function'); 27 | persistent.globalContext(function () { t.ok(true); }); 28 | persistent.specificContext(function () { t.ok(true); }); 29 | persistent.customReceiver(function () { t.equal(this, process); }, process); 30 | persistent.callDirect(function () { t.ok(true); }); 31 | persistent.callAsFunction(function () { t.ok(true); }); 32 | t.ok(persistent.resetUnset()); 33 | t.ok(persistent.resetSet(function () {})); 34 | t.ok(persistent.callRetval(function () { return 1; })); 35 | 36 | var round2 = Math.round 37 | , x = function(param) { return param + 1; } 38 | , y = function(param) { return param + 2; } 39 | , x2 = x; 40 | t.ok(persistent.compareCallbacks(round, round2, Math.floor)); 41 | t.ok(persistent.compareCallbacks(x, x2, y)); 42 | }) 43 | -------------------------------------------------------------------------------- /test/js/nannew-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'nannew' }); 12 | 13 | 14 | // register c++ functions as tests... 15 | for (var symbol in bindings) { 16 | if (typeof bindings[symbol] == 'function' && symbol.match(/^test.*/)) { 17 | test('C++: ' + symbol, bindings[symbol]); 18 | } 19 | } 20 | 21 | test('numbers', function (t) { 22 | t.plan(12); 23 | 24 | t.type(bindings.newIntegerWithValue, 'function'); 25 | t.equals(bindings.newIntegerWithValue(23), 23); 26 | t.equals(bindings.newIntegerWithValue(5), 5); 27 | t.type(bindings.newIntegerWithValue(23), 'number'); 28 | 29 | t.type(bindings.newNumberWithValue, 'function'); 30 | t.equals(bindings.newNumberWithValue(Math.PI), Math.PI); 31 | t.equals(bindings.newNumberWithValue(Math.E), Math.E); 32 | t.type(bindings.newNumberWithValue(Math.PI), 'number'); 33 | 34 | t.type(bindings.newUint32WithValue, 'function'); 35 | t.equals(bindings.newUint32WithValue(23), 23); 36 | t.equals(bindings.newUint32WithValue(5), 5); 37 | t.type(bindings.newUint32WithValue(5), 'number'); 38 | t.end(); 39 | }); 40 | 41 | 42 | test('strings', function (t) { 43 | t.plan(3); 44 | 45 | t.equals(bindings.newStringFromChars(), "hello?"); 46 | t.equals(bindings.newStringFromCharsWithLength(), "hell"); 47 | t.equals(bindings.newStringFromStdString(), "hello!"); 48 | 49 | t.end(); 50 | }); 51 | 52 | test('test MakeMaybe(...)', function (t) { 53 | t.plan(1); 54 | t.ok(bindings.invokeMakeMaybe() - Math.PI < 10e-8); 55 | t.end(); 56 | }); 57 | -------------------------------------------------------------------------------- /test/js/news-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'news' }); 12 | 13 | test('news', function (t) { 14 | t.plan(52); 15 | t.type(bindings.newNumber, 'function'); 16 | t.type(bindings.newPositiveInteger, 'function'); 17 | t.type(bindings.newNegativeInteger, 'function'); 18 | t.type(bindings.newUnsignedInteger, 'function'); 19 | t.type(bindings.newInt32FromPositive, 'function'); 20 | t.type(bindings.newInt32FromNegative, 'function'); 21 | t.type(bindings.newUint32FromPositive, 'function'); 22 | t.type(bindings.newUint32FromNegative, 'function'); 23 | t.type(bindings.newUtf8String, 'function'); 24 | t.type(bindings.newLatin1String, 'function'); 25 | t.type(bindings.newUcs2String, 'function'); 26 | t.type(bindings.newStdString, 'function'); 27 | t.type(bindings.newRegExp, 'function'); 28 | t.type(bindings.newStringObject, 'function'); 29 | t.type(bindings.newNumberObject, 'function'); 30 | t.type(bindings.newBooleanObject, 'function'); 31 | t.type(bindings.newExternal, 'function'); 32 | t.type(bindings.newSignature, 'function'); 33 | t.type(bindings.newScript, 'function'); 34 | t.type(bindings.newScript2, 'function'); 35 | t.type(bindings.compileScript, 'function'); 36 | t.type(bindings.compileScript2, 'function'); 37 | t.type(bindings.newDate, 'function'); 38 | t.type(bindings.newArray, 'function'); 39 | t.type(bindings.newBoolean, 'function'); 40 | t.type(bindings.newBoolean2, 'function'); 41 | 42 | t.equal(bindings.newNumber(), 0.5); 43 | t.equal(bindings.newPositiveInteger(), 1); 44 | t.equal(bindings.newNegativeInteger(), -1); 45 | t.equal(bindings.newUnsignedInteger(), 0xFFFFFFFF); 46 | t.equal(bindings.newInt32FromPositive(), -1); 47 | t.equal(bindings.newInt32FromNegative(), -1); 48 | t.equal(bindings.newUint32FromPositive(), 0xFFFFFFFF); 49 | t.equal(bindings.newUint32FromNegative(), 0xFFFFFFFF); 50 | t.equal(bindings.newUtf8String(), 'strïng'); 51 | t.equal(bindings.newLatin1String(), 'strïng'); 52 | t.equal(bindings.newUcs2String(), 'strïng'); 53 | t.equal(bindings.newStdString(), 'strïng'); 54 | t.equal(bindings.newRegExp().toString(), '/foo/'); 55 | t.deepEquals(bindings.newStringObject(), new String("foo")); 56 | t.deepEquals(bindings.newNumberObject(), new Number(0.5)); 57 | t.deepEquals(bindings.newBooleanObject(), new Boolean(true)); 58 | t.equals(bindings.newExternal(), 'passed'); 59 | t.equals(bindings.newSignature(), 'string'); 60 | t.equals(bindings.newScript(), 6); 61 | t.equals(bindings.newScript2(), 6); 62 | t.equals(bindings.compileScript(), 6); 63 | t.equals(bindings.compileScript2(), 6); 64 | t.deepEquals(bindings.newDate(), new Date(1337)); 65 | t.deepEquals(bindings.newArray(), []); 66 | t.equal(bindings.newBoolean(), true); 67 | t.equal(bindings.newBoolean2(), true); 68 | }); 69 | -------------------------------------------------------------------------------- /test/js/objectwraphandle-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'objectwraphandle' }); 12 | 13 | test('objectwraphandle', function (t) { 14 | t.plan(9); 15 | 16 | t.type(bindings.MyObject, 'function'); 17 | 18 | var obj = new bindings.MyObject(10); 19 | 20 | t.type(obj.getHandle, 'function'); 21 | t.type(obj.getHandleConst, 'function'); 22 | t.type(obj.getValue, 'function'); 23 | t.type(obj.getHandle(), 'object'); 24 | t.type(obj.getHandleConst(), 'object'); 25 | t.type(obj.getValue(), 'number'); 26 | 27 | var derived = Object.create(obj); 28 | t.type(derived, bindings.MyObject); 29 | try { 30 | // In Node 0.10 this call is valid: 31 | t.equal(derived.getValue(), 10); 32 | } catch (err) { 33 | // In Node >= 0.12 it throws instead: 34 | t.type(err, TypeError); 35 | } 36 | }); 37 | -------------------------------------------------------------------------------- /test/js/persistent-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'persistent' }); 12 | 13 | test('persistent', function (t) { 14 | t.plan(15); 15 | 16 | var persistent = bindings; 17 | t.type(persistent.save1, 'function'); 18 | t.type(persistent.get1, 'function'); 19 | t.type(persistent.dispose1, 'function'); 20 | t.type(persistent.toPersistentAndBackAgain, 'function'); 21 | t.type(persistent.persistentToPersistent, 'function'); 22 | t.type(persistent.copyablePersistent, 'function'); 23 | t.type(persistent.passGlobal, 'function'); 24 | 25 | t.deepEqual(persistent.toPersistentAndBackAgain({ x: 42 }), { x: 42 }); 26 | 27 | t.equal(persistent.persistentToPersistent('any string'), 'any string'); 28 | 29 | persistent.save1('a string to save'); 30 | t.equal(persistent.get1(), 'a string to save'); 31 | t.equal(persistent.copyablePersistent(), 'a string to save'); 32 | 33 | t.equal(persistent.passGlobal(), 42, 'pass global'); 34 | 35 | setTimeout(function () { 36 | t.equal(persistent.get1(), 'a string to save'); 37 | persistent.dispose1(); 38 | t.ok(persistent.get1() === undefined, 'no more persistent'); 39 | t.ok(persistent.copyablePersistent() === undefined, 'no more persistent'); 40 | }, 25); 41 | }); 42 | -------------------------------------------------------------------------------- /test/js/private-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'private' }); 12 | 13 | test('private', function (t) { 14 | t.plan(8); 15 | t.type(bindings.hasPrivateYes, 'function'); 16 | t.type(bindings.hasPrivateNo, 'function'); 17 | t.type(bindings.deletePrivateNo, 'function'); 18 | t.type(bindings.noConflict, 'function'); 19 | t.ok(bindings.hasPrivateYes()); 20 | t.ok(bindings.hasPrivateNo()); 21 | t.ok(bindings.deletePrivateNo()); 22 | t.ok(bindings.noConflict()); 23 | }); 24 | -------------------------------------------------------------------------------- /test/js/returnemptystring-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'returnemptystring' }); 12 | 13 | test('returnemptystring', function (t) { 14 | t.plan(3); 15 | t.type(bindings.r, 'function'); 16 | t.equal(bindings.r('a string value'), ''); 17 | t.equal(bindings.r(), ''); 18 | }); 19 | -------------------------------------------------------------------------------- /test/js/returnnull-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'returnnull' }); 12 | 13 | test('returnnull', function (t) { 14 | t.plan(3); 15 | t.type(bindings.r, 'function'); 16 | t.equal(bindings.r('a string value'), null); 17 | t.equal(bindings.r(), null); 18 | }); 19 | -------------------------------------------------------------------------------- /test/js/returnundefined-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'returnundefined' }); 12 | 13 | test('returnundefined', function (t) { 14 | t.plan(3); 15 | t.type(bindings.r, 'function'); 16 | t.equal(bindings.r('a string value'), undefined); 17 | t.equal(bindings.r(), undefined); 18 | }); 19 | -------------------------------------------------------------------------------- /test/js/returnvalue-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'returnvalue' }); 12 | 13 | test('returnvalue', function (t) { 14 | t.plan(9); 15 | t.type(bindings.r, 'function'); 16 | t.type(bindings.p, 'function'); 17 | t.type(bindings.q, 'function'); 18 | t.type(bindings.u, 'function'); 19 | t.equal(bindings.r('a string value'), 'a string value'); 20 | t.equal(bindings.r(), 'default'); 21 | t.ok(bindings.p()); 22 | t.ok(bindings.q()); 23 | t.equal(bindings.u(), 0x80000000); 24 | }); 25 | -------------------------------------------------------------------------------- /test/js/setcallhandler-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'setcallhandler' }); 12 | 13 | test('setcallhandler', function (t) { 14 | t.plan(4); 15 | t.type(bindings.a, 'function'); 16 | t.type(bindings.b, 'function'); 17 | t.equal(bindings.a()(), 12); 18 | t.equal(bindings.b()(), 15); 19 | }); 20 | -------------------------------------------------------------------------------- /test/js/settemplate-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'settemplate' }) 12 | 13 | test('SetPrototypeTemplate', function (t) { 14 | t.plan(4); 15 | var r = new bindings.MyObject(); 16 | t.type(r, 'object'); 17 | r = Object.getPrototypeOf(r); 18 | t.type(r, 'object'); 19 | t.type(r.prototypeProp, 'string'); 20 | t.equal(r.prototypeProp, 'a prototype property'); 21 | }); 22 | 23 | test('SetInstanceTemplate', function (t) { 24 | t.plan(3); 25 | var r = new bindings.MyObject(); 26 | t.type(r, 'object'); 27 | t.type(r.instanceProp, 'string'); 28 | t.equal(r.instanceProp, 'an instance property'); 29 | }); 30 | 31 | test('PropertyAttribute None', function (t) { 32 | t.plan(3); 33 | var r = new bindings.MyObject(); 34 | t.type(r, 'object'); 35 | t.type(r.none, 'string'); 36 | t.equal(r.none, 'none'); 37 | }); 38 | 39 | test('PropertyAttribute ReadOnly', function (t) { 40 | t.plan(4); 41 | var r = new bindings.MyObject(); 42 | t.type(r, 'object'); 43 | t.type(r.readOnly, 'string'); 44 | t.equal(r.readOnly, 'readOnly'); 45 | r.readOnly = 'changed'; 46 | t.equal(r.readOnly, 'readOnly'); 47 | }); 48 | 49 | test('PropertyAttribute DontEnum', function (t) { 50 | t.plan(4); 51 | var r = new bindings.MyObject(); 52 | t.type(r, 'object'); 53 | t.type(r.dontEnum, 'string'); 54 | t.equal(r.dontEnum, 'dontEnum'); 55 | t.notOk(r.propertyIsEnumerable('dontEnum'), 'is not enumerable'); 56 | }); 57 | 58 | test('PropertyAttribute DontDelete', function (t) { 59 | t.plan(4); 60 | var r = new bindings.MyObject(); 61 | t.type(r, 'object'); 62 | t.type(r.dontDelete, 'string'); 63 | t.equal(r.dontDelete, 'dontDelete'); 64 | delete r.dontDelete; 65 | t.equal(r.dontDelete, 'dontDelete'); 66 | }); 67 | -------------------------------------------------------------------------------- /test/js/strings-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'strings' }); 12 | 13 | 14 | test('FromV8String', function (t) { 15 | t.plan(6); 16 | 17 | var a = bindings.returnUtf8String; 18 | var b = bindings.heapString; 19 | 20 | t.type(a, 'function'); 21 | t.type(b, 'function'); 22 | 23 | t.equal(a('an utf8 strïng'), 'an utf8 strïng'); 24 | t.equal(b('an utf8 strïng'), 'an utf8 strïng'); 25 | 26 | var buf; 27 | 28 | /* we check Buffer.alloc rather than Buffer.from because 29 | * we don't want the base class Uint8Array.from */ 30 | if (typeof(Buffer.alloc) === "function") { 31 | buf = Buffer.from('hello'); 32 | } else { 33 | buf = new Buffer('hello'); 34 | } 35 | t.equal(bindings.encodeHex(), buf.toString('hex')); 36 | t.equal(bindings.encodeUCS2(), 'hello'); 37 | }); 38 | -------------------------------------------------------------------------------- /test/js/symbols-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'symbols' }); 12 | 13 | test('symbols', function (t) { 14 | t.plan(2); 15 | t.type(bindings.key, 'string'); 16 | t.equal(bindings.key, 'a property'); 17 | }); 18 | -------------------------------------------------------------------------------- /test/js/threadlocal-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'threadlocal' }); 12 | 13 | test('thread local storage', bindings.thread_local_storage); 14 | -------------------------------------------------------------------------------- /test/js/trycatch-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'trycatch' }); 12 | 13 | test('returnemptystring', function (t) { 14 | t.plan(2); 15 | t.type(bindings.r, 'function'); 16 | try { 17 | bindings.r(); 18 | } catch (err) { 19 | t.equal(err, 'waaa'); 20 | } 21 | }); 22 | -------------------------------------------------------------------------------- /test/js/typedarrays-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'typedarrays' }); 12 | 13 | test('typedarrays - simple cases', function (t) { 14 | if (typeof Uint8Array !== 'function') { 15 | 16 | t.pass('typedarrays not supported'); 17 | t.end(); 18 | 19 | } else { 20 | 21 | var zeros = new Uint8Array(5) 22 | t.same(bindings.ReadU8(zeros), [0,0,0,0,0]) 23 | 24 | var y = zeros[0] 25 | t.equals(y, 0) 26 | t.same(bindings.ReadU8(zeros), [0,0,0,0,0]) 27 | 28 | var u8array = new Uint8Array([1, 255, 3]); 29 | t.same(bindings.ReadU8(u8array), [1, 255, 3]); 30 | t.same(bindings.ReadU8(u8array.subarray(1)), [255, 3]); 31 | t.same(bindings.ReadU8(u8array.subarray(0, 2)), [1, 255]); 32 | t.same(bindings.ReadU8(u8array.subarray(1, 2)), [255]); 33 | 34 | t.same(bindings.ReadU8(new Uint8Array(u8array)), [1, 255, 3]); 35 | t.same(bindings.ReadU8(new Uint8Array(u8array.subarray(1))), [255, 3]); 36 | t.same(bindings.ReadU8(new Uint8Array(u8array.subarray(0, 2))), [1, 255]); 37 | t.same(bindings.ReadU8(new Uint8Array(u8array.subarray(1, 2))), [255]); 38 | 39 | t.same(bindings.ReadU8((new Uint8Array(u8array.buffer)).subarray(1)), [255, 3]); 40 | 41 | 42 | var i32array = new Int32Array([0, 1, -1, 1073741824, -1073741824]); 43 | t.same(bindings.ReadI32(i32array), [0, 1, -1, 1073741824, -1073741824]); 44 | 45 | var f32array = new Float32Array([1, -1, Infinity, -Infinity, 0, +0, -0]); 46 | t.same(bindings.ReadFloat(f32array), [1, -1, Infinity, -Infinity, 0, +0, -0]); 47 | t.same(bindings.ReadFloat(f32array.subarray(1)), [-1, Infinity, -Infinity, 0, +0, -0]); 48 | t.same(bindings.ReadFloat(f32array.subarray(0,4)), [1, -1, Infinity, -Infinity]); 49 | t.same(bindings.ReadFloat(f32array.subarray(1,3)), [-1, Infinity]); 50 | 51 | t.end(); 52 | } 53 | }); 54 | 55 | test('typedarrays - bad arguments', function (t) { 56 | if (typeof Uint8Array !== 'function') { 57 | 58 | t.pass('typedarrays not supported'); 59 | t.end(); 60 | 61 | } else { 62 | 63 | t.same(bindings.ReadU8(0), []); 64 | t.same(bindings.ReadU8(1), []); 65 | t.same(bindings.ReadU8(null), []); 66 | t.same(bindings.ReadU8(), []); 67 | t.same(bindings.ReadU8('foobar'), []); 68 | t.same(bindings.ReadU8([]), []); 69 | t.same(bindings.ReadU8([1,2]), []); 70 | t.same(bindings.ReadU8({}), []); 71 | t.same(bindings.ReadU8(Uint8Array), []); 72 | t.same(bindings.ReadU8(new Float32Array(0)), []); 73 | 74 | t.same(bindings.ReadU8({ 75 | byteLength: 10000000, 76 | byteOffset: 100000, 77 | buffer: null 78 | }), []) 79 | 80 | t.end(); 81 | } 82 | }); 83 | -------------------------------------------------------------------------------- /test/js/weak-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'weak' }) 12 | , gc = require('./gc-fn'); 13 | const nodeVersion = parseInt(process.versions.node.split('.')[0]); 14 | 15 | // https://github.com/nodejs/nan/issues/995 16 | // https://chromium-review.googlesource.com/c/v8/v8/+/4733273 17 | // Week tests are incompatible with recent V8 changes 18 | 19 | if(nodeVersion < 24){ 20 | test('weak', function (t) { 21 | t.plan(3); 22 | 23 | var weak = bindings, count = 0; 24 | t.type(weak.hustle, 'function'); 25 | 26 | weak.hustle(function () {}, function (val) { 27 | t.equal(val, 42); 28 | count++; 29 | }); 30 | 31 | var timeout = setTimeout(function () { 32 | // run weak callback, should dispose 33 | gc(); 34 | 35 | // do not run weak callback 36 | gc(); 37 | 38 | if (count > 0) { 39 | clearTimeout(timeout); 40 | t.equal(count, 1); 41 | } 42 | }, 100); 43 | }); 44 | 45 | test('weak external', function (t) { 46 | t.plan(2); 47 | 48 | var weak = bindings; 49 | t.type(weak.weakExternal, 'function'); 50 | 51 | weak.weakExternal(); 52 | t.ok(true); // All good if the previous line didn't crash. 53 | }); 54 | } 55 | 56 | -------------------------------------------------------------------------------- /test/js/weak2-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'weak2' }) 12 | , gc = require('./gc-fn'); 13 | const nodeVersion = parseInt(process.versions.node.split('.')[0]); 14 | 15 | // https://github.com/nodejs/nan/issues/995 16 | // https://chromium-review.googlesource.com/c/v8/v8/+/4733273 17 | // Week tests are incompatible with recent V8 changes 18 | 19 | if(nodeVersion < 24){ 20 | test('weak2', function (t) { 21 | t.plan(3); 22 | 23 | var weak2 = bindings, count = 0; 24 | t.type(weak2.hustle, 'function'); 25 | 26 | weak2.hustle(function (val) { 27 | t.equal(val, 42); 28 | count++; 29 | }); 30 | 31 | // run weak callback, should dispose 32 | gc(); 33 | 34 | // do not run weak callback 35 | gc(); 36 | 37 | var timeout = setTimeout(function () { 38 | if (count > 0) { 39 | clearTimeout(timeout); 40 | t.equal(count, 1); 41 | } 42 | }, 100); 43 | }); 44 | } -------------------------------------------------------------------------------- /test/js/wrappedobjectfactory-test.js: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * NAN - Native Abstractions for Node.js 3 | * 4 | * Copyright (c) 2018 NAN contributors 5 | * 6 | * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> 7 | ********************************************************************/ 8 | 9 | const test = require('tap').test 10 | , testRoot = require('path').resolve(__dirname, '..') 11 | , bindings = require('bindings')({ module_root: testRoot, bindings: 'wrappedobjectfactory' }); 12 | 13 | test('wrappedobjectfactory', function (t) { 14 | t.plan(4); 15 | 16 | var obj = bindings.newFactoryObjectInstance(123); 17 | 18 | t.type(obj.getValue, 'function'); 19 | t.type(obj.getValue(), 'number'); 20 | t.equal(obj.getValue(), 123); 21 | 22 | var inner = obj.newInnerObject(456); 23 | t.equal(inner.getValue(), 456); 24 | }); 25 | -------------------------------------------------------------------------------- /test/tap-as-worker.js: -------------------------------------------------------------------------------- 1 | // Run the tap tests in a worker 2 | // Not a clean approach, but is sufficient to verify correctness 3 | const worker_threads = require('worker_threads'); 4 | const path = require('path'); 5 | 6 | if (worker_threads.isMainThread) { 7 | const worker = new worker_threads.Worker(__filename, { 8 | workerData: process.argv 9 | }); 10 | worker.on('error', () => { 11 | // Worker will have logged the error, but will not set the exit code 12 | process.exit(1); 13 | }); 14 | } else { 15 | process.argv = worker_threads.workerData; 16 | require(path.resolve(require.resolve('tap'), '../../bin/tap.js')); 17 | } 18 | -------------------------------------------------------------------------------- /tools/README.md: -------------------------------------------------------------------------------- 1 | 1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, 2 | false positives and missed opportunities. The input files are rewritten in place. Make sure that 3 | you have backups. You will have to manually review the changes afterwards and do some touchups. 4 | 5 | ```sh 6 | $ tools/1to2.js 7 | 8 | Usage: 1to2 [options] <file ...> 9 | 10 | Options: 11 | 12 | -h, --help output usage information 13 | -V, --version output the version number 14 | ``` 15 | -------------------------------------------------------------------------------- /tools/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "1to2", 3 | "version": "1.0.0", 4 | "description": "NAN 1 -> 2 Migration Script", 5 | "main": "1to2.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git://github.com/nodejs/nan.git" 9 | }, 10 | "contributors": [ 11 | "Benjamin Byholm <bbyholm@abo.fi> (https://github.com/kkoopa/)", 12 | "Mathias Küsel (https://github.com/mathiask88/)" 13 | ], 14 | "dependencies": { 15 | "glob": "~5.0.10", 16 | "commander": "~2.8.1" 17 | }, 18 | "license": "MIT" 19 | } 20 | --------------------------------------------------------------------------------