(show)
|
/manta/public/examples/node-v0.10.17/CONTRIBUTING.md
The node.js project welcomes new contributors. This document will guide you
through the process.
Fork the project [on GitHub](https://github.com/joyent/node) and check out
your copy.
```
$ git clone git@github.com:username/node.git
$ cd node
$ git remote add upstream git://github.com/joyent/node.git
```
Now decide if you want your feature or bug fix to go into the master branch
or the stable branch. As a rule of thumb, bug fixes go into the stable branch
while new features go into the master branch.
The stable branch is effectively frozen; patches that change the node.js
API/ABI or affect the run-time behavior of applications get rejected.
The rules for the master branch are less strict; consult the
[stability index page][] for details.
In a nutshell, modules are at varying levels of API stability. Bug fixes are
always welcome but API or behavioral changes to modules at stability level 3
and up are off-limits.
Node.js has several bundled dependencies in the deps/ and the tools/
directories that are not part of the project proper. Any changes to files
in those directories or its subdirectories should be sent to their respective
projects. Do not send your patch to us, we cannot accept it.
In case of doubt, open an issue in the [issue tracker][], post your question
to the [node.js mailing list][] or contact one of the [project maintainers][]
on [IRC][].
Especially do so if you plan to work on something big. Nothing is more
frustrating than seeing your hard work go to waste because your vision
does not align with that of a project maintainer.
Okay, so you have decided on the proper branch. Create a feature branch
and start hacking:
```
$ git checkout -b my-feature-branch -t origin/v0.10
```
(Where v0.10 is the latest stable branch as of this writing.)
Make sure git knows your name and email address:
```
$ git config --global user.name "J. Random User"
$ git config --global user.email "j.random.user@example.com"
```
Writing good commit logs is important. A commit log should describe what
changed and why. Follow these guidelines when writing one:
1. The first line should be 50 characters or less and contain a short
description of the change prefixed with the name of the changed
subsystem (e.g. "net: add localAddress and localPort to Socket").
2. Keep the second line blank.
3. Wrap all other lines at 72 columns.
A good commit log looks like this:
```
subsystem: explaining the commit in one line
Body of commit message is a few lines of text, explaining things
in more detail, possibly giving some background about the issue
being fixed, etc etc.
The body of the commit message can be several paragraphs, and
please do proper word-wrap and keep columns shorter than about
72 characters or so. That way `git log` will show things
nicely even when it is indented.
```
The header line should be meaningful; it is what other people see when they
run `git shortlog` or `git log --oneline`.
Check the output of `git log --oneline files_that_you_changed` to find out
what subsystem (or subsystems) your changes touch.
Use `git rebase` (not `git merge`) to sync your work from time to time.
```
$ git fetch upstream
$ git rebase upstream/v0.10 # or upstream/master
```
Bug fixes and features should come with tests. Add your tests in the
test/simple/ directory. Look at other tests to see how they should be
structured (license boilerplate, common includes, etc.).
```
$ make jslint test
```
Make sure the linter is happy and that all tests pass. Please, do not submit
patches that fail either check.
```
$ git push origin my-feature-branch
```
Go to https://github.com/username/node and select your feature branch. Click
the 'Pull Request' button and fill out the form.
Pull requests are usually reviewed within a few days. If there are comments
to address, apply your changes in a separate commit and push that to your
feature branch. Post a comment in the pull request afterwards; GitHub does
not send out notifications when you add commits.
Please visit http://nodejs.org/cla.html and sign the Contributor License
Agreement. You only need to do that once.
[stability index page]: https://github.com/joyent/node/blob/master/doc/api/documentation.markdown
[issue tracker]: https://github.com/joyent/node/issues
[node.js mailing list]: http://groups.google.com/group/nodejs
[IRC]: http://webchat.freenode.net/?channels=node.js
[project maintainers]: https://github.com/joyent/node/wiki/Project-Organization
|
(show)
|
/manta/public/examples/node-v0.10.17/common.gypi
{
'variables': {
'visibility%': 'hidden', # V8's visibility setting
'target_arch%': 'ia32', # set v8's target architecture
'host_arch%': 'ia32', # set v8's host architecture
'want_separate_host_toolset': 0, # V8 should not build target and host
'library%': 'static_library', # allow override to 'shared_library' for DLL/.so builds
'component%': 'static_library', # NB. these names match with what V8 expects
'msvs_multi_core_compile': '0', # we do enable multicore compiles, but not using the V8 way
'gcc_version%': 'unknown',
'clang%': 0,
'python%': 'python',
# Turn on optimizations that may trigger compiler bugs.
# Use at your own risk. Do *NOT* report bugs if this option is enabled.
'node_unsafe_optimizations%': 0,
# Enable V8's post-mortem debugging only on unix flavors.
'conditions': [
['OS != "win"', {
'v8_postmortem_support': 'true'
}]
],
},
'target_defaults': {
'default_configuration': 'Release',
'configurations': {
'Debug': {
'defines': [ 'DEBUG', '_DEBUG' ],
'cflags': [ '-g', '-O0' ],
'conditions': [
['target_arch=="x64"', {
'msvs_configuration_platform': 'x64',
}],
],
'msvs_settings': {
'VCCLCompilerTool': {
'RuntimeLibrary': 1, # static debug
'Optimization': 0, # /Od, no optimization
'MinimalRebuild': 'false',
'OmitFramePointers': 'false',
'BasicRuntimeChecks': 3, # /RTC1
},
'VCLinkerTool': {
'LinkIncremental': 2, # enable incremental linking
},
},
'xcode_settings': {
'GCC_OPTIMIZATION_LEVEL': '0', # stop gyp from defaulting to -Os
},
},
'Release': {
'conditions': [
['target_arch=="x64"', {
'msvs_configuration_platform': 'x64',
}],
['node_unsafe_optimizations==1', {
'cflags': [ '-O3', '-ffunction-sections', '-fdata-sections' ],
'ldflags': [ '-Wl,--gc-sections' ],
}, {
'cflags': [ '-O2', '-fno-strict-aliasing' ],
'cflags!': [ '-O3', '-fstrict-aliasing' ],
'conditions': [
# Required by the dtrace post-processor. Unfortunately,
# some gcc/binutils combos generate bad code when
# -ffunction-sections is enabled. Let's hope for the best.
['OS=="solaris"', {
'cflags': [ '-ffunction-sections', '-fdata-sections' ],
}, {
'cflags!': [ '-ffunction-sections', '-fdata-sections' ],
}],
['clang == 0 and gcc_version >= 40', {
'cflags': [ '-fno-tree-vrp' ],
}],
['clang == 0 and gcc_version <= 44', {
'cflags': [ '-fno-tree-sink' ],
}],
],
}],
['OS=="solaris"', {
'cflags': [ '-fno-omit-frame-pointer' ],
# pull in V8's postmortem metadata
'ldflags': [ '-Wl,-z,allextract' ]
}],
],
'msvs_settings': {
'VCCLCompilerTool': {
'RuntimeLibrary': 0, # static release
'Optimization': 3, # /Ox, full optimization
'FavorSizeOrSpeed': 1, # /Ot, favour speed over size
'InlineFunctionExpansion': 2, # /Ob2, inline anything eligible
'WholeProgramOptimization': 'true', # /GL, whole program optimization, needed for LTCG
'OmitFramePointers': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'RuntimeTypeInfo': 'false',
'ExceptionHandling': '0',
'AdditionalOptions': [
'/MP', # compile across multiple CPUs
],
},
'VCLibrarianTool': {
'AdditionalOptions': [
'/LTCG', # link time code generation
],
},
'VCLinkerTool': {
'LinkTimeCodeGeneration': 1, # link-time code generation
'OptimizeReferences': 2, # /OPT:REF
'EnableCOMDATFolding': 2, # /OPT:ICF
'LinkIncremental': 1, # disable incremental linking
},
},
}
},
'msvs_settings': {
'VCCLCompilerTool': {
'StringPooling': 'true', # pool string literals
'DebugInformationFormat': 3, # Generate a PDB
'WarningLevel': 3,
'BufferSecurityCheck': 'true',
'ExceptionHandling': 1, # /EHsc
'SuppressStartupBanner': 'true',
'WarnAsError': 'false',
},
'VCLibrarianTool': {
},
'VCLinkerTool': {
'conditions': [
['target_arch=="x64"', {
'TargetMachine' : 17 # /MACHINE:X64
}],
],
'GenerateDebugInformation': 'true',
'RandomizedBaseAddress': 2, # enable ASLR
'DataExecutionPrevention': 2, # enable DEP
'AllowIsolation': 'true',
'SuppressStartupBanner': 'true',
'target_conditions': [
['_type=="executable"', {
'SubSystem': 1, # console executable
}],
],
},
},
'conditions': [
['OS == "win"', {
'msvs_cygwin_shell': 0, # prevent actions from trying to use cygwin
'defines': [
'WIN32',
# we don't really want VC++ warning us about
# how dangerous C functions are...
'_CRT_SECURE_NO_DEPRECATE',
# ... or that C implementations shouldn't use
# POSIX names
'_CRT_NONSTDC_NO_DEPRECATE',
'BUILDING_V8_SHARED=1',
'BUILDING_UV_SHARED=1',
],
}],
[ 'OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', {
'cflags': [ '-Wall', '-Wextra', '-Wno-unused-parameter', '-pthread', ],
'cflags_cc': [ '-fno-rtti', '-fno-exceptions' ],
'ldflags': [ '-pthread', '-rdynamic' ],
'target_conditions': [
['_type=="static_library"', {
'standalone_static_library': 1, # disable thin archive which needs binutils >= 2.19
}],
],
'conditions': [
[ 'target_arch=="ia32"', {
'cflags': [ '-m32' ],
'ldflags': [ '-m32' ],
}],
[ 'target_arch=="x64"', {
'cflags': [ '-m64' ],
'ldflags': [ '-m64' ],
}],
[ 'OS=="solaris"', {
'cflags': [ '-pthreads' ],
'ldflags': [ '-pthreads' ],
'cflags!': [ '-pthread' ],
'ldflags!': [ '-pthread' ],
}],
],
}],
['OS=="mac"', {
'defines': ['_DARWIN_USE_64_BIT_INODE=1'],
'xcode_settings': {
'ALWAYS_SEARCH_USER_PATHS': 'NO',
'GCC_CW_ASM_SYNTAX': 'NO', # No -fasm-blocks
'GCC_DYNAMIC_NO_PIC': 'NO', # No -mdynamic-no-pic
# (Equivalent to -fPIC)
'GCC_ENABLE_CPP_EXCEPTIONS': 'NO', # -fno-exceptions
'GCC_ENABLE_CPP_RTTI': 'NO', # -fno-rtti
'GCC_ENABLE_PASCAL_STRINGS': 'NO', # No -mpascal-strings
'GCC_THREADSAFE_STATICS': 'NO', # -fno-threadsafe-statics
'PREBINDING': 'NO', # No -Wl,-prebind
'MACOSX_DEPLOYMENT_TARGET': '10.5', # -mmacosx-version-min=10.5
'USE_HEADERMAP': 'NO',
'OTHER_CFLAGS': [
'-fno-strict-aliasing',
],
'WARNING_CFLAGS': [
'-Wall',
'-Wendif-labels',
'-W',
'-Wno-unused-parameter',
],
},
'target_conditions': [
['_type!="static_library"', {
'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-search_paths_first']},
}],
],
'conditions': [
['target_arch=="ia32"', {
'xcode_settings': {'ARCHS': ['i386']},
}],
['target_arch=="x64"', {
'xcode_settings': {'ARCHS': ['x86_64']},
}],
],
}],
['OS=="freebsd" and node_use_dtrace=="true"', {
'libraries': [ '-lelf' ],
}]
],
}
}
|
(show)
|
/manta/public/examples/node-v0.10.17/.travis.yml
language: node_js
before_script:
- "./configure"
- "make"
script:
- "make test"
notifications:
email: false
irc:
- "irc.freenode.net#libuv"
|
(show)
|
/manta/public/examples/node-v0.10.17/README.md
Prerequisites (Unix only):
* GCC 4.2 or newer
* Python 2.6 or 2.7
* GNU Make 3.81 or newer
* libexecinfo (FreeBSD and OpenBSD only)
Unix/Macintosh:
./configure
make
make install
If your python binary is in a non-standard location or has a
non-standard name, run the following instead:
export PYTHON=/path/to/python
$PYTHON ./configure
make
make install
Windows:
vcbuild.bat
Unix/Macintosh:
make test
Windows:
vcbuild.bat test
make doc
man doc/node.1
- [The Wiki](https://github.com/joyent/node/wiki)
- [nodejs.org](http://nodejs.org/)
- [how to install node.js and npm (node package manager)](http://joyeur.com/2010/12/10/installing-node-and-npm/)
- [list of modules](https://github.com/joyent/node/wiki/modules)
- [searching the npm registry](http://npmjs.org/)
- [list of companies and projects using node](https://github.com/joyent/node/wiki/Projects,-Applications,-and-Companies-Using-Node)
- [node.js mailing list](http://groups.google.com/group/nodejs)
- irc chatroom, [#node.js on freenode.net](http://webchat.freenode.net?channels=node.js&uio=d4)
- [community](https://github.com/joyent/node/wiki/Community)
- [contributing](https://github.com/joyent/node/wiki/Contributing)
- [big list of all the helpful wiki pages](https://github.com/joyent/node/wiki/_pages)
|
(show)
|
/manta/public/examples/node-v0.10.17/node.gyp
{
'variables': {
'v8_use_snapshot%': 'true',
# Turn off -Werror in V8
# See http://codereview.chromium.org/8159015
'werror': '',
'node_use_dtrace%': 'false',
'node_use_etw%': 'false',
'node_use_perfctr%': 'false',
'node_has_winsdk%': 'false',
'node_shared_v8%': 'false',
'node_shared_zlib%': 'false',
'node_shared_http_parser%': 'false',
'node_shared_cares%': 'false',
'node_shared_libuv%': 'false',
'node_use_openssl%': 'true',
'node_use_systemtap%': 'false',
'node_shared_openssl%': 'false',
'library_files': [
'src/node.js',
'lib/_debugger.js',
'lib/_linklist.js',
'lib/assert.js',
'lib/buffer.js',
'lib/child_process.js',
'lib/console.js',
'lib/constants.js',
'lib/crypto.js',
'lib/cluster.js',
'lib/dgram.js',
'lib/dns.js',
'lib/domain.js',
'lib/events.js',
'lib/freelist.js',
'lib/fs.js',
'lib/http.js',
'lib/https.js',
'lib/module.js',
'lib/net.js',
'lib/os.js',
'lib/path.js',
'lib/punycode.js',
'lib/querystring.js',
'lib/readline.js',
'lib/repl.js',
'lib/stream.js',
'lib/_stream_readable.js',
'lib/_stream_writable.js',
'lib/_stream_duplex.js',
'lib/_stream_transform.js',
'lib/_stream_passthrough.js',
'lib/string_decoder.js',
'lib/sys.js',
'lib/timers.js',
'lib/tls.js',
'lib/tty.js',
'lib/url.js',
'lib/util.js',
'lib/vm.js',
'lib/zlib.js',
],
},
'targets': [
{
'target_name': 'node',
'type': 'executable',
'dependencies': [
'node_js2c#host',
],
'include_dirs': [
'src',
'tools/msvs/genfiles',
'deps/uv/src/ares',
'<(SHARED_INTERMEDIATE_DIR)' # for node_natives.h
],
'sources': [
'src/fs_event_wrap.cc',
'src/cares_wrap.cc',
'src/handle_wrap.cc',
'src/node.cc',
'src/node_buffer.cc',
'src/node_constants.cc',
'src/node_extensions.cc',
'src/node_file.cc',
'src/node_http_parser.cc',
'src/node_javascript.cc',
'src/node_main.cc',
'src/node_os.cc',
'src/node_script.cc',
'src/node_stat_watcher.cc',
'src/node_string.cc',
'src/node_zlib.cc',
'src/pipe_wrap.cc',
'src/signal_wrap.cc',
'src/string_bytes.cc',
'src/stream_wrap.cc',
'src/slab_allocator.cc',
'src/tcp_wrap.cc',
'src/timer_wrap.cc',
'src/tty_wrap.cc',
'src/process_wrap.cc',
'src/v8_typed_array.cc',
'src/udp_wrap.cc',
# headers to make for a more pleasant IDE experience
'src/handle_wrap.h',
'src/node.h',
'src/node_buffer.h',
'src/node_constants.h',
'src/node_crypto.h',
'src/node_extensions.h',
'src/node_file.h',
'src/node_http_parser.h',
'src/node_javascript.h',
'src/node_os.h',
'src/node_root_certs.h',
'src/node_script.h',
'src/node_string.h',
'src/node_version.h',
'src/ngx-queue.h',
'src/pipe_wrap.h',
'src/tty_wrap.h',
'src/tcp_wrap.h',
'src/udp_wrap.h',
'src/req_wrap.h',
'src/slab_allocator.h',
'src/string_bytes.h',
'src/stream_wrap.h',
'src/tree.h',
'src/v8_typed_array.h',
'deps/http_parser/http_parser.h',
'<(SHARED_INTERMEDIATE_DIR)/node_natives.h',
# javascript files to make for an even more pleasant IDE experience
'<@(library_files)',
# node.gyp is added to the project by default.
'common.gypi',
],
'defines': [
'NODE_WANT_INTERNALS=1',
'ARCH="<(target_arch)"',
'PLATFORM="<(OS)"',
'NODE_TAG="<(node_tag)"',
],
'conditions': [
[ 'node_use_openssl=="true"', {
'defines': [ 'HAVE_OPENSSL=1' ],
'sources': [ 'src/node_crypto.cc' ],
'conditions': [
[ 'node_shared_openssl=="false"', {
'dependencies': [ './deps/openssl/openssl.gyp:openssl' ],
}]]
}, {
'defines': [ 'HAVE_OPENSSL=0' ]
}],
[ 'node_use_dtrace=="true"', {
'defines': [ 'HAVE_DTRACE=1' ],
'dependencies': [ 'node_dtrace_header' ],
'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)' ],
#
# DTrace is supported on solaris, mac, and bsd. There are three
# object files associated with DTrace support, but they're not all
# used all the time:
#
# node_dtrace.o all configurations
# node_dtrace_ustack.o not supported on OS X
# node_dtrace_provider.o All except OS X. "dtrace -G" is not
# used on OS X.
#
# Note that node_dtrace_provider.cc and node_dtrace_ustack.cc do not
# actually exist. They're listed here to trick GYP into linking the
# corresponding object files into the final "node" executable. These
# object files are generated by "dtrace -G" using custom actions
# below, and the GYP-generated Makefiles will properly build them when
# needed.
#
'sources': [
'src/node_dtrace.cc',
],
'conditions': [ [
'OS!="mac"', {
'sources': [
'src/node_dtrace_ustack.cc',
'src/node_dtrace_provider.cc',
]
}
] ]
} ],
[ 'node_use_systemtap=="true"', {
'defines': [ 'HAVE_SYSTEMTAP=1', 'STAP_SDT_V1=1' ],
'dependencies': [ 'node_systemtap_header' ],
'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)' ],
'sources': [
'src/node_dtrace.cc',
'<(SHARED_INTERMEDIATE_DIR)/node_systemtap.h',
],
} ],
[ 'node_use_etw=="true"', {
'defines': [ 'HAVE_ETW=1' ],
'dependencies': [ 'node_etw' ],
'sources': [
'src/node_win32_etw_provider.h',
'src/node_win32_etw_provider-inl.h',
'src/node_win32_etw_provider.cc',
'src/node_dtrace.cc',
'tools/msvs/genfiles/node_etw_provider.h',
'tools/msvs/genfiles/node_etw_provider.rc',
]
} ],
[ 'node_use_perfctr=="true"', {
'defines': [ 'HAVE_PERFCTR=1' ],
'dependencies': [ 'node_perfctr' ],
'sources': [
'src/node_win32_perfctr_provider.h',
'src/node_win32_perfctr_provider.cc',
'src/node_counters.cc',
'src/node_counters.h',
'tools/msvs/genfiles/node_perfctr_provider.rc',
]
} ],
[ 'node_shared_v8=="false"', {
'sources': [
'deps/v8/include/v8.h',
'deps/v8/include/v8-debug.h',
],
'dependencies': [ 'deps/v8/tools/gyp/v8.gyp:v8' ],
}],
[ 'node_shared_zlib=="false"', {
'dependencies': [ 'deps/zlib/zlib.gyp:zlib' ],
}],
[ 'node_shared_http_parser=="false"', {
'dependencies': [ 'deps/http_parser/http_parser.gyp:http_parser' ],
}],
[ 'node_shared_cares=="false"', {
'dependencies': [ 'deps/cares/cares.gyp:cares' ],
}],
[ 'node_shared_libuv=="false"', {
'dependencies': [ 'deps/uv/uv.gyp:libuv' ],
}],
[ 'OS=="win"', {
'sources': [
'src/res/node.rc',
],
'defines': [
'FD_SETSIZE=1024',
# we need to use node's preferred "win32" rather than gyp's preferred "win"
'PLATFORM="win32"',
'_UNICODE=1',
],
'libraries': [ '-lpsapi.lib' ]
}, { # POSIX
'defines': [ '__POSIX__' ],
}],
[ 'OS=="mac"', {
'libraries': [ '-framework Carbon' ],
'defines!': [
'PLATFORM="mac"',
],
'defines': [
# we need to use node's preferred "darwin" rather than gyp's preferred "mac"
'PLATFORM="darwin"',
],
}],
[ 'OS=="freebsd"', {
'libraries': [
'-lutil',
'-lkvm',
],
}],
[ 'OS=="solaris"', {
'libraries': [
'-lkstat',
'-lumem',
],
'defines!': [
'PLATFORM="solaris"',
],
'defines': [
# we need to use node's preferred "sunos"
# rather than gyp's preferred "solaris"
'PLATFORM="sunos"',
],
}],
],
'msvs_settings': {
'VCLinkerTool': {
'SubSystem': 1, # /subsystem:console
},
},
},
# generate ETW header and resource files
{
'target_name': 'node_etw',
'type': 'none',
'conditions': [
[ 'node_use_etw=="true" and node_has_winsdk=="true"', {
'actions': [
{
'action_name': 'node_etw',
'inputs': [ 'src/res/node_etw_provider.man' ],
'outputs': [
'tools/msvs/genfiles/node_etw_provider.rc',
'tools/msvs/genfiles/node_etw_provider.h',
'tools/msvs/genfiles/node_etw_providerTEMP.BIN',
],
'action': [ 'mc <@(_inputs) -h tools/msvs/genfiles -r tools/msvs/genfiles' ]
}
]
} ]
]
},
# generate perf counter header and resource files
{
'target_name': 'node_perfctr',
'type': 'none',
'conditions': [
[ 'node_use_perfctr=="true" and node_has_winsdk=="true"', {
'actions': [
{
'action_name': 'node_perfctr_man',
'inputs': [ 'src/res/node_perfctr_provider.man' ],
'outputs': [
'tools/msvs/genfiles/node_perfctr_provider.h',
'tools/msvs/genfiles/node_perfctr_provider.rc',
'tools/msvs/genfiles/MSG00001.
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/vcbuild.bat
@echo off
cd %~dp0
if /i "%1"=="help" goto help
if /i "%1"=="--help" goto help
if /i "%1"=="-help" goto help
if /i "%1"=="/help" goto help
if /i "%1"=="?" goto help
if /i "%1"=="-?" goto help
if /i "%1"=="--?" goto help
if /i "%1"=="/?" goto help
@rem Process arguments.
set config=Release
set msiplatform=x86
set target=Build
set target_arch=ia32
set debug_arg=
set nosnapshot_arg=
set noprojgen=
set nobuild=
set nosign=
set nosnapshot=
set test=
set test_args=
set msi=
set licensertf=
set upload=
set jslint=
set buildnodeweak=
set noetw=
set noetw_arg=
set noetw_msi_arg=
set noperfctr=
set noperfctr_arg=
set noperfctr_msi_arg=
:next-arg
if "%1"=="" goto args-done
if /i "%1"=="debug" set config=Debug&goto arg-ok
if /i "%1"=="release" set config=Release&goto arg-ok
if /i "%1"=="clean" set target=Clean&goto arg-ok
if /i "%1"=="ia32" set target_arch=ia32&goto arg-ok
if /i "%1"=="x86" set target_arch=ia32&goto arg-ok
if /i "%1"=="x64" set target_arch=x64&goto arg-ok
if /i "%1"=="noprojgen" set noprojgen=1&goto arg-ok
if /i "%1"=="nobuild" set nobuild=1&goto arg-ok
if /i "%1"=="nosign" set nosign=1&goto arg-ok
if /i "%1"=="nosnapshot" set nosnapshot=1&goto arg-ok
if /i "%1"=="noetw" set noetw=1&goto arg-ok
if /i "%1"=="noperfctr" set noperfctr=1&goto arg-ok
if /i "%1"=="licensertf" set licensertf=1&goto arg-ok
if /i "%1"=="test-uv" set test=test-uv&goto arg-ok
if /i "%1"=="test-internet" set test=test-internet&goto arg-ok
if /i "%1"=="test-pummel" set test=test-pummel&goto arg-ok
if /i "%1"=="test-simple" set test=test-simple&goto arg-ok
if /i "%1"=="test-message" set test=test-message&goto arg-ok
if /i "%1"=="test-gc" set test=test-gc&set buildnodeweak=1&goto arg-ok
if /i "%1"=="test-all" set test=test-all&set buildnodeweak=1&goto arg-ok
if /i "%1"=="test" set test=test&goto arg-ok
if /i "%1"=="msi" set msi=1&set licensertf=1&goto arg-ok
if /i "%1"=="upload" set upload=1&goto arg-ok
if /i "%1"=="jslint" set jslint=1&goto arg-ok
echo Warning: ignoring invalid command line option `%1`.
:arg-ok
:arg-ok
shift
goto next-arg
:args-done
if defined upload goto upload
if defined jslint goto jslint
if "%config%"=="Debug" set debug_arg=--debug
if "%target_arch%"=="x64" set msiplatform=x64
if defined nosnapshot set nosnapshot_arg=--without-snapshot
if defined noetw set noetw_arg=--without-etw& set noetw_msi_arg=/p:NoETW=1
if defined noperfctr set noperfctr_arg=--without-perfctr& set noperfctr_msi_arg=/p:NoPerfCtr=1
:project-gen
@rem Skip project generation if requested.
if defined noprojgen goto msbuild
if defined NIGHTLY set TAG=nightly-%NIGHTLY%
@rem Generate the VS project.
SETLOCAL
if defined VS100COMNTOOLS call "%VS100COMNTOOLS%\VCVarsQueryRegistry.bat"
python configure %debug_arg% %nosnapshot_arg% %noetw_arg% %noperfctr_arg% --dest-cpu=%target_arch% --tag=%TAG%
if errorlevel 1 goto create-msvs-files-failed
if not exist node.sln goto create-msvs-files-failed
echo Project files generated.
ENDLOCAL
:msbuild
@rem Skip project generation if requested.
if defined nobuild goto sign
@rem Look for Visual Studio 2012
if not defined VS110COMNTOOLS goto vc-set-2010
if not exist "%VS110COMNTOOLS%\..\..\vc\vcvarsall.bat" goto vc-set-2010
call "%VS110COMNTOOLS%\..\..\vc\vcvarsall.bat"
if not defined VCINSTALLDIR goto msbuild-not-found
set GYP_MSVS_VERSION=2012
goto msbuild-found
:vc-set-2010
if not defined VS100COMNTOOLS goto msbuild-not-found
if not exist "%VS100COMNTOOLS%\..\..\vc\vcvarsall.bat" goto msbuild-not-found
call "%VS100COMNTOOLS%\..\..\vc\vcvarsall.bat"
if not defined VCINSTALLDIR goto msbuild-not-found
goto msbuild-found
:msbuild-not-found
echo Build skipped. To build, this file needs to run from VS cmd prompt.
goto run
:msbuild-found
@rem Build the sln with msbuild.
msbuild node.sln /m /t:%target% /p:Configuration=%config% /clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal /nologo
if errorlevel 1 goto exit
:sign
@rem Skip signing if the `nosign` option was specified.
if defined nosign goto licensertf
signtool sign /a Release\node.exe
:licensertf
@rem Skip license.rtf generation if not requested.
if not defined licensertf goto msi
%config%\node tools\license2rtf.js < LICENSE > %config%\license.rtf
if errorlevel 1 echo Failed to generate license.rtf&goto exit
:msi
@rem Skip msi generation if not requested
if not defined msi goto run
call :getnodeversion
if not defined NIGHTLY goto msibuild
set NODE_VERSION=%NODE_VERSION%.%NIGHTLY%
:msibuild
echo Building node-%NODE_VERSION%
msbuild "%~dp0tools\msvs\msi\nodemsi.sln" /m /t:Clean,Build /p:Configuration=%config% /p:Platform=%msiplatform% /p:NodeVersion=%NODE_VERSION% %noetw_msi_arg% %noperfctr_msi_arg% /clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal /nologo
if errorlevel 1 goto exit
if defined nosign goto run
signtool sign /a Release\node-v%NODE_VERSION%-%msiplatform%.msi
:run
@rem Run tests if requested.
if "%test%"=="" goto exit
if "%config%"=="Debug" set test_args=--mode=debug
if "%config%"=="Release" set test_args=--mode=release
if "%test%"=="test" set test_args=%test_args% simple message
if "%test%"=="test-internet" set test_args=%test_args% internet
if "%test%"=="test-pummel" set test_args=%test_args% pummel
if "%test%"=="test-simple" set test_args=%test_args% simple
if "%test%"=="test-message" set test_args=%test_args% message
if "%test%"=="test-gc" set test_args=%test_args% gc
if "%test%"=="test-all" set test_args=%test_args%
:build-node-weak
@rem Build node-weak if required
if "%buildnodeweak%"=="" goto run-tests
"%config%\node" deps\npm\node_modules\node-gyp\bin\node-gyp rebuild --directory="%~dp0test\gc\node_modules\weak" --nodedir="%~dp0."
if errorlevel 1 goto build-node-weak-failed
goto run-tests
:build-node-weak-failed
echo Failed to build node-weak.
goto exit
:run-tests
echo running 'python tools/test.py %test_args%'
python tools/test.py %test_args%
if "%test%"=="test" goto jslint
goto exit
:create-msvs-files-failed
echo Failed to create vc project files.
goto exit
:upload
echo uploading .exe .msi .pdb to nodejs.org
call :getnodeversion
@echo on
ssh node@nodejs.org mkdir -p web/nodejs.org/dist/v%NODE_VERSION%
scp Release\node.msi node@nodejs.org:~/web/nodejs.org/dist/v%NODE_VERSION%/node-v%NODE_VERSION%.msi
scp Release\node.exe node@nodejs.org:~/web/nodejs.org/dist/v%NODE_VERSION%/node.exe
scp Release\node.pdb node@nodejs.org:~/web/nodejs.org/dist/v%NODE_VERSION%/node.pdb
@echo off
goto exit
:jslint
echo running jslint
set PYTHONPATH=tools/closure_linter/
python tools/closure_linter/closure_linter/gjslint.py --unix_mode --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js
goto exit
:help
echo vcbuild.bat [debug/release] [msi] [test-all/test-uv/test-internet/test-pummel/test-simple/test-message] [clean] [noprojgen] [nobuild] [nosign] [x86/x64]
echo Examples:
echo vcbuild.bat : builds release build
echo vcbuild.bat debug : builds debug build
echo vcbuild.bat release msi : builds release build and MSI installer package
echo vcbuild.bat test : builds debug build and runs tests
goto exit
:exit
goto :EOF
rem ***************
rem Subroutines
rem ***************
:getnodeversion
set NODE_VERSION=
for /F "usebackq tokens=*" %i in (`python "%~dp0tools\getnodeversion.py"`) do set NODE_VERSION=%i
if not defined NODE_VERSION echo Cannot determine current version of node.js & exit /b 1
goto :EOF
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/common.js
var assert = require('assert');
var path = require('path');
var silent = +process.env.NODE_BENCH_SILENT;
exports.PORT = process.env.PORT || 12346;
if (module === require.main) {
var type = process.argv[2];
if (!type) {
console.error('usage:\n ./node benchmark/common.js <type>');
process.exit(1);
}
var fs = require('fs');
var dir = path.join(__dirname, type);
var tests = fs.readdirSync(dir);
var spawn = require('child_process').spawn;
runBenchmarks();
function runBenchmarks() {
var test = tests.shift();
if (!test)
return;
if (test.match(/^[\._]/))
return process.nextTick(runBenchmarks);
console.error(type + '/' + test);
test = path.resolve(dir, test);
var child = spawn(process.execPath, [ test ], { stdio: 'inherit' });
child.on('close', function(code) {
if (code)
process.exit(code);
else {
console.log('');
runBenchmarks();
}
});
}
}
exports.createBenchmark = function(fn, options) {
return new Benchmark(fn, options);
};
function Benchmark(fn, options) {
this.fn = fn;
this.options = options;
this.config = parseOpts(options);
this._name = require.main.filename.split(/benchmark[\/\\]/).pop();
this._start = [0,0];
this._started = false;
var self = this;
process.nextTick(function() {
self._run();
});
}
Benchmark.prototype.http = function(p, args, cb) {
var self = this;
var wrk = path.resolve(__dirname, '..', 'tools', 'wrk', 'wrk');
var regexp = /Requests\/sec:[ \t]+([0-9\.]+)/;
var spawn = require('child_process').spawn;
var url = 'http://127.0.0.1:' + exports.PORT + p;
args = args.concat(url);
var out = '';
var child = spawn(wrk, args);
child.stdout.setEncoding('utf8');
child.stdout.on('data', function(chunk) {
out += chunk;
});
child.on('close', function(code) {
if (cb)
cb(code);
if (code) {
console.error('wrk failed with ' + code);
process.exit(code)
}
var m = out.match(regexp);
var qps = m && +m[1];
if (!qps) {
console.error('%j', out);
console.error('wrk produced strange output');
process.exit(1);
}
self.report(+qps);
});
};
Benchmark.prototype._run = function() {
if (this.config)
return this.fn(this.config);
var main = require.main.filename;
var settings = [];
var queueLen = 1;
var options = this.options;
var queue = Object.keys(options).reduce(function(set, key) {
var vals = options[key];
assert(Array.isArray(vals));
var newSet = new Array(set.length * vals.length);
var j = 0;
set.forEach(function(s) {
vals.forEach(function(val) {
newSet[j++] = s.concat(key + '=' + val);
});
});
return newSet;
}, [[main]]);
var spawn = require('child_process').spawn;
var node = process.execPath;
var i = 0;
function run() {
var argv = queue[i++];
if (!argv)
return;
var child = spawn(node, argv, { stdio: 'inherit' });
child.on('close', function(code, signal) {
if (code)
console.error('child process exited with code ' + code);
else
run();
});
}
run();
};
function parseOpts(options) {
var keys = Object.keys(options);
var num = keys.length;
var conf = {};
for (var i = 2; i < process.argv.length; i++) {
var m = process.argv[i].match(/^(.+)=(.+)$/);
if (!m || !m[1] || !m[2] || !options[m[1]])
return null;
else {
conf[m[1]] = isFinite(m[2]) ? +m[2] : m[2]
num--;
}
}
if (num !== 0) {
Object.keys(conf).forEach(function(k) {
options[k] = [conf[k]];
});
}
return num === 0 ? conf : null;
};
Benchmark.prototype.start = function() {
if (this._started)
throw new Error('Called start more than once in a single benchmark');
this._started = true;
this._start = process.hrtime();
};
Benchmark.prototype.end = function(operations) {
var elapsed = process.hrtime(this._start);
if (!this._started)
throw new Error('called end without start');
if (typeof operations !== 'number')
throw new Error('called end() without specifying operation count');
var time = elapsed[0] + elapsed[1]/1e9;
var rate = operations/time;
this.report(rate);
};
Benchmark.prototype.report = function(value) {
var heading = this.getHeading();
if (!silent)
console.log('%s: %s', heading, value.toPrecision(5));
process.exit(0);
};
Benchmark.prototype.getHeading = function() {
var conf = this.config;
return this._name + ' ' + Object.keys(conf).map(function(key) {
return key + '=' + conf[key];
}).join(' ');
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/fs-write-stream-throughput.js
if (!process.argv[2])
parent();
else
runTest(+process.argv[2], +process.argv[3], process.argv[4]);
function parent() {
var types = [ 'string', 'buffer' ];
var durs = [ 1, 5 ];
var sizes = [ 1, 10, 100, 2048, 10240 ];
var queue = [];
types.forEach(function(t) {
durs.forEach(function(d) {
sizes.forEach(function(s) {
queue.push([__filename, d, s, t]);
});
});
});
var spawn = require('child_process').spawn;
var node = process.execPath;
run();
function run() {
var args = queue.shift();
if (!args)
return;
var child = spawn(node, args, { stdio: 'inherit' });
child.on('close', function(code, signal) {
if (code)
throw new Error('Benchmark failed: ' + args.slice(1));
run();
});
}
}
function runTest(dur, size, type) {
if (type !== 'string')
type = 'buffer';
switch (type) {
case 'string':
var chunk = new Array(size + 1).join('a');
break;
case 'buffer':
var chunk = new Buffer(size);
chunk.fill('a');
break;
}
var writes = 0;
var fs = require('fs');
try { fs.unlinkSync('write_stream_throughput'); } catch (e) {}
var start
var end;
function done() {
var time = end[0] + end[1]/1E9;
var written = fs.statSync('write_stream_throughput').size / 1024;
var rate = (written / time).toFixed(2);
console.log('fs_write_stream_dur_%d_size_%d_type_%s: %d',
dur, size, type, rate);
try { fs.unlinkSync('write_stream_throughput'); } catch (e) {}
}
var f = require('fs').createWriteStream('write_stream_throughput');
f.on('drain', write);
f.on('open', write);
f.on('close', done);
f.on('finish', function() {
end = process.hrtime(start);
});
var ending = false;
function write() {
if (ending)
return;
start = start || process.hrtime();
while (false !== f.write(chunk));
end = process.hrtime(start);
if (end[0] >= dur) {
ending = true;
f.end();
}
}
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http-flamegraph.sh
#!/bin/bash
cd "$(dirname "$(dirname $0)")"
node=${NODE:-./node}
name=${NAME:-stacks}
if type sysctl &>/dev/null; then
sudo sysctl -w net.inet.ip.portrange.first=12000
sudo sysctl -w net.inet.tcp.msl=1000
sudo sysctl -w kern.maxfiles=1000000 kern.maxfilesperproc=1000000
elif type /usr/sbin/ndd &>/dev/null; then
/usr/sbin/ndd -set /dev/tcp tcp_smallest_anon_port 12000
/usr/sbin/ndd -set /dev/tcp tcp_largest_anon_port 65535
/usr/sbin/ndd -set /dev/tcp tcp_max_buf 2097152
/usr/sbin/ndd -set /dev/tcp tcp_xmit_hiwat 1048576
/usr/sbin/ndd -set /dev/tcp tcp_recv_hiwat 1048576
fi
ulimit -n 100000
$node benchmark/http_simple.js &
nodepid=$!
echo "node pid = $nodepid"
sleep 1
dtrace -n 'profile-97/pid == '$nodepid' && arg1/{ @[jstack(150, 8000)] = count(); } tick-60s { exit(0); }' \
| grep -v _ZN2v88internalL21Builtin_HandleApiCallENS0_12_GLOBAL__N_116BuiltinA \
> "$name".src &
dtracepid=$!
echo "dtrace pid = $dtracepid"
sleep 1
test () {
c=$1
t=$2
l=$3
k=$4
ab $k -t 10 -c $c http://127.0.0.1:8000/$t/$l \
2>&1 | grep Req
}
echo 'Keep going until dtrace stops listening...'
while pargs $dtracepid &>/dev/null; do
test 100 bytes ${LENGTH:-1} -k
done
kill $nodepid
echo 'Turn the stacks into a svg'
stackvis dtrace flamegraph-svg < "$name".src > "$name".raw.svg
echo 'Prune tiny stacks out of the graph'
node -e '
var infile = process.argv[1];
var outfile = process.argv[2];
var output = "";
var fs = require("fs");
var input = fs.readFileSync(infile, "utf8");
input = input.split("id=\"details\" > </text>");
var head = input.shift() + "id=\"details\" > </text>";
input = input.join("id=\"details\" > </text>");
var tail = "</svg>";
input = input.split("</svg>")[0];
var minyKept = Infinity;
var minyOverall = Infinity;
var rects = input.trim().split(/\n/).filter(function(rect) {
var my = rect.match(/y="([0-9\.]+)"/);
if (!my)
return false;
var y = +my[1];
if (!y)
return false;
minyOverall = Math.min(minyOverall, y);
// pluck off everything that will be less than one pixel.
var mw = rect.match(/width="([0-9\.]+)"/)
if (mw) {
var width = +mw[1];
if (!(width >= 1))
return false;
}
minyKept = Math.min(minyKept, y);
return true;
});
// move everything up to the top of the page.
var ydiff = minyKept - minyOverall;
rects = rects.map(function(rect) {
var my = rect.match(/y="([0-9\.]+)"/);
var y = +my[1];
var newy = y - ydiff;
rect = rect.replace(/y="([0-9\.]+)"/, "y=\"" + newy + "\"");
return rect;
});
fs.writeFileSync(outfile, head + "\n" + rects.join("\n") + "\n" + tail);
' "$name".raw.svg "$name".svg
echo ''
echo 'done. Results in '"$name"'.svg'
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/compare.js
var usage = 'node benchmark/compare.js ' +
'<node-binary1> <node-binary2> ' +
'[--html] [--red|-r] [--green|-g]';
var show = 'both';
var nodes = [];
var html = false;
for (var i = 2; i < process.argv.length; i++) {
var arg = process.argv[i];
switch (arg) {
case '--red': case '-r':
show = show === 'green' ? 'both' : 'red';
break;
case '--green': case '-g':
show = show === 'red' ? 'both' : 'green';
break;
case '--html':
html = true;
break;
case '-h': case '-?': case '--help':
console.log(usage);
process.exit(0);
default:
nodes.push(arg);
break;
}
}
if (!html) {
var start = '';
var green = '\033[1;32m';
var red = '\033[1;31m';
var reset = '\033[m';
var end = '';
} else {
var start = '<pre style="background-color:#333;color:#eee">';
var green = '<span style="background-color:#0f0;color:#000">';
var red = '<span style="background-color:#f00;color:#fff">';
var reset = '</span>';
var end = '</pre>';
}
var runBench = process.env.NODE_BENCH || 'bench';
if (nodes.length !== 2)
return console.error('usage:\n %s', usage);
var spawn = require('child_process').spawn;
var results = {};
var toggle = 1;
var r = (+process.env.NODE_BENCH_RUNS || 1) * 2;
run();
function run() {
if (--r < 0)
return compare();
toggle = ++toggle % 2;
var node = nodes[toggle];
console.error('running %s', node);
var env = {};
for (var i in process.env)
env[i] = process.env[i];
env.NODE = node;
var out = '';
var child = spawn('make', [runBench], { env: env });
child.stdout.setEncoding('utf8');
child.stdout.on('data', function(c) {
out += c;
});
child.stderr.pipe(process.stderr);
child.on('close', function(code) {
if (code) {
console.error('%s exited with code=%d', node, code);
process.exit(code);
} else {
out.trim().split(/\r?\n/).forEach(function(line) {
line = line.trim();
if (!line)
return;
var s = line.split(':');
var num = +s.pop();
if (!num && num !== 0)
return;
line = s.join(':');
var res = results[line] = results[line] || {};
res[node] = res[node] || [];
res[node].push(num);
});
run();
}
});
}
function compare() {
var maxLen = -Infinity;
var util = require('util');
console.log(start);
Object.keys(results).map(function(bench) {
var res = results[bench];
var n0 = avg(res[nodes[0]]);
var n1 = avg(res[nodes[1]]);
var pct = ((n0 - n1) / n1 * 100).toFixed(2);
var g = n0 > n1 ? green : '';
var r = n0 > n1 ? '' : red;
var c = r || g;
if (show === 'green' && !g || show === 'red' && !r)
return;
var r0 = util.format('%s%s: %d%s', g, nodes[0], n0.toPrecision(5), g ? reset : '');
var r1 = util.format('%s%s: %d%s', r, nodes[1], n1.toPrecision(5), r ? reset : '');
var pct = c + pct + '%' + reset;
var l = util.format('%s: %s %s', bench, r0, r1);
maxLen = Math.max(l.length + pct.length, maxLen);
return [l, pct];
}).filter(function(l) {
return l;
}).forEach(function(line) {
var l = line[0];
var pct = line[1];
var dotLen = maxLen - l.length - pct.length + 2;
var dots = ' ' + new Array(Math.max(0, dotLen)).join('.') + ' ';
console.log(l + dots + pct);
});
console.log(end);
}
function avg(list) {
if (list.length >= 3) {
list = list.sort();
var q = Math.floor(list.length / 4) || 1;
list = list.slice(q, -q);
}
return list.reduce(function(a, b) {
return a + b;
}, 0) / list.length;
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http.sh
#!/bin/bash
cd "$(dirname "$(dirname $0)")"
if type sysctl &>/dev/null; then
sudo sysctl -w net.ipv4.ip_local_port_range="12000 65535"
sudo sysctl -w net.inet.ip.portrange.first=12000
sudo sysctl -w net.inet.tcp.msl=1000
sudo sysctl -w kern.maxfiles=1000000 kern.maxfilesperproc=1000000
elif type /usr/sbin/ndd &>/dev/null; then
/usr/sbin/ndd -set /dev/tcp tcp_smallest_anon_port 12000
/usr/sbin/ndd -set /dev/tcp tcp_largest_anon_port 65535
/usr/sbin/ndd -set /dev/tcp tcp_max_buf 2097152
/usr/sbin/ndd -set /dev/tcp tcp_xmit_hiwat 1048576
/usr/sbin/ndd -set /dev/tcp tcp_recv_hiwat 1048576
fi
ulimit -n 100000
k=${KEEPALIVE}
if [ "$k" = "no" ]; then
k=""
else
k="-k"
fi
node=${NODE:-./node}
$node benchmark/http_simple.js &
npid=$!
sleep 1
if [ "$k" = "-k" ]; then
echo "using keepalive"
fi
for i in a a a a a a a a a a a a a a a a a a a a; do
ab $k -t 10 -c 100 http://127.0.0.1:8000/${TYPE:-bytes}/${LENGTH:-1024} \
2>&1 | grep Req | egrep -o '[0-9\.]+'
done
kill $npid
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_bench.js
var spawn = require('child_process').spawn;
var cluster = require('cluster');
var http = require('http');
var options = {
mode: 'master',
host: '127.0.0.1',
port: 22344,
path: '/',
servers: 1,
clients: 1
};
for (var i = 2; i < process.argv.length; ++i) {
var args = process.argv[i].split('=', 2);
var key = args[0];
var val = args[1];
options[key] = val;
}
switch (options.mode) {
case 'master': startMaster(); break;
case 'server': startServer(); break;
case 'client': startClient(); break;
default: throw new Error('Bad mode: ' + options.mode);
}
process.title = 'http_bench[' + options.mode + ']';
console.log = patch(console.log);
console.trace = patch(console.trace);
console.error = patch(console.error);
function patch(fun) {
var prefix = process.title + '[' + process.pid + '] ';
return function() {
var args = Array.prototype.slice.call(arguments);
args[0] = prefix + args[0];
return fun.apply(console, args);
};
}
function startMaster() {
if (!cluster.isMaster) return startServer();
for (var i = ~~options.servers; i > 0; --i) cluster.fork();
for (var i = ~~options.clients; i > 0; --i) {
var cp = spawn(process.execPath, [__filename, 'mode=client']);
cp.stdout.pipe(process.stdout);
cp.stderr.pipe(process.stderr);
}
}
function startServer() {
http.createServer(onRequest).listen(options.port, options.host);
var body = Array(1024).join('x');
var headers = {'Content-Length': '' + body.length};
function onRequest(req, res) {
req.on('error', onError);
res.on('error', onError);
res.writeHead(200, headers);
res.end(body);
}
function onError(err) {
console.error(err.stack);
}
}
function startClient() {
sendRequest();
sendRequest();
function sendRequest() {
var req = http.request(options, onConnection);
req.on('error', onError);
req.end();
}
function relaxedSendRequest() {
setTimeout(sendRequest, 1);
}
function onConnection(res) {
res.on('error', onError);
res.on('data', onData);
res.on('end', relaxedSendRequest);
}
function onError(err) {
console.error(err.stack);
relaxedSendRequest();
}
function onData(data) {
}
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple.js
var path = require('path'),
exec = require('child_process').exec,
http = require('http');
var port = parseInt(process.env.PORT || 8000);
var fixed = makeString(20 * 1024, 'C'),
storedBytes = {},
storedBuffer = {},
storedUnicode = {};
var useDomains = process.env.NODE_USE_DOMAINS;
if (useDomains) {
var domain = require('domain');
var gdom = domain.create();
gdom.on('error', function(er) {
console.error('Error on global domain', er);
throw er;
});
gdom.enter();
}
var server = module.exports = http.createServer(function (req, res) {
if (useDomains) {
var dom = domain.create();
dom.add(req);
dom.add(res);
}
var commands = req.url.split('/');
var command = commands[1];
var body = '';
var arg = commands[2];
var n_chunks = parseInt(commands[3], 10);
var status = 200;
if (command == 'bytes') {
var n = ~~arg;
if (n <= 0)
throw new Error('bytes called with n <= 0')
if (storedBytes[n] === undefined) {
storedBytes[n] = makeString(n, 'C');
}
body = storedBytes[n];
} else if (command == 'buffer') {
var n = ~~arg;
if (n <= 0)
throw new Error('buffer called with n <= 0');
if (storedBuffer[n] === undefined) {
storedBuffer[n] = new Buffer(n);
for (var i = 0; i < n; i++) {
storedBuffer[n][i] = 'C'.charCodeAt(0);
}
}
body = storedBuffer[n];
} else if (command == 'unicode') {
var n = ~~arg;
if (n <= 0)
throw new Error('unicode called with n <= 0');
if (storedUnicode[n] === undefined) {
storedUnicode[n] = makeString(n, '\u263A');
}
body = storedUnicode[n];
} else if (command == 'quit') {
res.connection.server.close();
body = 'quitting';
} else if (command == 'fixed') {
body = fixed;
} else if (command == 'echo') {
res.writeHead(200, { 'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked' });
req.pipe(res);
return;
} else {
status = 404;
body = 'not found\n';
}
if (n_chunks > 0) {
res.writeHead(status, { 'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked' });
var len = body.length;
var step = Math.floor(len / n_chunks) || 1;
for (var i = 0, n = (n_chunks - 1); i < n; ++i) {
res.write(body.slice(i * step, i * step + step));
}
res.end(body.slice((n_chunks - 1) * step));
} else {
var content_length = body.length.toString();
res.writeHead(status, { 'Content-Type': 'text/plain',
'Content-Length': content_length });
res.end(body);
}
});
function makeString(size, c) {
var s = '';
while (s.length < size) {
s += c;
}
return s;
}
server.listen(port, function () {
if (module === require.main)
console.error('Listening at http://127.0.0.1:'+port+'/');
});
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple_bench.sh
#!/bin/bash
SERVER=127.0.0.1
PORT=${PORT:=8000}
if [ ! -d benchmark/ ]; then
echo "Run this script from the node root directory"
exit 1
fi
if [ $SERVER == "127.0.0.1" ]; then
./node benchmark/http_simple.js &
node_pid=$!
sleep 1
fi
date=`date "+%Y%m%d%H%M%S"`
ab_hello_world() {
local type="$1"
local ressize="$2"
if [ $type == "string" ]; then
local uri="bytes/$ressize"
else
local uri="buffer/$ressize"
fi
name="ab-hello-world-$type-$ressize"
dir=".benchmark_reports/$name/$rev/"
if [ ! -d $dir ]; then
mkdir -p $dir
fi
summary_fn="$dir/$date.summary"
data_fn="$dir/$date.data"
echo "Bench $name starts in 3 seconds..."
sleep 3
ab -g $data_fn -c 100 -t 10 http://$SERVER:$PORT/$uri > $summary_fn
echo >> $summary_fn
echo >> $summary_fn
echo "webserver-rev: $rev" >> $summary_fn
echo "webserver-uname: $uname" >> $summary_fn
grep Req $summary_fn
echo "Summary: $summary_fn"
echo
}
ab_hello_world 'string' '1024'
ab_hello_world 'buffer' '1024'
ab_hello_world 'string' '102400'
ab_hello_world 'buffer' '102400'
if [ ! -z $node_pid ]; then
kill -9 $node_pid
fi
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple.rb
DIR = File.dirname(__FILE__)
def fib(n)
return 1 if n <= 1
fib(n-1) + fib(n-2)
end
def wait(seconds)
n = (seconds / 0.01).to_i
n.times do
sleep(0.01)
end
end
class SimpleApp
@@responses = {}
def initialize
@count = 0
end
def deferred?(env)
false
end
def call(env)
path = env['PATH_INFO'] || env['REQUEST_URI']
commands = path.split('/')
@count += 1
if commands.include?('periodical_activity') and @count % 10 != 1
return [200, {'Content-Type'=>'text/plain'}, "quick response!\r\n"]
end
if commands.include?('fibonacci')
n = commands.last.to_i
raise "fibonacci called with n <= 0" if n <= 0
body = (1..n).to_a.map { |i| fib(i).to_s }.join(' ')
status = 200
elsif commands.include?('wait')
n = commands.last.to_f
raise "wait called with n <= 0" if n <= 0
wait(n)
body = "waited about #{n} seconds"
status = 200
elsif commands.include?('bytes')
n = commands.last.to_i
raise "bytes called with n <= 0" if n <= 0
body = @@responses[n] || "C"*n
status = 200
elsif commands.include?('fixed')
n = 20 * 1024;
body = @@responses[n] || "C"*n
status = 200
elsif commands.include?('test_post_length')
input_body = ""
while chunk = env['rack.input'].read(512)
input_body << chunk
end
if env['CONTENT_LENGTH'].to_i == input_body.length
body = "Content-Length matches input length"
status = 200
else
body = "Content-Length doesn't matches input length!
content_length = #{env['CONTENT_LENGTH'].to_i}
input_body.length = #{input_body.length}"
status = 500
end
else
status = 404
body = "Undefined url"
end
body += "\r\n"
headers = {'Content-Type' => 'text/plain', 'Content-Length' => body.length.to_s }
[status, headers, [body]]
end
end
if $0 == __FILE__
require 'rubygems'
require 'rack'
require 'thin'
require 'ebb'
Thin::Server.start("0.0.0.0", 8000, SimpleApp.new)
end
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple_auto.js
var path = require("path");
var http = require("http");
var spawn = require("child_process").spawn;
var port = parseInt(process.env.PORT || 8000);
var fixed = ""
for (var i = 0; i < 20*1024; i++) {
fixed += "C";
}
var stored = {};
var storedBuffer = {};
var server = http.createServer(function (req, res) {
var commands = req.url.split("/");
var command = commands[1];
var body = "";
var arg = commands[2];
var n_chunks = parseInt(commands[3], 10);
var status = 200;
if (command == "bytes") {
var n = parseInt(arg, 10)
if (n <= 0)
throw "bytes called with n <= 0"
if (stored[n] === undefined) {
stored[n] = "";
for (var i = 0; i < n; i++) {
stored[n] += "C"
}
}
body = stored[n];
} else if (command == "buffer") {
var n = parseInt(arg, 10)
if (n <= 0) throw new Error("bytes called with n <= 0");
if (storedBuffer[n] === undefined) {
storedBuffer[n] = new Buffer(n);
for (var i = 0; i < n; i++) {
storedBuffer[n][i] = "C".charCodeAt(0);
}
}
body = storedBuffer[n];
} else if (command == "quit") {
res.connection.server.close();
body = "quitting";
} else if (command == "fixed") {
body = fixed;
} else if (command == "echo") {
res.writeHead(200, { "Content-Type": "text/plain",
"Transfer-Encoding": "chunked" });
req.pipe(res);
return;
} else {
status = 404;
body = "not found\n";
}
if (n_chunks > 0) {
res.writeHead(status, { "Content-Type": "text/plain",
"Transfer-Encoding": "chunked" });
var len = body.length;
var step = Math.floor(len / n_chunks) || 1;
for (var i = 0, n = (n_chunks - 1); i < n; ++i) {
res.write(body.slice(i * step, i * step + step));
}
res.end(body.slice((n_chunks - 1) * step));
} else {
var content_length = body.length.toString();
res.writeHead(status, { "Content-Type": "text/plain",
"Content-Length": content_length });
res.end(body);
}
});
server.listen(port, function () {
var url = 'http://127.0.0.1:' + port + '/';
var n = process.argv.length - 1;
process.argv[n] = url + process.argv[n];
var cp = spawn('ab', process.argv.slice(2));
cp.stdout.pipe(process.stdout);
cp.stderr.pipe(process.stderr);
cp.on('exit', function() {
server.close();
process.nextTick(dump_mm_stats);
});
});
function dump_mm_stats() {
if (typeof gc != 'function') return;
var before = process.memoryUsage();
for (var i = 0; i < 10; ++i) gc();
var after = process.memoryUsage();
setTimeout(print_stats, 250);
function print_stats() {
console.log('\nBEFORE / AFTER GC');
['rss', 'heapTotal', 'heapUsed'].forEach(function(key) {
var a = before[key] / (1024 * 1024);
var b = after[key] / (1024 * 1024);
console.log('%sM / %sM %s', a.toFixed(2), b.toFixed(2), key);
});
}
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_server_lag.js
var http = require('http');
var port = parseInt(process.env.PORT, 10) || 8000;
var defaultLag = parseInt(process.argv[2], 10) || 100;
http.createServer(function(req, res) {
res.writeHead(200, { 'content-type': 'text/plain',
'content-length': '2' });
var lag = parseInt(req.url.split("/").pop(), 10) || defaultLag;
setTimeout(function() {
res.end('ok');
}, lag);
}).listen(port, 'localhost');
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple_cluster.js
var cluster = require('cluster');
var os = require('os');
if (cluster.isMaster) {
console.log('master running on pid %d', process.pid);
for (var i = 0, n = os.cpus().length; i < n; ++i) cluster.fork();
} else {
require(__dirname + '/http_simple.js');
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/report-startup-memory.js
console.log(process.memoryUsage().rss);
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/idle_clients.js
net = require('net');
var errors = 0, connections = 0;
var lastClose = 0;
function connect () {
process.nextTick(function () {
var s = net.Stream();
var gotConnected = false;
s.connect(9000);
s.on('connect', function () {
gotConnected = true;
connections++;
connect();
});
s.on('close', function () {
if (gotConnected) connections--;
lastClose = new Date();
});
s.on('error', function () {
errors++;
});
});
}
connect();
var oldConnections, oldErrors;
setInterval(connect, 5000);
setInterval(function () {
if (oldConnections != connections) {
oldConnections = connections;
console.log("CLIENT %d connections: %d", process.pid, connections);
}
if (oldErrors != errors) {
oldErrors = errors;
console.log("CLIENT %d errors: %d", process.pid, errors);
}
}, 1000);
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/plot.R
#!/usr/bin/env Rscript
# To use this script you'll need to install R: http://www.r-project.org/
# and a library for R called ggplot2
# Which can be done by starting R and typing install.packages("ggplot2")
# like this:
#
# shell% R
# R version 2.11.0 beta (2010-04-12 r51689)
# > install.packages("ggplot2")
# (follow prompt)
#
# Then you can try this script by providing a full path to .data file
# outputed from 'make bench'
#
# > cd ~/src/node
# > make bench
# ...
# > ./benchmark/plot.R .benchmark_reports/ab-hello-world-buffer-1024/ff456b38862de3fd0118c6ac6b3f46edb1fbb87f/20101013162056.data
#
# This will generate a PNG file which you can view
#
#
# Hopefully these steps will be automated in the future.
library(ggplot2)
args <- commandArgs(TRUE)
ab.load <- function (filename, name) {
raw <- data.frame(read.csv(filename, sep="\t", header=T), server=name)
raw <- data.frame(raw, time=raw$seconds-min(raw$seconds))
raw <- data.frame(raw, time_s=raw$time/1000000)
raw
}
#ab.tsPoint <- function (d) {
# qplot(time_s, ttime, data=d, facets=server~.,
# geom="point", alpha=I(1/15), ylab="response time (ms)",
# xlab="time (s)", main="c=30, res=26kb",
# ylim=c(0,100))
#}
#
#ab.tsLine <- function (d) {
# qplot(time_s, ttime, data=d, facets=server~.,
# geom="line", ylab="response time (ms)",
# xlab="time (s)", main="c=30, res=26kb",
# ylim=c(0,100))
#}
filename <- args[0:1]
data <- ab.load(filename, "node")
# histogram
#hist_png_filename <- gsub(".data", "_hist.png", filename)
hist_png_filename <- "hist.png"
png(filename = hist_png_filename, width = 480, height = 380, units = "px")
qplot(ttime, data=data, geom="histogram",
main="xxx",
binwidth=1, xlab="response time (ms)",
xlim=c(0,100))
print(hist_png_filename)
# time series
#ts_png_filename <- gsub(".data", "_ts.png", filename)
ts_png_filename = "ts.png"
png(filename = ts_png_filename, width = 480, height = 380, units = "px")
qplot(time, ttime, data=data, facets=server~.,
geom="point", alpha=I(1/15), ylab="response time (ms)",
xlab="time (s)", main="xxx",
ylim=c(0,100))
print(ts_png_filename)
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/io.c
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/time.h>
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
static int c = 0;
static int tsize = 1000 * 1048576;
static const char* path = "/tmp/wt.dat";
static char buf[65536];
static uint64_t now(void) {
struct timeval tv;
if (gettimeofday(&tv, NULL))
abort();
return tv.tv_sec * 1000000ULL + tv.tv_usec;
}
static void writetest(int size, size_t bsize)
{
int i;
uint64_t start, end;
double elapsed;
double mbps;
assert(bsize <= sizeof buf);
int fd = open(path, O_CREAT|O_WRONLY, 0644);
if (fd < 0) {
perror("open failed");
exit(254);
}
start = now();
for (i = 0; i < size; i += bsize) {
int rv = write(fd, buf, bsize);
if (rv < 0) {
perror("write failed");
exit(254);
}
}
#ifndef NSYNC
# ifdef __linux__
fdatasync(fd);
# else
fsync(fd);
# endif
#endif /* SYNC */
close(fd);
end = now();
elapsed = (end - start) / 1e6;
mbps = ((tsize/elapsed)) / 1048576;
fprintf(stderr, "Wrote %d bytes in %03fs using %ld byte buffers: %03f\n", size, elapsed, bsize, mbps);
}
void readtest(int size, size_t bsize)
{
int i;
uint64_t start, end;
double elapsed;
double mbps;
assert(bsize <= sizeof buf);
int fd = open(path, O_RDONLY, 0644);
if (fd < 0) {
perror("open failed");
exit(254);
}
start = now();
for (i = 0; i < size; i += bsize) {
int rv = read(fd, buf, bsize);
if (rv < 0) {
perror("write failed");
exit(254);
}
}
close(fd);
end = now();
elapsed = (end - start) / 1e6;
mbps = ((tsize/elapsed)) / 1048576;
fprintf(stderr, "Read %d bytes in %03fs using %ld byte buffers: %03fmB/s\n", size, elapsed, bsize, mbps);
}
void cleanup() {
unlink(path);
}
int main(int argc, char** argv)
{
int i;
int bsizes[] = {1024, 4096, 8192, 16384, 32768, 65536, 0};
if (argc > 1) path = argv[1];
for (i = 0; bsizes[i] != 0; i++) {
writetest(tsize, bsizes[i]);
}
for (i = 0; bsizes[i] != 0; i++) {
readtest(tsize, bsizes[i]);
}
atexit(cleanup);
return 0;
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/idle_server.js
net = require('net');
connections = 0;
var errors = 0;
server = net.Server(function (socket) {
socket.on('error', function () {
errors++;
});
});
server.listen(9000);
var oldConnections, oldErrors;
setInterval(function () {
if (oldConnections != server.connections) {
oldConnections = server.connections;
console.log("SERVER %d connections: %d", process.pid, server.connections);
}
if (oldErrors != errors) {
oldErrors = errors;
console.log("SERVER %d errors: %d", process.pid, errors);
}
}, 1000);
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/static_http_server.js
var http = require('http');
var concurrency = 30;
var port = 12346;
var n = 700;
var bytes = 1024*5;
var requests = 0;
var responses = 0;
var body = '';
for (var i = 0; i < bytes; i++) {
body += 'C';
}
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Length': body.length
});
res.end(body);
})
server.listen(port, function() {
var agent = new http.Agent();
agent.maxSockets = concurrency;
for (var i = 0; i < n; i++) {
var req = http.get({
port: port,
path: '/',
agent: agent
}, function(res) {
res.resume();
res.on('end', function() {
if (++responses === n) {
server.close();
}
});
});
req.id = i;
requests++;
}
});
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/buffer-creation.js
SlowBuffer = require('buffer').SlowBuffer;
var common = require('../common.js');
var bench = common.createBenchmark(main, {
type: ['fast', 'slow'],
len: [10, 1024],
n: [1024]
});
function main(conf) {
var len = +conf.len;
var n = +conf.n;
var clazz = conf.type === 'fast' ? Buffer : SlowBuffer;
bench.start();
for (var i = 0; i < n * 1024; i++) {
b = new clazz(len);
}
bench.end(n);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/dataview-set.js
var common = require('../common.js');
var bench = common.createBenchmark(main, {
type: ['Uint8', 'Uint16LE', 'Uint16BE',
'Uint32LE', 'Uint32BE',
'Int8', 'Int16LE', 'Int16BE',
'Int32LE', 'Int32BE',
'Float32LE', 'Float32BE',
'Float64LE', 'Float64BE'],
millions: [1]
});
const INT8 = 0x7f;
const INT16 = 0x7fff;
const INT32 = 0x7fffffff;
const UINT8 = INT8 * 2;
const UINT16 = INT16 * 2;
const UINT32 = INT32 * 2;
var mod = {
setInt8: INT8,
setInt16: INT16,
setInt32: INT32,
setUint8: UINT8,
setUint16: UINT16,
setUint32: UINT32
};
function main(conf) {
var len = +conf.millions * 1e6;
var ab = new ArrayBuffer(8);
var dv = new DataView(ab, 0, 8);
var le = /LE$/.test(conf.type);
var fn = 'set' + conf.type.replace(/[LB]E$/, '');
if (/int/i.test(fn))
benchInt(dv, fn, len, le);
else
benchFloat(dv, fn, len, le);
}
function benchInt(dv, fn, len, le) {
var m = mod[fn];
bench.start();
for (var i = 0; i < len; i++) {
dv[fn](0, i % m, le);
}
bench.end(len / 1e6);
}
function benchFloat(dv, fn, len, le) {
bench.start();
for (var i = 0; i < len; i++) {
dv[fn](0, i * 0.1, le);
}
bench.end(len / 1e6);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/buffer-base64-encode.js
// Copyright Joyent, Inc. and other Node contributors.
//
// 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:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// 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.
var common = require('../common.js');
var bench = common.createBenchmark(main, {});
function main(conf) {
var N = 64 * 1024 * 1024;
var b = Buffer(N);
var s = '';
for (var i = 0; i < 256; ++i) s += String.fromCharCode(i);
bench.start();
for (var i = 0; i < N; i += 256) b.write(s, i, 256, 'ascii');
for (var i = 0; i < 32; ++i) b.toString('base64');
bench.end(64);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/buffer-read.js
var common = require('../common.js');
var bench = common.createBenchmark(main, {
noAssert: [false, true],
buffer: ['fast', 'slow'],
type: ['UInt8', 'UInt16LE', 'UInt16BE',
'UInt32LE', 'UInt32BE',
'Int8', 'Int16LE', 'Int16BE',
'Int32LE', 'Int32BE',
'FloatLE', 'FloatBE',
'DoubleLE', 'DoubleBE'],
millions: [1]
});
function main(conf) {
var noAssert = conf.noAssert === 'true';
var len = +conf.millions * 1e6;
var clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer;
var buff = new clazz(8);
var fn = 'read' + conf.type;
buff.writeDoubleLE(0, 0, noAssert);
bench.start();
for (var i = 0; i < len; i++) {
buff[fn](0, noAssert);
}
bench.end(len / 1e6);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/buffer-write.js
var common = require('../common.js');
var bench = common.createBenchmark(main, {
noAssert: [false, true],
buffer: ['fast', 'slow'],
type: ['UInt8', 'UInt16LE', 'UInt16BE',
'UInt32LE', 'UInt32BE',
'Int8', 'Int16LE', 'Int16BE',
'Int32LE', 'Int32BE',
'FloatLE', 'FloatBE',
'DoubleLE', 'DoubleBE'],
millions: [1]
});
const INT8 = 0x7f;
const INT16 = 0x7fff;
const INT32 = 0x7fffffff;
const UINT8 = INT8 * 2;
const UINT16 = INT16 * 2;
const UINT32 = INT32 * 2;
var mod = {
writeInt8: INT8,
writeInt16BE: INT16,
writeInt16LE: INT16,
writeInt32BE: INT32,
writeInt32LE: INT32,
writeUInt8: UINT8,
writeUInt16BE: UINT16,
writeUInt16LE: UINT16,
writeUInt32BE: UINT32,
writeUInt32LE: UINT32
};
function main(conf) {
var noAssert = conf.noAssert === 'true';
var len = +conf.millions * 1e6;
var clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer;
var buff = new clazz(8);
var fn = 'write' + conf.type;
if (fn.match(/Int/))
benchInt(buff, fn, len, noAssert);
else
benchFloat(buff, fn, len, noAssert);
}
function benchInt(buff, fn, len, noAssert) {
var m = mod[fn];
bench.start();
for (var i = 0; i < len; i++) {
buff[fn](i % m, 0, noAssert);
}
bench.end(len / 1e6);
}
function benchFloat(buff, fn, len, noAssert) {
bench.start();
for (var i = 0; i < len; i++) {
buff[fn](i * 0.1, 0, noAssert);
}
bench.end(len / 1e6);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_debugger.js
var util = require('util'),
path = require('path'),
net = require('net'),
vm = require('vm'),
repl = require('repl'),
inherits = util.inherits,
spawn = require('child_process').spawn;
exports.start = function(argv, stdin, stdout) {
argv || (argv = process.argv.slice(2));
if (argv.length < 1) {
console.error('Usage: node debug script.js');
process.exit(1);
}
stdin = stdin || process.stdin;
stdout = stdout || process.stdout;
var args = ['--debug-brk'].concat(argv),
interface_ = new Interface(stdin, stdout, args);
stdin.resume();
process.on('uncaughtException', function(e) {
console.error("There was an internal error in Node's debugger. " +
'Please report this bug.');
console.error(e.message);
console.error(e.stack);
if (interface_.child) interface_.child.kill();
process.exit(1);
});
};
exports.port = 5858;
function Protocol() {
this._newRes();
}
exports.Protocol = Protocol;
Protocol.prototype._newRes = function(raw) {
this.res = { raw: raw || '', headers: {} };
this.state = 'headers';
this.reqSeq = 1;
this.execute('');
};
Protocol.prototype.execute = function(d) {
var res = this.res;
res.raw += d;
switch (this.state) {
case 'headers':
var endHeaderIndex = res.raw.indexOf('\r\n\r\n');
if (endHeaderIndex < 0) break;
var rawHeader = res.raw.slice(0, endHeaderIndex);
var endHeaderByteIndex = Buffer.byteLength(rawHeader, 'utf8');
var lines = rawHeader.split('\r\n');
for (var i = 0; i < lines.length; i++) {
var kv = lines[i].split(/: +/);
res.headers[kv[0]] = kv[1];
}
this.contentLength = +res.headers['Content-Length'];
this.bodyStartByteIndex = endHeaderByteIndex + 4;
this.state = 'body';
var len = Buffer.byteLength(res.raw, 'utf8');
if (len - this.bodyStartByteIndex < this.contentLength) {
break;
}
case 'body':
var resRawByteLength = Buffer.byteLength(res.raw, 'utf8');
if (resRawByteLength - this.bodyStartByteIndex >= this.contentLength) {
var buf = new Buffer(resRawByteLength);
buf.write(res.raw, 0, resRawByteLength, 'utf8');
res.body =
buf.slice(this.bodyStartByteIndex,
this.bodyStartByteIndex +
this.contentLength).toString('utf8');
res.body = res.body.length ? JSON.parse(res.body) : {};
this.onResponse(res);
this._newRes(buf.slice(this.bodyStartByteIndex +
this.contentLength).toString('utf8'));
}
break;
default:
throw new Error('Unknown state');
break;
}
};
Protocol.prototype.serialize = function(req) {
req.type = 'request';
req.seq = this.reqSeq++;
var json = JSON.stringify(req);
return 'Content-Length: ' + Buffer.byteLength(json, 'utf8') +
'\r\n\r\n' + json;
};
var NO_FRAME = -1;
function Client() {
net.Stream.call(this);
var protocol = this.protocol = new Protocol(this);
this._reqCallbacks = [];
var socket = this;
this.currentFrame = NO_FRAME;
this.currentSourceLine = -1;
this.currentSource = null;
this.handles = {};
this.scripts = {};
this.breakpoints = [];
socket.setEncoding('utf8');
socket.on('data', function(d) {
protocol.execute(d);
});
protocol.onResponse = this._onResponse.bind(this);
}
inherits(Client, net.Stream);
exports.Client = Client;
Client.prototype._addHandle = function(desc) {
if (typeof desc != 'object' || typeof desc.handle != 'number') {
return;
}
this.handles[desc.handle] = desc;
if (desc.type == 'script') {
this._addScript(desc);
}
};
var natives = process.binding('natives');
Client.prototype._addScript = function(desc) {
this.scripts[desc.id] = desc;
if (desc.name) {
desc.isNative = (desc.name.replace('.js', '') in natives) ||
desc.name == 'node.js';
}
};
Client.prototype._removeScript = function(desc) {
this.scripts[desc.id] = undefined;
};
Client.prototype._onResponse = function(res) {
var cb,
index = -1;
this._reqCallbacks.some(function(fn, i) {
if (fn.request_seq == res.body.request_seq) {
cb = fn;
index = i;
return true;
}
});
var self = this;
var handled = false;
if (res.headers.Type == 'connect') {
self.reqScripts();
self.emit('ready');
handled = true;
} else if (res.body && res.body.event == 'break') {
this.emit('break', res.body);
handled = true;
} else if (res.body && res.body.event == 'exception') {
this.emit('exception', res.body);
handled = true;
} else if (res.body && res.body.event == 'afterCompile') {
this._addHandle(res.body.body.script);
handled = true;
} else if (res.body && res.body.event == 'scriptCollected') {
this._removeScript(res.body.body.script);
handled = true;
}
if (cb) {
this._reqCallbacks.splice(index, 1);
handled = true;
var err = res.success === false && (res.message || true) ||
res.body.success === false && (res.body.message || true);
cb(err, res.body && res.body.body || res.body, res);
}
if (!handled) this.emit('unhandledResponse', res.body);
};
Client.prototype.req = function(req, cb) {
this.write(this.protocol.serialize(req));
cb.request_seq = req.seq;
this._reqCallbacks.push(cb);
};
Client.prototype.reqVersion = function(cb) {
cb = cb || function() {};
this.req({ command: 'version' } , function(err, body, res) {
if (err) return cb(err);
cb(null, res.body.body.V8Version, res.body.running);
});
};
Client.prototype.reqLookup = function(refs, cb) {
var self = this;
var req = {
command: 'lookup',
arguments: {
handles: refs
}
};
cb = cb || function() {};
this.req(req, function(err, res) {
if (err) return cb(err);
for (var ref in res) {
if (typeof res[ref] == 'object') {
self._addHandle(res[ref]);
}
}
cb(null, res);
});
};
Client.prototype.reqScopes = function(cb) {
var self = this,
req = {
command: 'scopes',
arguments: {}
};
cb = cb || function() {};
this.req(req, function(err, res) {
if (err) return cb(err);
var refs = res.scopes.map(function(scope) {
return scope.object.ref;
});
self.reqLookup(refs, function(err, res) {
if (err) return cb(err);
var globals = Object.keys(res).map(function(key) {
return res[key].properties.map(function(prop) {
return prop.name;
});
});
cb(null, globals.reverse());
});
});
};
Client.prototype.reqEval = function(expression, cb) {
var self = this;
if (this.currentFrame == NO_FRAME) {
this.reqFrameEval(expression, NO_FRAME, cb);
return;
}
cb = cb || function() {};
this.reqBacktrace(function(err, bt) {
if (err || !bt.frames) {
return cb(null, {});
}
var frame = bt.frames[self.currentFrame];
var evalFrames = frame.scopes.map(function(s) {
if (!s) return;
var x = bt.frames[s.index];
if (!x) return;
return x.index;
});
self._reqFramesEval(expression, evalFrames, cb);
});
};
Client.prototype._reqFramesEval = function(expression, evalFrames, cb) {
if (evalFrames.length == 0) {
this.reqFrameEval(expression, NO_FRAME, cb);
return;
}
var self = this;
var i = evalFrames.shift();
cb = cb || function() {};
this.reqFrameEval(expression, i, function(err, res) {
if (!err) return cb(null, res);
self._reqFramesEval(expression, evalFrames, cb);
});
};
Client.prototype.reqFrameEval = function(expression, frame, cb) {
var self = this;
var req = {
command: 'evaluate',
arguments: { expression: expression }
};
if (frame == NO_FRAME) {
req.arguments.global = true;
} else {
req.arguments.frame = frame;
}
cb = cb || function() {};
this.req(req, function(err, res) {
if (!err) self._addHandle(res);
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_linklist.js
function init(list) {
list._idleNext = list;
list._idlePrev = list;
}
exports.init = init;
function peek(list) {
if (list._idlePrev == list) return null;
return list._idlePrev;
}
exports.peek = peek;
function shift(list) {
var first = list._idlePrev;
remove(first);
return first;
}
exports.shift = shift;
function remove(item) {
if (item._idleNext) {
item._idleNext._idlePrev = item._idlePrev;
}
if (item._idlePrev) {
item._idlePrev._idleNext = item._idleNext;
}
item._idleNext = null;
item._idlePrev = null;
}
exports.remove = remove;
function append(list, item) {
remove(item);
item._idleNext = list._idleNext;
list._idleNext._idlePrev = item;
item._idlePrev = list;
list._idleNext = item;
}
exports.append = append;
function isEmpty(list) {
return list._idleNext === list;
}
exports.isEmpty = isEmpty;
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_transform.js
module.exports = Transform;
var Duplex = require('_stream_duplex');
var util = require('util');
util.inherits(Transform, Duplex);
function TransformState(options, stream) {
this.afterTransform = function(er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined)
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
Duplex.call(this, options);
var ts = this._transformState = new TransformState(options, this);
var stream = this;
this._readableState.needReadable = true;
this._readableState.sync = false;
this.once('finish', function() {
if ('function' === typeof this._flush)
this._flush(function(er) {
done(stream, er);
});
else
done(stream);
});
}
Transform.prototype.push = function(chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
Transform.prototype._transform = function(chunk, encoding, cb) {
throw new Error('not implemented');
};
Transform.prototype._write = function(chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform ||
rs.needReadable ||
rs.length < rs.highWaterMark)
this._read(rs.highWaterMark);
}
};
Transform.prototype._read = function(n) {
var ts = this._transformState;
if (ts.writechunk && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
var ws = stream._writableState;
var rs = stream._readableState;
var ts = stream._transformState;
if (ws.length)
throw new Error('calling transform done when ws.length != 0');
if (ts.transforming)
throw new Error('calling transform done when still transforming');
return stream.push(null);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_readable.js
module.exports = Readable;
Readable.ReadableState = ReadableState;
var EE = require('events').EventEmitter;
var Stream = require('stream');
var util = require('util');
var StringDecoder;
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
options = options || {};
var hwm = options.highWaterMark;
this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = false;
this.ended = false;
this.endEmitted = false;
this.reading = false;
this.calledRead = false;
this.sync = true;
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.objectMode = !!options.objectMode;
this.defaultEncoding = options.defaultEncoding || 'utf8';
this.ranOut = false;
this.awaitDrain = 0;
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder)
StringDecoder = require('string_decoder').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
this.readable = true;
Stream.call(this);
}
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (typeof chunk === 'string' && !state.objectMode) {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
Readable.prototype.unshift = function(chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (chunk === null || chunk === undefined) {
state.reading = false;
if (!state.ended)
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var e = new Error('stream.unshift() after end event');
stream.emit('error', e);
} else {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) {
state.buffer.unshift(chunk);
} else {
state.reading = false;
state.buffer.push(chunk);
}
if (state.needReadable)
emitReadable(stream);
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
};
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
n--;
for (var p = 1; p < 32; p <<= 1) n |= n >> p;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended)
return 0;
if (state.objectMode)
return n === 0 ? 0 : 1;
if (isNaN(n) || n === null) {
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;
if (n > state.highWaterMark)
state.highWaterMark = roundUpToNextPowerOf2(n);
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else
return state.length;
}
return n;
}
Readable.prototype.read = function(n) {
var state = this._readableState;
state.calledRead = true;
var nOrig = n;
if (typeof n !== 'number' || n > 0)
state.emittedReadable = false;
if (n === 0 &&
state.needReadable &&
(state.length >= state.highWaterMark || state.ended)) {
emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
if (n === 0 && state.ended) {
if (state.length === 0)
endReadable(this);
return null;
}
var doRead = state.needReadable;
if (state.length - n <= state.highWaterMark)
doRead = true;
if (state.ended || state.reading)
doRead = false;
if (doRead) {
state.reading = true;
state.sync = true;
if (state.length === 0)
state.needReadable = true;
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_passthrough.js
// Copyright Joyent, Inc. and other Node contributors.
//
// 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:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// 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.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = require('_stream_transform');
var util = require('util');
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_duplex.js
module.exports = Duplex;
var util = require('util');
var Readable = require('_stream_readable');
var Writable = require('_stream_writable');
util.inherits(Duplex, Readable);
Object.keys(Writable.prototype).forEach(function(method) {
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
});
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
function onend() {
if (this.allowHalfOpen || this._writableState.ended)
return;
process.nextTick(this.end.bind(this));
}
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_writable.js
module.exports = Writable;
Writable.WritableState = WritableState;
var util = require('util');
var assert = require('assert');
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
options = options || {};
var hwm = options.highWaterMark;
this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
this.objectMode = !!options.objectMode;
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
this.ending = false;
this.ended = false;
this.finished = false;
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
this.defaultEncoding = options.defaultEncoding || 'utf8';
this.length = 0;
this.writing = false;
this.sync = true;
this.bufferProcessing = false;
this.onwrite = function(er) {
onwrite(stream, er);
};
this.writecb = null;
this.writelen = 0;
this.buffer = [];
}
function Writable(options) {
if (!(this instanceof Writable) && !(this instanceof Stream.Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
this.writable = true;
Stream.call(this);
}
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!Buffer.isBuffer(chunk) &&
'string' !== typeof chunk &&
chunk !== null &&
chunk !== undefined &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (Buffer.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (typeof cb !== 'function')
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb))
ret = writeOrBuffer(this, state, chunk, encoding, cb);
return ret;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
state.needDrain = !ret;
if (state.writing)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
cb(er);
});
else
cb(er);
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
var finished = needFinish(stream, state);
if (!finished && !state.bufferProcessing && state.buffer.length)
clearBuffer(stream, state);
if (sync) {
process.nextTick(function() {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
cb();
if (finished)
finishMaybe(stream, state);
}
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
function clearBuffer(stream, state) {
state.bufferProcessing = true;
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, len, chunk, encoding, cb);
if (state.writing) {
c++;
break;
}
}
state.bufferProcessing = false;
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (typeof chunk !== 'undefined' && chunk !== null)
this.write(chunk, encoding);
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
state.finished = true;
stream.emit('finish');
}
return need;
}
function endWritable(strea
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/assert.js
var util = require('util');
var pSlice = Array.prototype.slice;
var assert = module.exports = ok;
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
this.message = options.message || getMessage(this);
var stackStartFunction = options.stackStartFunction || fail;
Error.captureStackTrace(this, stackStartFunction);
};
util.inherits(assert.AssertionError, Error);
function replacer(key, value) {
if (value === undefined) {
return '' + value;
}
if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {
return value.toString();
}
if (typeof value === 'function' || value instanceof RegExp) {
return value.toString();
}
return value;
}
function truncate(s, n) {
if (typeof s == 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function getMessage(self) {
return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
self.operator + ' ' +
truncate(JSON.stringify(self.expected, replacer), 128);
}
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
assert.fail = fail;
function ok(value, message) {
if (!!!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
function _deepEqual(actual, expected) {
if (actual === expected) {
return true;
} else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
} else if (actual instanceof RegExp && expected instanceof RegExp) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
} else if (typeof actual != 'object' && typeof expected != 'object') {
return actual == expected;
} else {
return objEquiv(actual, expected);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b) {
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
if (a.prototype !== b.prototype) return false;
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
try {
var ka = Object.keys(a),
kb = Object.keys(b),
key, i;
} catch (e) {
return false;
}
if (ka.length != kb.length)
return false;
ka.sort();
kb.sort();
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}
return false;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof expected === 'string') {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
if (!shouldThrow && expectedException(actual, expected)) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!s
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/child_process.js
var StringDecoder = require('string_decoder').StringDecoder;
var EventEmitter = require('events').EventEmitter;
var net = require('net');
var dgram = require('dgram');
var Process = process.binding('process_wrap').Process;
var assert = require('assert');
var util = require('util');
var constants;
var handleWraps = {};
function handleWrapGetter(name, callback) {
var cons;
Object.defineProperty(handleWraps, name, {
get: function() {
if (cons !== undefined) return cons;
return cons = callback();
}
});
}
handleWrapGetter('Pipe', function() {
return process.binding('pipe_wrap').Pipe;
});
handleWrapGetter('TTY', function() {
return process.binding('tty_wrap').TTY;
});
handleWrapGetter('TCP', function() {
return process.binding('tcp_wrap').TCP;
});
handleWrapGetter('UDP', function() {
return process.binding('udp_wrap').UDP;
});
function createPipe(ipc) {
return new handleWraps.Pipe(ipc);
}
function createSocket(pipe, readable) {
var s = new net.Socket({ handle: pipe });
if (readable) {
s.writable = false;
s.readable = true;
} else {
s.writable = true;
s.readable = false;
}
return s;
}
var handleConversion = {
'net.Native': {
simultaneousAccepts: true,
send: function(message, handle) {
return handle;
},
got: function(message, handle, emit) {
emit(handle);
}
},
'net.Server': {
simultaneousAccepts: true,
send: function(message, server) {
return server._handle;
},
got: function(message, handle, emit) {
var self = this;
var server = new net.Server();
server.listen(handle, function() {
emit(server);
});
}
},
'net.Socket': {
send: function(message, socket) {
if (socket.server) {
message.key = socket.server._connectionKey;
var firstTime = !this._channel.sockets.send[message.key];
var socketList = getSocketList('send', this, message.key);
if (firstTime) socket.server._setupSlave(socketList);
socket.server._connections--;
}
var handle = socket._handle;
handle.onread = function() {};
socket._handle = null;
return handle;
},
postSend: function(handle) {
handle.close();
},
got: function(message, handle, emit) {
var socket = new net.Socket({handle: handle});
socket.readable = socket.writable = true;
if (message.key) {
var socketList = getSocketList('got', this, message.key);
socketList.add({
socket: socket
});
}
emit(socket);
}
},
'dgram.Native': {
simultaneousAccepts: false,
send: function(message, handle) {
return handle;
},
got: function(message, handle, emit) {
emit(handle);
}
},
'dgram.Socket': {
simultaneousAccepts: false,
send: function(message, socket) {
message.dgramType = socket.type;
return socket._handle;
},
got: function(message, handle, emit) {
var socket = new dgram.Socket(message.dgramType);
socket.bind(handle, function() {
emit(socket);
});
}
}
};
function SocketListSend(slave, key) {
EventEmitter.call(this);
var self = this;
this.key = key;
this.slave = slave;
}
util.inherits(SocketListSend, EventEmitter);
SocketListSend.prototype._request = function(msg, cmd, callback) {
var self = this;
if (!this.slave.connected) return onclose();
this.slave.send(msg);
function onclose() {
self.slave.removeListener('internalMessage', onreply);
callback(new Error('Slave closed before reply'));
};
function onreply(msg) {
if (!(msg.cmd === cmd && msg.key === self.key)) return;
self.slave.removeListener('disconnect', onclose);
self.slave.removeListener('internalMessage', onreply);
callback(null, msg);
};
this.slave.once('disconnect', onclose);
this.slave.on('internalMessage', onreply);
};
SocketListSend.prototype.close = function close(callback) {
this._request({
cmd: 'NODE_SOCKET_NOTIFY_CLOSE',
key: this.key
}, 'NODE_SOCKET_ALL_CLOSED', callback);
};
SocketListSend.prototype.getConnections = function getConnections(callback) {
this._request({
cmd: 'NODE_SOCKET_GET_COUNT',
key: this.key
}, 'NODE_SOCKET_COUNT', function(err, msg) {
if (err) return callback(err);
callback(null, msg.count);
});
};
function SocketListReceive(slave, key) {
EventEmitter.call(this);
var self = this;
this.connections = 0;
this.key = key;
this.slave = slave;
function onempty() {
if (!self.slave.connected) return;
self.slave.send({
cmd: 'NODE_SOCKET_ALL_CLOSED',
key: self.key
});
}
this.slave.on('internalMessage', function(msg) {
if (msg.key !== self.key) return;
if (msg.cmd === 'NODE_SOCKET_NOTIFY_CLOSE') {
if (self.connections === 0) return onempty();
self.once('empty', onempty);
} else if (msg.cmd === 'NODE_SOCKET_GET_COUNT') {
if (!self.slave.connected) return;
self.slave.send({
cmd: 'NODE_SOCKET_COUNT',
key: self.key,
count: self.connections
});
}
});
}
util.inherits(SocketListReceive, EventEmitter);
SocketListReceive.prototype.add = function(obj) {
var self = this;
this.connections++;
obj.socket.once('close', function() {
self.connections--;
if (self.connections === 0) self.emit('empty');
});
};
function getSocketList(type, slave, key) {
var sockets = slave._channel.sockets[type];
var socketList = sockets[key];
if (!socketList) {
var Construct = type === 'send' ? SocketListSend : SocketListReceive;
socketList = sockets[key] = new Construct(slave, key);
}
return socketList;
}
var INTERNAL_PREFIX = 'NODE_';
function handleMessage(target, message, handle) {
var eventName = 'message';
if (message !== null &&
typeof message === 'object' &&
typeof message.cmd === 'string' &&
message.cmd.length > INTERNAL_PREFIX.length &&
message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) {
eventName = 'internalMessage';
}
target.emit(eventName, message, handle);
}
function setupChannel(target, channel) {
target._channel = channel;
target._handleQueue = null;
var decoder = new StringDecoder('utf8');
var jsonBuffer = '';
channel.buffering = false;
channel.onread = function(pool, offset, length, recvHandle) {
if (pool) {
jsonBuffer += decoder.write(pool.slice(offset, offset + length));
var i, start = 0;
while ((i = jsonBuffer.indexOf('\n', start)) >= 0) {
var json = jsonBuffer.slice(start, i);
var message = JSON.parse(json);
if (message && message.cmd === 'NODE_HANDLE')
handleMessage(target, message, recvHandle);
else
handleMessage(target, message, undefined);
start = i + 1;
}
jsonBuffer = jsonBuffer.slice(start);
this.buffering = jsonBuffer.length !== 0;
} else {
this.buffering = false;
target.disconnect();
channel.onread = nop;
channel.close();
maybeClose(target);
}
};
channel.sockets = { got: {}, send: {} };
target.on('internalMessage', function(message, handle) {
if (message.cmd === 'NODE_HANDLE_ACK') {
assert(Array.isArray(target._handleQueue));
var queue = target._handleQueue;
target._handleQueue = null;
queue.forEach(function(args) {
target.send(args.message, args.handle);
});
return;
}
if (message.cmd !== 'NODE_HANDLE') return;
target.send({ cmd: 'NODE_HANDLE_ACK' });
var obj = handleConversion[me
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/console.js
var util = require('util');
function Console(stdout, stderr) {
if (!(this instanceof Console)) {
return new Console(stdout, stderr);
}
if (!stdout || typeof stdout.write !== 'function') {
throw new TypeError('Console expects a writable stream instance');
}
if (!stderr) {
stderr = stdout;
}
var prop = {
writable: true,
enumerable: false,
configurable: true
};
prop.value = stdout;
Object.defineProperty(this, '_stdout', prop);
prop.value = stderr;
Object.defineProperty(this, '_stderr', prop);
prop.value = {};
Object.defineProperty(this, '_times', prop);
Object.keys(Console.prototype).forEach(function(k) {
this[k] = this[k].bind(this);
}, this);
}
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};
Console.prototype.info = Console.prototype.log;
Console.prototype.warn = function() {
this._stderr.write(util.format.apply(this, arguments) + '\n');
};
Console.prototype.error = Console.prototype.warn;
Console.prototype.dir = function(object) {
this._stdout.write(util.inspect(object) + '\n');
};
Console.prototype.time = function(label) {
this._times[label] = Date.now();
};
Console.prototype.timeEnd = function(label) {
var time = this._times[label];
if (!time) {
throw new Error('No such label: ' + label);
}
var duration = Date.now() - time;
this.log('%s: %dms', label, duration);
};
Console.prototype.trace = function() {
var err = new Error;
err.name = 'Trace';
err.message = util.format.apply(this, arguments);
Error.captureStackTrace(err, arguments.callee);
this.error(err.stack);
};
Console.prototype.assert = function(expression) {
if (!expression) {
var arr = Array.prototype.slice.call(arguments, 1);
require('assert').ok(false, util.format.apply(this, arr));
}
};
module.exports = new Console(process.stdout, process.stderr);
module.exports.Console = Console;
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/buffer.js
var SlowBuffer = process.binding('buffer').SlowBuffer;
var assert = require('assert');
exports.INSPECT_MAX_BYTES = 50;
SlowBuffer.prototype.__proto__ = Buffer.prototype;
function clamp(index, len, defaultValue) {
if (typeof index !== 'number') return defaultValue;
index = ~~index;
if (index >= len) return len;
if (index >= 0) return index;
index += len;
if (index >= 0) return index;
return 0;
}
function toHex(n) {
if (n < 16) return '0' + n.toString(16);
return n.toString(16);
}
SlowBuffer.prototype.toString = function(encoding, start, end) {
encoding = String(encoding || 'utf8').toLowerCase();
start = +start || 0;
if (typeof end !== 'number') end = this.length;
if (+end == start) {
return '';
}
switch (encoding) {
case 'hex':
return this.hexSlice(start, end);
case 'utf8':
case 'utf-8':
return this.utf8Slice(start, end);
case 'ascii':
return this.asciiSlice(start, end);
case 'binary':
return this.binarySlice(start, end);
case 'base64':
return this.base64Slice(start, end);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return this.ucs2Slice(start, end);
default:
throw new TypeError('Unknown encoding: ' + encoding);
}
};
SlowBuffer.prototype.write = function(string, offset, length, encoding) {
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length;
length = undefined;
}
} else {
var swap = encoding;
encoding = offset;
offset = length;
length = swap;
}
offset = +offset || 0;
var remaining = this.length - offset;
if (!length) {
length = remaining;
} else {
length = +length;
if (length > remaining) {
length = remaining;
}
}
encoding = String(encoding || 'utf8').toLowerCase();
switch (encoding) {
case 'hex':
return this.hexWrite(string, offset, length);
case 'utf8':
case 'utf-8':
return this.utf8Write(string, offset, length);
case 'ascii':
return this.asciiWrite(string, offset, length);
case 'binary':
return this.binaryWrite(string, offset, length);
case 'base64':
return this.base64Write(string, offset, length);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return this.ucs2Write(string, offset, length);
default:
throw new TypeError('Unknown encoding: ' + encoding);
}
};
SlowBuffer.prototype.slice = function(start, end) {
var len = this.length;
start = clamp(start, len, 0);
end = clamp(end, len, len);
return new Buffer(this, end - start, start);
};
var zeroBuffer = new SlowBuffer(0);
function Buffer(subject, encoding, offset) {
if (!(this instanceof Buffer)) {
return new Buffer(subject, encoding, offset);
}
var type;
if (typeof offset === 'number') {
if (!Buffer.isBuffer(subject)) {
throw new TypeError('First argument must be a Buffer when slicing');
}
this.length = +encoding > 0 ? Math.ceil(encoding) : 0;
this.parent = subject.parent ? subject.parent : subject;
this.offset = offset;
} else {
switch (type = typeof subject) {
case 'number':
this.length = +subject > 0 ? Math.ceil(subject) : 0;
break;
case 'string':
this.length = Buffer.byteLength(subject, encoding);
break;
case 'object':
this.length = +subject.length > 0 ? Math.ceil(subject.length) : 0;
break;
default:
throw new TypeError('First argument needs to be a number, ' +
'array or string.');
}
if (this.length > Buffer.poolSize) {
this.parent = new SlowBuffer(this.length);
this.offset = 0;
} else if (this.length > 0) {
if (!pool || pool.length - pool.used < this.length) allocPool();
this.parent = pool;
this.offset = pool.used;
pool.used = (pool.used + this.length + 7) & ~7;
} else {
this.parent = zeroBuffer;
this.offset = 0;
}
if (typeof subject !== 'number') {
if (type === 'string') {
this.length = this.write(subject, 0, encoding);
} else if (Buffer.isBuffer(subject)) {
if (subject.parent)
subject.parent.copy(this.parent,
this.offset,
subject.offset,
this.length + subject.offset);
else
subject.copy(this.parent, this.offset, 0, this.length);
} else if (isArrayIsh(subject)) {
for (var i = 0; i < this.length; i++)
this.parent[i + this.offset] = subject[i];
}
}
}
SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length);
}
function isArrayIsh(subject) {
return Array.isArray(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number';
}
exports.SlowBuffer = SlowBuffer;
exports.Buffer = Buffer;
Buffer.isEncoding = function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
case 'raw':
return true;
default:
return false;
}
};
Buffer.poolSize = 8 * 1024;
var pool;
function allocPool() {
pool = new SlowBuffer(Buffer.poolSize);
pool.used = 0;
}
Buffer.isBuffer = function isBuffer(b) {
return b instanceof Buffer;
};
Buffer.prototype.inspect = function inspect() {
var out = [],
len = this.length,
name = this.constructor.name;
for (var i = 0; i < len; i++) {
out[i] = toHex(this[i]);
if (i == exports.INSPECT_MAX_BYTES) {
out[i + 1] = '...';
break;
}
}
return '<' + name + ' ' + out.join(' ') + '>';
};
Buffer.prototype.get = function get(offset) {
if (offset < 0 || offset >= this.length)
throw new RangeError('offset is out of bounds');
return this.parent[this.offset + offset];
};
Buffer.prototype.set = function set(offset, v) {
if (offset < 0 || offset >= this.length)
throw new RangeError('offset is out of bounds');
return this.parent[this.offset + offset] = v;
};
Buffer.prototype.write = function(string, offset, length, encoding) {
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length;
length = undefined;
}
} else {
var swap = encoding;
encoding = offset;
offset = length;
length = swap;
}
offset = +offset || 0;
var remaining = this.length - offset;
if (!length) {
length = remaining;
} else {
length = +length;
if (length > remaining) {
length = remaining;
}
}
encoding = String(encoding || 'utf8').toLowerCase();
if (string.length > 0 && (length < 0 || offset < 0))
throw new RangeError('attempt to write beyond buffer bounds');
var ret;
switch (encoding) {
case 'hex':
ret = this.parent.hexWrite(string, this.offset + offset, length);
break;
case 'utf8':
case 'utf-8':
ret = this.parent.utf8Write(string, this.offset + offset, length);
break;
case 'ascii':
ret = this.parent.asciiWrite(string, this.offset + offset, length);
break;
case 'binary':
ret = this.parent.binaryWrite(string, this.offset + offset, length);
break;
case 'base64':
ret = this.parent.base64Write(string, this.offset + offset, length);
break;
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = this.parent.ucs2Write(string, this.offset + offset, length);
break;
default:
throw new TypeError('Unknown encoding: ' + encoding);
}
Buffer._charsWritten = SlowBuffer._charsWritten;
return ret;
};
Buffer.prototype.toJSON = function() {
return Array.prototype.slice.call(this, 0);
};
Buffer.prototype.toString = function(encoding, start, end) {
encoding = String(encoding || 'utf8').toLowerCase();
if (typeof start !== 'number' || start < 0) {
start = 0;
}
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/cluster.js
var assert = require('assert');
var fork = require('child_process').fork;
var net = require('net');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
function isObject(o) {
return (typeof o === 'object' && o !== null);
}
var debug;
if (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) {
debug = function(x) {
var prefix = process.pid + ',' +
(process.env.NODE_UNIQUE_ID ? 'Worker' : 'Master');
console.error(prefix, x);
};
} else {
debug = function() { };
}
function Cluster() {
EventEmitter.call(this);
}
util.inherits(Cluster, EventEmitter);
var cluster = module.exports = new Cluster();
var masterStarted = false;
var ids = 0;
var serverHandlers = {};
var serverListeners = {};
var queryIds = 0;
var queryCallbacks = {};
cluster.isWorker = 'NODE_UNIQUE_ID' in process.env;
cluster.isMaster = ! cluster.isWorker;
cluster.worker = cluster.isWorker ? {} : null;
cluster.workers = cluster.isMaster ? {} : null;
var settings = cluster.settings = {};
function eachWorker(cb) {
for (var id in cluster.workers) {
if (cluster.workers.hasOwnProperty(id)) {
cb(cluster.workers[id]);
}
}
}
function ProgressTracker(missing, callback) {
this.missing = missing;
this.callback = callback;
}
ProgressTracker.prototype.done = function() {
this.missing -= 1;
this.check();
};
ProgressTracker.prototype.check = function() {
if (this.missing === 0) this.callback();
};
cluster.setupMaster = function(options) {
assert(cluster.isMaster);
if (masterStarted) return;
masterStarted = true;
options = options || {};
var execArgv = options.execArgv || process.execArgv;
if (execArgv.some(function(s) { return /^--prof/.test(s); }) &&
!execArgv.some(function(s) { return /^--logfile=/.test(s); }))
{
execArgv = execArgv.slice();
execArgv.push('--logfile=v8-%p.log');
}
settings = cluster.settings = {
exec: options.exec || process.argv[1],
execArgv: execArgv,
args: options.args || process.argv.slice(2),
silent: options.silent || false
};
cluster.emit('setup');
};
var INTERNAL_PREFIX = 'NODE_CLUSTER_';
function isInternalMessage(message) {
return isObject(message) &&
typeof message.cmd === 'string' &&
message.cmd.length > INTERNAL_PREFIX.length &&
message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX;
}
function internalMessage(inMessage) {
var outMessage = util._extend({}, inMessage);
outMessage.cmd = INTERNAL_PREFIX + (outMessage.cmd || '');
return outMessage;
}
function handleResponse(outMessage, outHandle, inMessage, inHandle, worker) {
var message = internalMessage(outMessage);
message._queryEcho = inMessage._requestEcho;
if (inMessage._queryEcho) {
queryCallbacks[inMessage._queryEcho](inMessage.content, inHandle);
delete queryCallbacks[inMessage._queryEcho];
}
if (!(outMessage === undefined && message._queryEcho === undefined)) {
sendInternalMessage(worker, message, outHandle);
}
}
var messageHandler = {};
function handleMessage(worker, inMessage, inHandle) {
var message = util._extend({}, inMessage);
message.cmd = inMessage.cmd.substr(INTERNAL_PREFIX.length);
var respondUsed = false;
function respond(outMessage, outHandler) {
respondUsed = true;
handleResponse(outMessage, outHandler, inMessage, inHandle, worker);
}
if (messageHandler[message.cmd]) {
messageHandler[message.cmd](message, worker, respond);
}
if (respondUsed === false) {
respond();
}
}
if (cluster.isMaster) {
messageHandler.online = function(message, worker) {
worker.state = 'online';
debug('Worker ' + worker.process.pid + ' online');
worker.emit('online');
cluster.emit('online', worker);
};
messageHandler.queryServer = function(message, worker, send) {
var args = [message.address,
message.port,
message.addressType,
message.fd];
var key = args.join(':');
var handler;
if (serverHandlers.hasOwnProperty(key)) {
handler = serverHandlers[key];
} else if (message.addressType === 'udp4' ||
message.addressType === 'udp6') {
var dgram = require('dgram');
handler = dgram._createSocketHandle.apply(net, args);
serverHandlers[key] = handler;
} else {
handler = net._createServerHandle.apply(net, args);
serverHandlers[key] = handler;
}
send({}, handler);
};
messageHandler.listening = function(message, worker) {
worker.state = 'listening';
worker.emit('listening', {
address: message.address,
port: message.port,
addressType: message.addressType,
fd: message.fd
});
cluster.emit('listening', worker, {
address: message.address,
port: message.port,
addressType: message.addressType,
fd: message.fd
});
};
messageHandler.suicide = function(message, worker) {
worker.suicide = true;
};
}
else if (cluster.isWorker) {
messageHandler.disconnect = function(message, worker) {
worker.disconnect();
};
}
function toDecInt(value) {
value = parseInt(value, 10);
return isNaN(value) ? null : value;
}
function Worker(customEnv) {
if (!(this instanceof Worker)) return new Worker();
EventEmitter.call(this);
var self = this;
var env = process.env;
this.id = cluster.isMaster ? ++ids : toDecInt(env.NODE_UNIQUE_ID);
this.workerID = this.uniqueID = this.id;
this.state = 'none';
if (cluster.isMaster) {
var envCopy = util._extend({}, env);
envCopy['NODE_UNIQUE_ID'] = this.id;
if (isObject(customEnv)) {
envCopy = util._extend(envCopy, customEnv);
}
this.process = fork(settings.exec, settings.args, {
'env': envCopy,
'silent': settings.silent,
'execArgv': settings.execArgv
});
} else {
this.process = process;
}
if (cluster.isMaster) {
cluster.workers[this.id] = this;
process.nextTick(function() {
cluster.emit('fork', self);
});
}
this.process.on('internalMessage', handleMessage.bind(null, this));
this.process.once('exit', function(exitCode, signalCode) {
prepareExit(self, 'dead');
self.emit('exit', exitCode, signalCode);
cluster.emit('exit', self, exitCode, signalCode);
});
this.process.once('disconnect', function() {
prepareExit(self, 'disconne
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/constants.js
// Copyright Joyent, Inc. and other Node contributors.
//
// 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:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// 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.
module.exports = process.binding('constants');
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/dgram.js
var assert = require('assert');
var util = require('util');
var events = require('events');
var UDP = process.binding('udp_wrap').UDP;
var BIND_STATE_UNBOUND = 0;
var BIND_STATE_BINDING = 1;
var BIND_STATE_BOUND = 2;
var cluster = null;
var dns = null;
var net = null;
function noop() {
}
function isIP(address) {
if (!net)
net = require('net');
return net.isIP(address);
}
function lookup(address, family, callback) {
if (!dns)
dns = require('dns');
return dns.lookup(address, family, callback);
}
function lookup4(address, callback) {
return lookup(address || '0.0.0.0', 4, callback);
}
function lookup6(address, callback) {
return lookup(address || '::0', 6, callback);
}
function newHandle(type) {
if (type == 'udp4') {
var handle = new UDP;
handle.lookup = lookup4;
return handle;
}
if (type == 'udp6') {
var handle = new UDP;
handle.lookup = lookup6;
handle.bind = handle.bind6;
handle.send = handle.send6;
return handle;
}
if (type == 'unix_dgram')
throw new Error('unix_dgram sockets are not supported any more.');
throw new Error('Bad socket type specified. Valid types are: udp4, udp6');
}
exports._createSocketHandle = function(address, port, addressType, fd) {
assert(typeof fd !== 'number' || fd < 0);
var handle = newHandle(addressType);
if (port || address) {
var r = handle.bind(address, port || 0, 0);
if (r == -1) {
handle.close();
handle = null;
}
}
return handle;
};
function Socket(type, listener) {
events.EventEmitter.call(this);
var handle = newHandle(type);
handle.owner = this;
this._handle = handle;
this._receiving = false;
this._bindState = BIND_STATE_UNBOUND;
this.type = type;
this.fd = null;
if (typeof listener === 'function')
this.on('message', listener);
}
util.inherits(Socket, events.EventEmitter);
exports.Socket = Socket;
exports.createSocket = function(type, listener) {
return new Socket(type, listener);
};
function startListening(socket) {
socket._handle.onmessage = onMessage;
socket._handle.recvStart();
socket._receiving = true;
socket._bindState = BIND_STATE_BOUND;
socket.fd = -42;
socket.emit('listening');
}
function replaceHandle(self, newHandle) {
newHandle.lookup = self._handle.lookup;
newHandle.bind = self._handle.bind;
newHandle.send = self._handle.send;
newHandle.owner = self;
self._handle.close();
self._handle = newHandle;
}
Socket.prototype.bind = function() {
var self = this;
self._healthCheck();
if (this._bindState != BIND_STATE_UNBOUND)
throw new Error('Socket is already bound');
this._bindState = BIND_STATE_BINDING;
if (typeof arguments[arguments.length - 1] === 'function')
self.once('listening', arguments[arguments.length - 1]);
var UDP = process.binding('udp_wrap').UDP;
if (arguments[0] instanceof UDP) {
replaceHandle(self, arguments[0]);
startListening(self);
return;
}
var port = arguments[0];
var address = arguments[1];
if (typeof address === 'function') address = '';
self._handle.lookup(address, function(err, ip) {
if (err) {
self._bindState = BIND_STATE_UNBOUND;
self.emit('error', err);
return;
}
if (!cluster)
cluster = require('cluster');
if (cluster.isWorker) {
cluster._getServer(self, ip, port, self.type, -1, function(handle) {
if (!self._handle)
return handle.close();
replaceHandle(self, handle);
startListening(self);
});
} else {
if (!self._handle)
return;
if (self._handle.bind(ip, port || 0, 0)) {
self.emit('error', errnoException(process._errno, 'bind'));
self._bindState = BIND_STATE_UNBOUND;
return;
}
startListening(self);
}
});
};
Socket.prototype.sendto = function(buffer,
offset,
length,
port,
address,
callback) {
if (typeof offset !== 'number' || typeof length !== 'number')
throw new Error('send takes offset and length as args 2 and 3');
if (typeof address !== 'string')
throw new Error(this.type + ' sockets must send to port, address');
this.send(buffer, offset, length, port, address, callback);
};
Socket.prototype.send = function(buffer,
offset,
length,
port,
address,
callback) {
var self = this;
if (!Buffer.isBuffer(buffer))
throw new TypeError('First argument must be a buffer object.');
offset = offset | 0;
if (offset < 0)
throw new RangeError('Offset should be >= 0');
if (offset >= buffer.length)
throw new RangeError('Offset into buffer too large');
length = length | 0;
if (length < 0)
throw new RangeError('Length should be >= 0');
if (offset + length > buffer.length)
throw new RangeError('Offset + length beyond buffer length');
port = port | 0;
if (port <= 0 || port > 65535)
throw new RangeError('Port should be > 0 and < 65536');
callback = callback || noop;
self._healthCheck();
if (self._bindState == BIND_STATE_UNBOUND)
self.bind(0, null);
if (self._bindState != BIND_STATE_BOUND) {
if (!self._sendQueue) {
self._sendQueue = [];
self.once('listening', function() {
for (var i = 0; i < self._sendQueue.length; i++)
self.send.apply(self, self._sendQueue[i]);
self._sendQueue = undefined;
});
}
self._sendQueue.push([buffer, offset, length, port, address, callback]);
return;
}
self._handle.lookup(address, function(err, ip) {
if (err) {
if (callback) callback(err);
self.emit('error', err);
}
else if (self._handle) {
var req = self._handle.send(buffer, offset, length, port, ip);
if (req) {
req.oncomplete = afterSend;
req.cb = callback;
}
else {
var err = errnoException(process._errno, 'send');
process.nextTick(function() {
callback(err);
});
}
}
});
};
function afterSend(status, handle, req, buffer) {
var self = handle.owner;
if (req.cb)
req.cb(null, buffer.length);
}
Socket.prototype.close = function() {
this._healthCheck();
this._stopReceiving();
this._handle.close();
this._handle = null;
this.emit('close');
};
Socket.prototype.address = function() {
this._healthCheck();
var address = this._handle.getsockname();
if (!address)
throw errnoException(process._errno, 'getsockname');
return address;
};
Socket.prototype.setBroadcast = function(arg) {
if (this._handle.setBroadcast((arg) ? 1 : 0)) {
throw errnoException(process._errno, 'setBroadcast');
}
};
Socket.prototype.setTTL = function(arg) {
if (typeof arg !== 'number') {
throw new TypeError('Argument must be a number');
}
if (this._handle.setTTL(arg)) {
throw errnoException(process._errno, 'setTTL');
}
return arg;
};
Socket.prototype.setMulticastTTL = function(arg) {
if (typeof arg !== 'number') {
throw new TypeError('Argument must be a number');
}
if (this._handle.setMulticastTTL(arg)) {
throw errnoException(process._errno, 'setMulticastTTL');
}
return arg;
};
Socket.prototype.setMulticastLoopback = function(arg) {
arg = arg ? 1 : 0;
if (this._handle.setMulticastLoopback(arg)) {
throw errnoException(process._errno, 'setMulticastLoopback');
}
return arg;
};
Socket.prototype.addMembership = function(multicastAddress,
interfaceAddress) {
this._healthCheck();
if (!multicastAddress) {
throw new Error('multicast address must be specified');
}
if (this._handle.addMembership(multicastAddress, interfaceAdd
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/crypto.js
exports.DEFAULT_ENCODING = 'buffer';
try {
var binding = process.binding('crypto');
var SecureContext = binding.SecureContext;
var randomBytes = binding.randomBytes;
var pseudoRandomBytes = binding.pseudoRandomBytes;
var getCiphers = binding.getCiphers;
var getHashes = binding.getHashes;
var crypto = true;
} catch (e) {
var crypto = false;
}
var stream = require('stream');
var util = require('util');
function toBuf(str, encoding) {
encoding = encoding || 'binary';
if (typeof str === 'string') {
if (encoding === 'buffer')
encoding = 'binary';
str = new Buffer(str, encoding);
}
return str;
}
var assert = require('assert');
var StringDecoder = require('string_decoder').StringDecoder;
function Credentials(secureProtocol, flags, context) {
if (!(this instanceof Credentials)) {
return new Credentials(secureProtocol, flags, context);
}
if (!crypto) {
throw new Error('node.js not compiled with openssl crypto support.');
}
if (context) {
this.context = context;
} else {
this.context = new SecureContext();
if (secureProtocol) {
this.context.init(secureProtocol);
} else {
this.context.init();
}
}
if (flags) this.context.setOptions(flags);
}
exports.Credentials = Credentials;
exports.createCredentials = function(options, context) {
if (!options) options = {};
var c = new Credentials(options.secureProtocol,
options.secureOptions,
context);
if (context) return c;
if (options.key) {
if (options.passphrase) {
c.context.setKey(options.key, options.passphrase);
} else {
c.context.setKey(options.key);
}
}
if (options.cert) c.context.setCert(options.cert);
if (options.ciphers) c.context.setCiphers(options.ciphers);
if (options.ca) {
if (Array.isArray(options.ca)) {
for (var i = 0, len = options.ca.length; i < len; i++) {
c.context.addCACert(options.ca[i]);
}
} else {
c.context.addCACert(options.ca);
}
} else {
c.context.addRootCerts();
}
if (options.crl) {
if (Array.isArray(options.crl)) {
for (var i = 0, len = options.crl.length; i < len; i++) {
c.context.addCRL(options.crl[i]);
}
} else {
c.context.addCRL(options.crl);
}
}
if (options.sessionIdContext) {
c.context.setSessionIdContext(options.sessionIdContext);
}
if (options.pfx) {
var pfx = options.pfx;
var passphrase = options.passphrase;
pfx = toBuf(pfx);
if (passphrase)
passphrase = toBuf(passphrase);
if (passphrase) {
c.context.loadPKCS12(pfx, passphrase);
} else {
c.context.loadPKCS12(pfx);
}
}
return c;
};
function LazyTransform(options) {
this._options = options;
}
util.inherits(LazyTransform, stream.Transform);
[
'_readableState',
'_writableState',
'_transformState'
].forEach(function(prop, i, props) {
Object.defineProperty(LazyTransform.prototype, prop, {
get: function() {
stream.Transform.call(this, this._options);
this._writableState.decodeStrings = false;
this._writableState.defaultEncoding = 'binary';
return this[prop];
},
set: function(val) {
Object.defineProperty(this, prop, {
value: val,
enumerable: true,
configurable: true,
writable: true
});
},
configurable: true,
enumerable: true
});
});
exports.createHash = exports.Hash = Hash;
function Hash(algorithm, options) {
if (!(this instanceof Hash))
return new Hash(algorithm, options);
this._binding = new binding.Hash(algorithm);
LazyTransform.call(this, options);
}
util.inherits(Hash, LazyTransform);
Hash.prototype._transform = function(chunk, encoding, callback) {
this._binding.update(chunk, encoding);
callback();
};
Hash.prototype._flush = function(callback) {
var encoding = this._readableState.encoding || 'buffer';
this.push(this._binding.digest(encoding), encoding);
callback();
};
Hash.prototype.update = function(data, encoding) {
encoding = encoding || exports.DEFAULT_ENCODING;
if (encoding === 'buffer' && typeof data === 'string')
encoding = 'binary';
this._binding.update(data, encoding);
return this;
};
Hash.prototype.digest = function(outputEncoding) {
outputEncoding = outputEncoding || exports.DEFAULT_ENCODING;
return this._binding.digest(outputEncoding);
};
exports.createHmac = exports.Hmac = Hmac;
function Hmac(hmac, key, options) {
if (!(this instanceof Hmac))
return new Hmac(hmac, key, options);
this._binding = new binding.Hmac();
this._binding.init(hmac, toBuf(key));
LazyTransform.call(this, options);
}
util.inherits(Hmac, LazyTransform);
Hmac.prototype.update = Hash.prototype.update;
Hmac.prototype.digest = Hash.prototype.digest;
Hmac.prototype._flush = Hash.prototype._flush;
Hmac.prototype._transform = Hash.prototype._transform;
function getDecoder(decoder, encoding) {
if (encoding === 'utf-8') encoding = 'utf8';
decoder = decoder || new StringDecoder(encoding);
assert(decoder.encoding === encoding, 'Cannot change encoding');
return decoder;
}
exports.createCipher = exports.Cipher = Cipher;
function Cipher(cipher, password, options) {
if (!(this instanceof Cipher))
return new Cipher(cipher, password, options);
this._binding = new binding.Cipher;
this._binding.init(cipher, toBuf(password));
this._decoder = null;
LazyTransform.call(this, options);
}
util.inherits(Cipher, LazyTransform);
Cipher.prototype._transform = function(chunk, encoding, callback) {
this.push(this._binding.update(chunk, encoding));
callback();
};
Cipher.prototype._flush = function(callback) {
this.push(this._binding.final());
callback();
};
Cipher.prototype.update = function(data, inputEncoding, outputEncoding) {
inputEncoding = inputEncoding || exports.DEFAULT_ENCODING;
outputEncoding = outputEncoding || exports.DEFAULT_ENCODING;
var ret = this._binding.update(data, inputEncoding);
if (outputEncoding && outputEncoding !== 'buffer') {
this._decoder = getDecoder(this._decoder, outputEncoding);
ret = this._decoder.write(ret);
}
return ret;
};
Cipher.prototype.final = function(outputEncoding) {
outputEncoding = outputEncoding || exports.DEFAULT_ENCODING;
var ret = this._binding.final();
if (outputEncoding && outputEncoding !== 'buffer') {
this._decoder = getDecoder(this._decoder, outputEncoding);
ret = this._decoder.end(ret);
}
return ret;
};
Cipher.prototype.setAutoPadding = function(ap) {
this._binding.setAutoPadding(ap);
return this;
};
exports.createCipheriv = exports.Cipheriv = Cipheriv;
function Cipheriv(cipher, key, iv, options) {
if (!(this instanceof Cipheriv))
return new Cipheriv(cipher, key, iv, options);
this._binding = new binding.Cipher();
this._binding.initiv(cipher, toBuf(key), toBuf(iv));
this._decoder = null;
LazyTransform.call(this, options);
}
util.inherits(Cipheriv, LazyTransform);
Cipheriv.prototype._transform = Cipher.prototype._transform;
Cipheriv.prototype._flush = Cipher.prototype._flush;
Cipheriv.prototype.update = Cipher.prototype.update;
Cipheriv.prototype.final = Cipher.prototype.final;
Cipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
exports.createDecipher = exports.Decipher = Decipher;
function Decipher(cipher, password, options) {
if (!(this instanceof Decipher))
return new Decipher(cipher, password, options);
this._binding = new binding.Decipher;
this._binding.init(cipher, toBuf(password));
this._decoder = null;
LazyTransform.call(this, options);
}
util.inherits(Decipher, LazyTransform);
Decipher.prototype._transform = Cipher.prototype._transform;
Decipher.prototype._flush = Cipher.prototype._flush;
Decipher.prototype.update = Cipher.prototype.update;
Decipher.prototype.final = Cipher.prototype.final;
Decipher.prototype.finaltol = Cipher.prototype.final;
Decipher.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
exports.createDecipheriv = exports.Decipheriv = Decipheriv;
function Decipheriv(cipher, key, iv, options) {
if (!(this instanceof Decipheriv))
return new Decipheriv(cipher, key, iv, options);
this._binding = new binding.Decipher;
this._binding.initiv(cipher, toBuf(key), toBuf(iv));
this._decoder = null;
LazyTransform.call(this, options);
}
util.inherits(Decipheriv, LazyTransform);
Decipheriv.prototype._transform = Cipher.prototype._transform;
Decipheriv.prototype._flush = Cipher.prototype._flush;
Decipheriv.prototype.update = Cipher.prototype.update;
Decipheriv.prototype.final = Cipher.prototype.final;
Decipheriv.prototype.finaltol = Cipher.prototype.final;
Decipheriv.prototype.setAutoPadding = Cipher.prototype.
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/events.js
var domain;
exports.usingDomains = false;
function EventEmitter() {
this.domain = null;
if (exports.usingDomains) {
domain = domain || require('domain');
if (domain.active && !(this instanceof domain.Domain)) {
this.domain = domain.active;
}
}
this._events = this._events || {};
this._maxListeners = this._maxListeners || defaultMaxListeners;
}
exports.EventEmitter = EventEmitter;
var defaultMaxListeners = 10;
EventEmitter.prototype.setMaxListeners = function(n) {
if (typeof n !== 'number' || n < 0)
throw TypeError('n must be a positive number');
this._maxListeners = n;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
if (type === 'error') {
if (!this._events.error ||
(typeof this._events.error === 'object' &&
!this._events.error.length)) {
er = arguments[1];
if (this.domain) {
if (!er) er = new TypeError('Uncaught, unspecified "error" event.');
er.domainEmitter = this;
er.domain = this.domain;
er.domainThrown = false;
this.domain.emit('error', er);
} else if (er instanceof Error) {
throw er;
} else {
throw TypeError('Uncaught, unspecified "error" event.');
}
return false;
}
}
handler = this._events[type];
if (typeof handler === 'undefined')
return false;
if (this.domain && this !== process)
this.domain.enter();
if (typeof handler === 'function') {
switch (arguments.length) {
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (typeof handler === 'object') {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
if (this.domain && this !== process)
this.domain.exit();
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (typeof listener !== 'function')
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
if (this._events.newListener)
this.emit('newListener', type, typeof listener.listener === 'function' ?
listener.listener : listener);
if (!this._events[type])
this._events[type] = listener;
else if (typeof this._events[type] === 'object')
this._events[type].push(listener);
else
this._events[type] = [this._events[type], listener];
if (typeof this._events[type] === 'object' && !this._events[type].warned) {
m = this._maxListeners;
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (typeof listener !== 'function')
throw TypeError('listener must be a function');
function g() {
this.removeListener(type, g);
listener.apply(this, arguments);
}
g.listener = listener;
this.on(type, g);
return this;
};
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (typeof listener !== 'function')
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(typeof list.listener === 'function' && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (typeof list === 'object') {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else {
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (typeof this._events[type] === 'function')
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (typeof emitter._events[type] === 'function')
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/domain.js
var util = require('util');
var events = require('events');
var EventEmitter = events.EventEmitter;
var inherits = util.inherits;
var endMethods = ['end', 'abort', 'destroy', 'destroySoon'];
events.usingDomains = true;
process._usingDomains();
exports.Domain = Domain;
exports.create = exports.createDomain = function(cb) {
return new Domain(cb);
};
var stack = [];
exports._stack = stack;
exports.active = null;
inherits(Domain, EventEmitter);
function Domain() {
EventEmitter.call(this);
this.members = [];
}
Domain.prototype.enter = function() {
if (this._disposed) return;
exports.active = process.domain = this;
stack.push(this);
};
Domain.prototype.exit = function() {
if (this._disposed) return;
var d;
do {
d = stack.pop();
} while (d && d !== this);
exports.active = stack[stack.length - 1];
process.domain = exports.active;
};
Domain.prototype.add = function(ee) {
if (this._disposed) return;
if (ee.domain === this) return;
if (ee.domain) {
ee.domain.remove(ee);
}
if (this.domain && (ee instanceof Domain)) {
for (var d = this.domain; d; d = d.domain) {
if (ee === d) return;
}
}
ee.domain = this;
this.members.push(ee);
};
Domain.prototype.remove = function(ee) {
ee.domain = null;
var index = this.members.indexOf(ee);
if (index !== -1) {
this.members.splice(index, 1);
}
};
Domain.prototype.run = function(fn) {
return this.bind(fn)();
};
Domain.prototype.intercept = function(cb) {
return this.bind(cb, true);
};
Domain.prototype.bind = function(cb, interceptError) {
var self = this;
var b = function() {
if (self._disposed) return;
if (this instanceof Domain) {
return cb.apply(this, arguments);
}
if (interceptError && arguments[0] &&
(arguments[0] instanceof Error)) {
var er = arguments[0];
util._extend(er, {
domainBound: cb,
domainThrown: false,
domain: self
});
self.emit('error', er);
return;
}
if (interceptError) {
var len = arguments.length;
var args;
switch (len) {
case 0:
case 1:
args = [];
break;
case 2:
args = [arguments[1]];
break;
default:
args = new Array(len - 1);
for (var i = 1; i < len; i++) {
args[i - 1] = arguments[i];
}
break;
}
self.enter();
var ret = cb.apply(this, args);
self.exit();
return ret;
}
self.enter();
var ret = cb.apply(this, arguments);
self.exit();
return ret;
};
b.domain = this;
return b;
};
Domain.prototype.dispose = function() {
if (this._disposed) return;
this.exit();
this.emit('dispose');
this.removeAllListeners();
this.on('error', function() {});
this.members.forEach(function(m) {
clearTimeout(m);
if (m instanceof EventEmitter) {
m.removeAllListeners();
m.on('error', function() {});
}
endMethods.forEach(function(method) {
if (typeof m[method] === 'function') {
try {
m[method]();
} catch (er) {}
}
});
});
if (this.domain) this.domain.remove(this);
this.members.length = 0;
this._disposed = true;
};
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/dns.js
var cares = process.binding('cares_wrap'),
net = require('net'),
isIp = net.isIP;
function errnoException(errorno, syscall) {
if (errorno == 'ENOENT') {
errorno = 'ENOTFOUND';
}
var e = new Error(syscall + ' ' + errorno);
e.errno = e.code = errorno;
e.syscall = syscall;
return e;
}
function makeAsync(callback) {
if (typeof callback !== 'function') {
return callback;
}
return function asyncCallback() {
if (asyncCallback.immediately) {
callback.apply(null, arguments);
} else {
var args = arguments;
process.nextTick(function() {
callback.apply(null, args);
});
}
};
}
exports.lookup = function(domain, family, callback) {
if (arguments.length === 2) {
callback = family;
family = 0;
} else if (!family) {
family = 0;
} else {
family = +family;
if (family !== 4 && family !== 6) {
throw new Error('invalid argument: `family` must be 4 or 6');
}
}
callback = makeAsync(callback);
if (!domain) {
callback(null, null, family === 6 ? 6 : 4);
return {};
}
if (process.platform == 'win32' && domain == 'localhost') {
callback(null, '127.0.0.1', 4);
return {};
}
var matchedFamily = net.isIP(domain);
if (matchedFamily) {
callback(null, domain, matchedFamily);
return {};
}
function onanswer(addresses) {
if (addresses) {
if (family) {
callback(null, addresses[0], family);
} else {
callback(null, addresses[0], addresses[0].indexOf(':') >= 0 ? 6 : 4);
}
} else {
callback(errnoException(process._errno, 'getaddrinfo'));
}
}
var wrap = cares.getaddrinfo(domain, family);
if (!wrap) {
throw errnoException(process._errno, 'getaddrinfo');
}
wrap.oncomplete = onanswer;
callback.immediately = true;
return wrap;
};
function resolver(bindingName) {
var binding = cares[bindingName];
return function query(name, callback) {
function onanswer(status, result) {
if (!status) {
callback(null, result);
} else {
callback(errnoException(process._errno, bindingName));
}
}
callback = makeAsync(callback);
var wrap = binding(name, onanswer);
if (!wrap) {
throw errnoException(process._errno, bindingName);
}
callback.immediately = true;
return wrap;
}
}
var resolveMap = {};
exports.resolve4 = resolveMap.A = resolver('queryA');
exports.resolve6 = resolveMap.AAAA = resolver('queryAaaa');
exports.resolveCname = resolveMap.CNAME = resolver('queryCname');
exports.resolveMx = resolveMap.MX = resolver('queryMx');
exports.resolveNs = resolveMap.NS = resolver('queryNs');
exports.resolveTxt = resolveMap.TXT = resolver('queryTxt');
exports.resolveSrv = resolveMap.SRV = resolver('querySrv');
exports.resolveNaptr = resolveMap.NAPTR = resolver('queryNaptr');
exports.reverse = resolveMap.PTR = resolver('getHostByAddr');
exports.resolve = function(domain, type_, callback_) {
var resolver, callback;
if (typeof type_ == 'string') {
resolver = resolveMap[type_];
callback = callback_;
} else {
resolver = exports.resolve4;
callback = type_;
}
if (typeof resolver === 'function') {
return resolver(domain, callback);
} else {
throw new Error('Unknown type "' + type_ + '"');
}
};
exports.NODATA = 'ENODATA';
exports.FORMERR = 'EFORMERR';
exports.SERVFAIL = 'ESERVFAIL';
exports.NOTFOUND = 'ENOTFOUND';
exports.NOTIMP = 'ENOTIMP';
exports.REFUSED = 'EREFUSED';
exports.BADQUERY = 'EBADQUERY';
exports.ADNAME = 'EADNAME';
exports.BADFAMILY = 'EBADFAMILY';
exports.BADRESP = 'EBADRESP';
exports.CONNREFUSED = 'ECONNREFUSED';
exports.TIMEOUT = 'ETIMEOUT';
exports.EOF = 'EOF';
exports.FILE = 'EFILE';
exports.NOMEM = 'ENOMEM';
exports.DESTRUCTION = 'EDESTRUCTION';
exports.BADSTR = 'EBADSTR';
exports.BADFLAGS = 'EBADFLAGS';
exports.NONAME = 'ENONAME';
exports.BADHINTS = 'EBADHINTS';
exports.NOTINITIALIZED = 'ENOTINITIALIZED';
exports.LOADIPHLPAPI = 'ELOADIPHLPAPI';
exports.ADDRGETNETWORKPARAMS = 'EADDRGETNETWORKPARAMS';
exports.CANCELLED = 'ECANCELLED';
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/freelist.js
exports.FreeList = function(name, max, constructor) {
this.name = name;
this.constructor = constructor;
this.max = max;
this.list = [];
};
exports.FreeList.prototype.alloc = function() {
return this.list.length ? this.list.shift() :
this.constructor.apply(this, arguments);
};
exports.FreeList.prototype.free = function(obj) {
if (this.list.length < this.max) {
this.list.push(obj);
}
};
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/http.js
var util = require('util');
var net = require('net');
var Stream = require('stream');
var timers = require('timers');
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var FreeList = require('freelist').FreeList;
var HTTPParser = process.binding('http_parser').HTTPParser;
var assert = require('assert').ok;
var debug;
if (process.env.NODE_DEBUG && /http/.test(process.env.NODE_DEBUG)) {
debug = function(x) { console.error('HTTP: %s', x); };
} else {
debug = function() { };
}
function readStart(socket) {
if (!socket || !socket._handle || !socket._handle.readStart) return;
socket._handle.readStart();
}
function readStop(socket) {
if (!socket || !socket._handle || !socket._handle.readStop) return;
socket._handle.readStop();
}
function parserOnHeaders(headers, url) {
if (this.maxHeaderPairs <= 0 ||
this._headers.length < this.maxHeaderPairs) {
this._headers = this._headers.concat(headers);
}
this._url += url;
}
function parserOnHeadersComplete(info) {
var parser = this;
var headers = info.headers;
var url = info.url;
if (!headers) {
headers = parser._headers;
parser._headers = [];
}
if (!url) {
url = parser._url;
parser._url = '';
}
parser.incoming = new IncomingMessage(parser.socket);
parser.incoming.httpVersionMajor = info.versionMajor;
parser.incoming.httpVersionMinor = info.versionMinor;
parser.incoming.httpVersion = info.versionMajor + '.' + info.versionMinor;
parser.incoming.url = url;
var n = headers.length;
if (parser.maxHeaderPairs > 0) {
n = Math.min(n, parser.maxHeaderPairs);
}
for (var i = 0; i < n; i += 2) {
var k = headers[i];
var v = headers[i + 1];
parser.incoming._addHeaderLine(k, v);
}
if (info.method) {
parser.incoming.method = info.method;
} else {
parser.incoming.statusCode = info.statusCode;
}
parser.incoming.upgrade = info.upgrade;
var skipBody = false;
if (!info.upgrade) {
skipBody = parser.onIncoming(parser.incoming, info.shouldKeepAlive);
}
return skipBody;
}
function parserOnBody(b, start, len) {
var parser = this;
var stream = parser.incoming;
if (!stream)
return;
var socket = stream.socket;
if (len > 0 && !stream._dumped) {
var slice = b.slice(start, start + len);
var ret = stream.push(slice);
if (!ret)
readStop(socket);
}
}
function parserOnMessageComplete() {
var parser = this;
var stream = parser.incoming;
if (stream) {
stream.complete = true;
var headers = parser._headers;
if (headers) {
for (var i = 0, n = headers.length; i < n; i += 2) {
var k = headers[i];
var v = headers[i + 1];
parser.incoming._addHeaderLine(k, v);
}
parser._headers = [];
parser._url = '';
}
if (!stream.upgrade)
stream.push(null);
}
if (stream && !parser.incoming._pendings.length) {
stream.push(null);
}
if (parser.socket.readable) {
readStart(parser.socket);
}
}
var parsers = new FreeList('parsers', 1000, function() {
var parser = new HTTPParser(HTTPParser.REQUEST);
parser._headers = [];
parser._url = '';
parser.onHeaders = parserOnHeaders;
parser.onHeadersComplete = parserOnHeadersComplete;
parser.onBody = parserOnBody;
parser.onMessageComplete = parserOnMessageComplete;
return parser;
});
exports.parsers = parsers;
var CRLF = '\r\n';
var STATUS_CODES = exports.STATUS_CODES = {
100 : 'Continue',
101 : 'Switching Protocols',
102 : 'Processing',
200 : 'OK',
201 : 'Created',
202 : 'Accepted',
203 : 'Non-Authoritative Information',
204 : 'No Content',
205 : 'Reset Content',
206 : 'Partial Content',
207 : 'Multi-Status',
300 : 'Multiple Choices',
301 : 'Moved Permanently',
302 : 'Moved Temporarily',
303 : 'See Other',
304 : 'Not Modified',
305 : 'Use Proxy',
307 : 'Temporary Redirect',
400 : 'Bad Request',
401 : 'Unauthorized',
402 : 'Payment Required',
403 : 'Forbidden',
404 : 'Not Found',
405 : 'Method Not Allowed',
406 : 'Not Acceptable',
407 : 'Proxy Authentication Required',
408 : 'Request Time-out',
409 : 'Conflict',
410 : 'Gone',
411 : 'Length Required',
412 : 'Precondition Failed',
413 : 'Request Entity Too Large',
414 : 'Request-URI Too Large',
415 : 'Unsupported Media Type',
416 : 'Requested Range Not Satisfiable',
417 : 'Expectation Failed',
418 : 'I\'m a teapot',
422 : 'Unprocessable Entity',
423 : 'Locked',
424 : 'Failed Dependency',
425 : 'Unordered Collection',
426 : 'Upgrade Required',
428 : 'Precondition Required',
429 : 'Too Many Requests',
431 : 'Request Header Fields Too Large',
500 : 'Internal Server Error',
501 : 'Not Implemented',
502 : 'Bad Gateway',
503 : 'Service Unavailable',
504 : 'Gateway Time-out',
505 : 'HTTP Version Not Supported',
506 : 'Variant Also Negotiates',
507 : 'Insufficient Storage',
509 : 'Bandwidth Limit Exceeded',
510 : 'Not Extended',
511 : 'Network Authentication Required'
};
var connectionExpression = /Connection/i;
var transferEncodingExpression = /Transfer-Encoding/i;
var closeExpression = /close/i;
var chunkExpression = /chunk/i;
var contentLengthExpression = /Content-Length/i;
var dateExpression = /Date/i;
var expectExpression = /Expect/i;
var continueExpression = /100-continue/i;
var dateCache;
function utcDate() {
if (!dateCache) {
var d = new Date();
dateCache = d.toUTCString();
timers.enroll(utcDate, 1000 - d.getMilliseconds());
timers._unrefActive(utcDate);
}
return dateCache;
}
utcDate._onTimeout = function() {
dateCache = undefined;
};
function IncomingMessage(socket) {
Stream.Readable.call(this);
this.socket = socket;
this.connection = socket;
this.httpVersion = null;
this.complete = false;
this.headers = {};
this.trailers = {};
this.readable = true;
this._pendings = [];
this._pendingIndex = 0;
this.url = '';
this.method = null;
this.statusCode = null;
this.client = this.socket;
this._consuming = false;
this._dumped = false;
}
util.inherits(IncomingMessage, Stream.Readable);
exports.IncomingMessage = IncomingMessage;
IncomingMessage.prototype.setTimeout = function(msecs, callback) {
if (callback)
this.on('timeout', callback);
this.socket.setTimeout(msecs);
};
IncomingMessage.prototype.read = function(n) {
this._consuming = true;
this.read = Stream.Readable.prototype.read;
return this.read(n);
};
IncomingMessage.prototype._read = function(n) {
if (!this.socket.r
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/https.js
var tls = require('tls');
var http = require('http');
var util = require('util');
var url = require('url');
var inherits = require('util').inherits;
function Server(opts, requestListener) {
if (!(this instanceof Server)) return new Server(opts, requestListener);
if (process.features.tls_npn && !opts.NPNProtocols) {
opts.NPNProtocols = ['http/1.1', 'http/1.0'];
}
tls.Server.call(this, opts, http._connectionListener);
this.httpAllowHalfOpen = false;
if (requestListener) {
this.addListener('request', requestListener);
}
this.addListener('clientError', function(err, conn) {
conn.destroy(err);
});
}
inherits(Server, tls.Server);
exports.Server = Server;
exports.createServer = function(opts, requestListener) {
return new Server(opts, requestListener);
};
function createConnection(port, host, options) {
if (typeof port === 'object') {
options = port;
} else if (typeof host === 'object') {
options = host;
} else if (typeof options === 'object') {
options = options;
} else {
options = {};
}
if (typeof port === 'number') {
options.port = port;
}
if (typeof host === 'string') {
options.host = host;
}
return tls.connect(options);
}
function Agent(options) {
http.Agent.call(this, options);
this.createConnection = createConnection;
}
inherits(Agent, http.Agent);
Agent.prototype.defaultPort = 443;
var globalAgent = new Agent();
exports.globalAgent = globalAgent;
exports.Agent = Agent;
exports.request = function(options, cb) {
if (typeof options === 'string') {
options = url.parse(options);
}
if (options.protocol && options.protocol !== 'https:') {
throw new Error('Protocol:' + options.protocol + ' not supported.');
}
options = util._extend({
createConnection: createConnection,
defaultPort: 443
}, options);
if (typeof options.agent === 'undefined') {
if (typeof options.ca === 'undefined' &&
typeof options.cert === 'undefined' &&
typeof options.ciphers === 'undefined' &&
typeof options.key === 'undefined' &&
typeof options.passphrase === 'undefined' &&
typeof options.pfx === 'undefined' &&
typeof options.rejectUnauthorized === 'undefined') {
options.agent = globalAgent;
} else {
options.agent = new Agent(options);
}
}
return new http.ClientRequest(options, cb);
};
exports.get = function(options, cb) {
var req = exports.request(options, cb);
req.end();
return req;
};
|