11222 lines
489 KiB
HTML
11222 lines
489 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<title>About this Documentation Node.js v0.8.14 Manual & Documentation</title>
|
||
<link rel="stylesheet" href="assets/style.css">
|
||
<link rel="stylesheet" href="assets/sh.css">
|
||
<link rel="canonical" href="http://nodejs.org/api/all.html">
|
||
</head>
|
||
<body class="alt apidoc" id="api-section-all">
|
||
<div id="intro" class="interior">
|
||
<a href="/" title="Go back to the home page">
|
||
<img id="logo" src="http://nodejs.org/images/logo-light.png" alt="node.js">
|
||
</a>
|
||
</div>
|
||
<div id="content" class="clearfix">
|
||
<div id="column2" class="interior">
|
||
<ul>
|
||
<li><a href="/" class="home">Home</a></li>
|
||
<li><a href="/download/" class="download">Download</a></li>
|
||
<li><a href="/about/" class="about">About</a></li>
|
||
<li><a href="http://search.npmjs.org/" class="npm">npm Registry</a></li>
|
||
<li><a href="http://nodejs.org/api/" class="docs current">Docs</a></li>
|
||
<li><a href="http://blog.nodejs.org" class="blog">Blog</a></li>
|
||
<li><a href="/community/" class="community">Community</a></li>
|
||
<li><a href="/logos/" class="logos">Logos</a></li>
|
||
<li><a href="http://jobs.nodejs.org/" class="jobs">Jobs</a></li>
|
||
</ul>
|
||
<p class="twitter"><a href="http://twitter.com/nodejs">@nodejs</a></p>
|
||
</div>
|
||
|
||
<div id="column1" class="interior">
|
||
<header>
|
||
<h1>Node.js v0.8.14 Manual & Documentation</h1>
|
||
<div id="gtoc">
|
||
<p>
|
||
<a href="index.html" name="toc">Index</a> |
|
||
<a href="all.html">View on single page</a> |
|
||
<a href="all.json">View as JSON</a>
|
||
</p>
|
||
</div>
|
||
<hr>
|
||
</header>
|
||
|
||
<div id="toc">
|
||
<h2>Table of Contents</h2>
|
||
<ul>
|
||
<li><a href="#all_about_this_documentation">About this Documentation</a><ul>
|
||
<li><a href="#all_stability_index">Stability Index</a></li>
|
||
<li><a href="#all_json_output">JSON Output</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_synopsis">Synopsis</a></li>
|
||
<li><a href="#all_global_objects">Global Objects</a><ul>
|
||
<li><a href="#all_global">global</a></li>
|
||
<li><a href="#all_process">process</a></li>
|
||
<li><a href="#all_console">console</a></li>
|
||
<li><a href="#all_class_buffer">Class: Buffer</a></li>
|
||
<li><a href="#all_require">require()</a><ul>
|
||
<li><a href="#all_require_resolve">require.resolve()</a></li>
|
||
<li><a href="#all_require_cache">require.cache</a></li>
|
||
<li><a href="#all_require_extensions">require.extensions</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_filename">__filename</a></li>
|
||
<li><a href="#all_dirname">__dirname</a></li>
|
||
<li><a href="#all_module">module</a></li>
|
||
<li><a href="#all_exports">exports</a></li>
|
||
<li><a href="#all_settimeout_cb_ms">setTimeout(cb, ms)</a></li>
|
||
<li><a href="#all_cleartimeout_t">clearTimeout(t)</a></li>
|
||
<li><a href="#all_setinterval_cb_ms">setInterval(cb, ms)</a></li>
|
||
<li><a href="#all_clearinterval_t">clearInterval(t)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_console_1">console</a><ul>
|
||
<li><a href="#all_console_log_data">console.log([data], [...])</a></li>
|
||
<li><a href="#all_console_info_data">console.info([data], [...])</a></li>
|
||
<li><a href="#all_console_error_data">console.error([data], [...])</a></li>
|
||
<li><a href="#all_console_warn_data">console.warn([data], [...])</a></li>
|
||
<li><a href="#all_console_dir_obj">console.dir(obj)</a></li>
|
||
<li><a href="#all_console_time_label">console.time(label)</a></li>
|
||
<li><a href="#all_console_timeend_label">console.timeEnd(label)</a></li>
|
||
<li><a href="#all_console_trace_label">console.trace(label)</a></li>
|
||
<li><a href="#all_console_assert_expression_message">console.assert(expression, [message])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_timers">Timers</a><ul>
|
||
<li><a href="#all_settimeout_callback_delay_arg">setTimeout(callback, delay, [arg], [...])</a></li>
|
||
<li><a href="#all_cleartimeout_timeoutid">clearTimeout(timeoutId)</a></li>
|
||
<li><a href="#all_setinterval_callback_delay_arg">setInterval(callback, delay, [arg], [...])</a></li>
|
||
<li><a href="#all_clearinterval_intervalid">clearInterval(intervalId)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_modules">Modules</a><ul>
|
||
<li><a href="#all_cycles">Cycles</a></li>
|
||
<li><a href="#all_core_modules">Core Modules</a></li>
|
||
<li><a href="#all_file_modules">File Modules</a></li>
|
||
<li><a href="#all_loading_from_node_modules_folders">Loading from <code>node_modules</code> Folders</a></li>
|
||
<li><a href="#all_folders_as_modules">Folders as Modules</a></li>
|
||
<li><a href="#all_caching">Caching</a><ul>
|
||
<li><a href="#all_module_caching_caveats">Module Caching Caveats</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_the_module_object">The <code>module</code> Object</a><ul>
|
||
<li><a href="#all_module_exports">module.exports</a></li>
|
||
<li><a href="#all_module_require_id">module.require(id)</a></li>
|
||
<li><a href="#all_module_id">module.id</a></li>
|
||
<li><a href="#all_module_filename">module.filename</a></li>
|
||
<li><a href="#all_module_loaded">module.loaded</a></li>
|
||
<li><a href="#all_module_parent">module.parent</a></li>
|
||
<li><a href="#all_module_children">module.children</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_all_together">All Together...</a></li>
|
||
<li><a href="#all_loading_from_the_global_folders">Loading from the global folders</a></li>
|
||
<li><a href="#all_accessing_the_main_module">Accessing the main module</a></li>
|
||
<li><a href="#all_addenda_package_manager_tips">Addenda: Package Manager Tips</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_addons">Addons</a><ul>
|
||
<li><a href="#all_hello_world">Hello world</a></li>
|
||
<li><a href="#all_addon_patterns">Addon patterns</a><ul>
|
||
<li><a href="#all_function_arguments">Function arguments</a></li>
|
||
<li><a href="#all_callbacks">Callbacks</a></li>
|
||
<li><a href="#all_object_factory">Object factory</a></li>
|
||
<li><a href="#all_function_factory">Function factory</a></li>
|
||
<li><a href="#all_wrapping_c_objects">Wrapping C++ objects</a></li>
|
||
<li><a href="#all_factory_of_wrapped_objects">Factory of wrapped objects</a></li>
|
||
<li><a href="#all_passing_wrapped_objects_around">Passing wrapped objects around</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_process_1">process</a><ul>
|
||
<li><a href="#all_event_exit">Event: 'exit'</a></li>
|
||
<li><a href="#all_event_uncaughtexception">Event: 'uncaughtException'</a></li>
|
||
<li><a href="#all_signal_events">Signal Events</a></li>
|
||
<li><a href="#all_process_stdout">process.stdout</a></li>
|
||
<li><a href="#all_process_stderr">process.stderr</a></li>
|
||
<li><a href="#all_process_stdin">process.stdin</a></li>
|
||
<li><a href="#all_process_argv">process.argv</a></li>
|
||
<li><a href="#all_process_execpath">process.execPath</a></li>
|
||
<li><a href="#all_process_abort">process.abort()</a></li>
|
||
<li><a href="#all_process_chdir_directory">process.chdir(directory)</a></li>
|
||
<li><a href="#all_process_cwd">process.cwd()</a></li>
|
||
<li><a href="#all_process_env">process.env</a></li>
|
||
<li><a href="#all_process_exit_code">process.exit([code])</a></li>
|
||
<li><a href="#all_process_getgid">process.getgid()</a></li>
|
||
<li><a href="#all_process_setgid_id">process.setgid(id)</a></li>
|
||
<li><a href="#all_process_getuid">process.getuid()</a></li>
|
||
<li><a href="#all_process_setuid_id">process.setuid(id)</a></li>
|
||
<li><a href="#all_process_version">process.version</a></li>
|
||
<li><a href="#all_process_versions">process.versions</a></li>
|
||
<li><a href="#all_process_config">process.config</a></li>
|
||
<li><a href="#all_process_kill_pid_signal">process.kill(pid, [signal])</a></li>
|
||
<li><a href="#all_process_pid">process.pid</a></li>
|
||
<li><a href="#all_process_title">process.title</a></li>
|
||
<li><a href="#all_process_arch">process.arch</a></li>
|
||
<li><a href="#all_process_platform">process.platform</a></li>
|
||
<li><a href="#all_process_memoryusage">process.memoryUsage()</a></li>
|
||
<li><a href="#all_process_nexttick_callback">process.nextTick(callback)</a></li>
|
||
<li><a href="#all_process_umask_mask">process.umask([mask])</a></li>
|
||
<li><a href="#all_process_uptime">process.uptime()</a></li>
|
||
<li><a href="#all_process_hrtime">process.hrtime()</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_util">util</a><ul>
|
||
<li><a href="#all_util_format_format">util.format(format, [...])</a></li>
|
||
<li><a href="#all_util_debug_string">util.debug(string)</a></li>
|
||
<li><a href="#all_util_error">util.error([...])</a></li>
|
||
<li><a href="#all_util_puts">util.puts([...])</a></li>
|
||
<li><a href="#all_util_print">util.print([...])</a></li>
|
||
<li><a href="#all_util_log_string">util.log(string)</a></li>
|
||
<li><a href="#all_util_inspect_object_showhidden_depth_colors">util.inspect(object, [showHidden], [depth], [colors])</a></li>
|
||
<li><a href="#all_util_isarray_object">util.isArray(object)</a></li>
|
||
<li><a href="#all_util_isregexp_object">util.isRegExp(object)</a></li>
|
||
<li><a href="#all_util_isdate_object">util.isDate(object)</a></li>
|
||
<li><a href="#all_util_iserror_object">util.isError(object)</a></li>
|
||
<li><a href="#all_util_pump_readablestream_writablestream_callback">util.pump(readableStream, writableStream, [callback])</a></li>
|
||
<li><a href="#all_util_inherits_constructor_superconstructor">util.inherits(constructor, superConstructor)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_events">Events</a><ul>
|
||
<li><a href="#all_class_events_eventemitter">Class: events.EventEmitter</a><ul>
|
||
<li><a href="#all_emitter_addlistener_event_listener">emitter.addListener(event, listener)</a></li>
|
||
<li><a href="#all_emitter_on_event_listener">emitter.on(event, listener)</a></li>
|
||
<li><a href="#all_emitter_once_event_listener">emitter.once(event, listener)</a></li>
|
||
<li><a href="#all_emitter_removelistener_event_listener">emitter.removeListener(event, listener)</a></li>
|
||
<li><a href="#all_emitter_removealllisteners_event">emitter.removeAllListeners([event])</a></li>
|
||
<li><a href="#all_emitter_setmaxlisteners_n">emitter.setMaxListeners(n)</a></li>
|
||
<li><a href="#all_emitter_listeners_event">emitter.listeners(event)</a></li>
|
||
<li><a href="#all_emitter_emit_event_arg1_arg2">emitter.emit(event, [arg1], [arg2], [...])</a></li>
|
||
<li><a href="#all_event_newlistener">Event: 'newListener'</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_domain">Domain</a><ul>
|
||
<li><a href="#all_additions_to_error_objects">Additions to Error objects</a></li>
|
||
<li><a href="#all_implicit_binding">Implicit Binding</a></li>
|
||
<li><a href="#all_explicit_binding">Explicit Binding</a></li>
|
||
<li><a href="#all_domain_create">domain.create()</a></li>
|
||
<li><a href="#all_class_domain">Class: Domain</a><ul>
|
||
<li><a href="#all_domain_run_fn">domain.run(fn)</a></li>
|
||
<li><a href="#all_domain_members">domain.members</a></li>
|
||
<li><a href="#all_domain_add_emitter">domain.add(emitter)</a></li>
|
||
<li><a href="#all_domain_remove_emitter">domain.remove(emitter)</a></li>
|
||
<li><a href="#all_domain_bind_callback">domain.bind(callback)</a><ul>
|
||
<li><a href="#all_example">Example</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_domain_intercept_callback">domain.intercept(callback)</a><ul>
|
||
<li><a href="#all_example_1">Example</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_domain_dispose">domain.dispose()</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_buffer">Buffer</a><ul>
|
||
<li><a href="#all_class_buffer_1">Class: Buffer</a><ul>
|
||
<li><a href="#all_new_buffer_size">new Buffer(size)</a></li>
|
||
<li><a href="#all_new_buffer_array">new Buffer(array)</a></li>
|
||
<li><a href="#all_new_buffer_str_encoding">new Buffer(str, [encoding])</a></li>
|
||
<li><a href="#all_buf_write_string_offset_length_encoding">buf.write(string, [offset], [length], [encoding])</a></li>
|
||
<li><a href="#all_buf_tostring_encoding_start_end">buf.toString([encoding], [start], [end])</a></li>
|
||
<li><a href="#all_buf_index">buf[index]</a></li>
|
||
<li><a href="#all_class_method_buffer_isbuffer_obj">Class Method: Buffer.isBuffer(obj)</a></li>
|
||
<li><a href="#all_class_method_buffer_bytelength_string_encoding">Class Method: Buffer.byteLength(string, [encoding])</a></li>
|
||
<li><a href="#all_class_method_buffer_concat_list_totallength">Class Method: Buffer.concat(list, [totalLength])</a></li>
|
||
<li><a href="#all_buf_length">buf.length</a></li>
|
||
<li><a href="#all_buf_copy_targetbuffer_targetstart_sourcestart_sourceend">buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])</a></li>
|
||
<li><a href="#all_buf_slice_start_end">buf.slice([start], [end])</a></li>
|
||
<li><a href="#all_buf_readuint8_offset_noassert">buf.readUInt8(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readuint16le_offset_noassert">buf.readUInt16LE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readuint16be_offset_noassert">buf.readUInt16BE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readuint32le_offset_noassert">buf.readUInt32LE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readuint32be_offset_noassert">buf.readUInt32BE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readint8_offset_noassert">buf.readInt8(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readint16le_offset_noassert">buf.readInt16LE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readint16be_offset_noassert">buf.readInt16BE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readint32le_offset_noassert">buf.readInt32LE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readint32be_offset_noassert">buf.readInt32BE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readfloatle_offset_noassert">buf.readFloatLE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readfloatbe_offset_noassert">buf.readFloatBE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readdoublele_offset_noassert">buf.readDoubleLE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_readdoublebe_offset_noassert">buf.readDoubleBE(offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeuint8_value_offset_noassert">buf.writeUInt8(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeuint16le_value_offset_noassert">buf.writeUInt16LE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeuint16be_value_offset_noassert">buf.writeUInt16BE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeuint32le_value_offset_noassert">buf.writeUInt32LE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeuint32be_value_offset_noassert">buf.writeUInt32BE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeint8_value_offset_noassert">buf.writeInt8(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeint16le_value_offset_noassert">buf.writeInt16LE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeint16be_value_offset_noassert">buf.writeInt16BE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeint32le_value_offset_noassert">buf.writeInt32LE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writeint32be_value_offset_noassert">buf.writeInt32BE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writefloatle_value_offset_noassert">buf.writeFloatLE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writefloatbe_value_offset_noassert">buf.writeFloatBE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writedoublele_value_offset_noassert">buf.writeDoubleLE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_writedoublebe_value_offset_noassert">buf.writeDoubleBE(value, offset, [noAssert])</a></li>
|
||
<li><a href="#all_buf_fill_value_offset_end">buf.fill(value, [offset], [end])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_buffer_inspect_max_bytes">buffer.INSPECT_MAX_BYTES</a></li>
|
||
<li><a href="#all_class_slowbuffer">Class: SlowBuffer</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_stream">Stream</a><ul>
|
||
<li><a href="#all_readable_stream">Readable Stream</a><ul>
|
||
<li><a href="#all_event_data">Event: 'data'</a></li>
|
||
<li><a href="#all_event_end">Event: 'end'</a></li>
|
||
<li><a href="#all_event_error">Event: 'error'</a></li>
|
||
<li><a href="#all_event_close">Event: 'close'</a></li>
|
||
<li><a href="#all_stream_readable">stream.readable</a></li>
|
||
<li><a href="#all_stream_setencoding_encoding">stream.setEncoding([encoding])</a></li>
|
||
<li><a href="#all_stream_pause">stream.pause()</a></li>
|
||
<li><a href="#all_stream_resume">stream.resume()</a></li>
|
||
<li><a href="#all_stream_destroy">stream.destroy()</a></li>
|
||
<li><a href="#all_stream_pipe_destination_options">stream.pipe(destination, [options])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_writable_stream">Writable Stream</a><ul>
|
||
<li><a href="#all_event_drain">Event: 'drain'</a></li>
|
||
<li><a href="#all_event_error_1">Event: 'error'</a></li>
|
||
<li><a href="#all_event_close_1">Event: 'close'</a></li>
|
||
<li><a href="#all_event_pipe">Event: 'pipe'</a></li>
|
||
<li><a href="#all_stream_writable">stream.writable</a></li>
|
||
<li><a href="#all_stream_write_string_encoding">stream.write(string, [encoding])</a></li>
|
||
<li><a href="#all_stream_write_buffer">stream.write(buffer)</a></li>
|
||
<li><a href="#all_stream_end">stream.end()</a></li>
|
||
<li><a href="#all_stream_end_string_encoding">stream.end(string, encoding)</a></li>
|
||
<li><a href="#all_stream_end_buffer">stream.end(buffer)</a></li>
|
||
<li><a href="#all_stream_destroy_1">stream.destroy()</a></li>
|
||
<li><a href="#all_stream_destroysoon">stream.destroySoon()</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_crypto">Crypto</a><ul>
|
||
<li><a href="#all_crypto_createcredentials_details">crypto.createCredentials(details)</a></li>
|
||
<li><a href="#all_crypto_createhash_algorithm">crypto.createHash(algorithm)</a></li>
|
||
<li><a href="#all_class_hash">Class: Hash</a><ul>
|
||
<li><a href="#all_hash_update_data_input_encoding">hash.update(data, [input_encoding])</a></li>
|
||
<li><a href="#all_hash_digest_encoding">hash.digest([encoding])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_crypto_createhmac_algorithm_key">crypto.createHmac(algorithm, key)</a></li>
|
||
<li><a href="#all_class_hmac">Class: Hmac</a><ul>
|
||
<li><a href="#all_hmac_update_data">hmac.update(data)</a></li>
|
||
<li><a href="#all_hmac_digest_encoding">hmac.digest([encoding])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_crypto_createcipher_algorithm_password">crypto.createCipher(algorithm, password)</a></li>
|
||
<li><a href="#all_crypto_createcipheriv_algorithm_key_iv">crypto.createCipheriv(algorithm, key, iv)</a></li>
|
||
<li><a href="#all_class_cipher">Class: Cipher</a><ul>
|
||
<li><a href="#all_cipher_update_data_input_encoding_output_encoding">cipher.update(data, [input_encoding], [output_encoding])</a></li>
|
||
<li><a href="#all_cipher_final_output_encoding">cipher.final([output_encoding])</a></li>
|
||
<li><a href="#all_cipher_setautopadding_auto_padding_true">cipher.setAutoPadding(auto_padding=true)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_crypto_createdecipher_algorithm_password">crypto.createDecipher(algorithm, password)</a></li>
|
||
<li><a href="#all_crypto_createdecipheriv_algorithm_key_iv">crypto.createDecipheriv(algorithm, key, iv)</a></li>
|
||
<li><a href="#all_class_decipher">Class: Decipher</a><ul>
|
||
<li><a href="#all_decipher_update_data_input_encoding_output_encoding">decipher.update(data, [input_encoding], [output_encoding])</a></li>
|
||
<li><a href="#all_decipher_final_output_encoding">decipher.final([output_encoding])</a></li>
|
||
<li><a href="#all_decipher_setautopadding_auto_padding_true">decipher.setAutoPadding(auto_padding=true)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_crypto_createsign_algorithm">crypto.createSign(algorithm)</a></li>
|
||
<li><a href="#all_class_signer">Class: Signer</a><ul>
|
||
<li><a href="#all_signer_update_data">signer.update(data)</a></li>
|
||
<li><a href="#all_signer_sign_private_key_output_format">signer.sign(private_key, [output_format])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_crypto_createverify_algorithm">crypto.createVerify(algorithm)</a></li>
|
||
<li><a href="#all_class_verify">Class: Verify</a><ul>
|
||
<li><a href="#all_verifier_update_data">verifier.update(data)</a></li>
|
||
<li><a href="#all_verifier_verify_object_signature_signature_format">verifier.verify(object, signature, [signature_format])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_crypto_creatediffiehellman_prime_length">crypto.createDiffieHellman(prime_length)</a></li>
|
||
<li><a href="#all_crypto_creatediffiehellman_prime_encoding">crypto.createDiffieHellman(prime, [encoding])</a></li>
|
||
<li><a href="#all_class_diffiehellman">Class: DiffieHellman</a><ul>
|
||
<li><a href="#all_diffiehellman_generatekeys_encoding">diffieHellman.generateKeys([encoding])</a></li>
|
||
<li><a href="#all_diffiehellman_computesecret_other_public_key_input_encoding_output_encoding">diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])</a></li>
|
||
<li><a href="#all_diffiehellman_getprime_encoding">diffieHellman.getPrime([encoding])</a></li>
|
||
<li><a href="#all_diffiehellman_getgenerator_encoding">diffieHellman.getGenerator([encoding])</a></li>
|
||
<li><a href="#all_diffiehellman_getpublickey_encoding">diffieHellman.getPublicKey([encoding])</a></li>
|
||
<li><a href="#all_diffiehellman_getprivatekey_encoding">diffieHellman.getPrivateKey([encoding])</a></li>
|
||
<li><a href="#all_diffiehellman_setpublickey_public_key_encoding">diffieHellman.setPublicKey(public_key, [encoding])</a></li>
|
||
<li><a href="#all_diffiehellman_setprivatekey_public_key_encoding">diffieHellman.setPrivateKey(public_key, [encoding])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_crypto_getdiffiehellman_group_name">crypto.getDiffieHellman(group_name)</a></li>
|
||
<li><a href="#all_crypto_pbkdf2_password_salt_iterations_keylen_callback">crypto.pbkdf2(password, salt, iterations, keylen, callback)</a></li>
|
||
<li><a href="#all_crypto_randombytes_size_callback">crypto.randomBytes(size, [callback])</a></li>
|
||
<li><a href="#all_proposed_api_changes_in_future_versions_of_node">Proposed API Changes in Future Versions of Node</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_tls_ssl">TLS (SSL)</a><ul>
|
||
<li><a href="#all_client_initiated_renegotiation_attack_mitigation">Client-initiated renegotiation attack mitigation</a></li>
|
||
<li><a href="#all_npn_and_sni">NPN and SNI</a></li>
|
||
<li><a href="#all_tls_createserver_options_secureconnectionlistener">tls.createServer(options, [secureConnectionListener])</a></li>
|
||
<li><a href="#all_tls_connect_options_callback">tls.connect(options, [callback])</a></li>
|
||
<li><a href="#all_tls_connect_port_host_options_callback">tls.connect(port, [host], [options], [callback])</a></li>
|
||
<li><a href="#all_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized">tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])</a></li>
|
||
<li><a href="#all_class_securepair">Class: SecurePair</a><ul>
|
||
<li><a href="#all_event_secure">Event: 'secure'</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_class_tls_server">Class: tls.Server</a><ul>
|
||
<li><a href="#all_event_secureconnection">Event: 'secureConnection'</a></li>
|
||
<li><a href="#all_event_clienterror">Event: 'clientError'</a></li>
|
||
<li><a href="#all_server_listen_port_host_callback">server.listen(port, [host], [callback])</a></li>
|
||
<li><a href="#all_server_close">server.close()</a></li>
|
||
<li><a href="#all_server_address">server.address()</a></li>
|
||
<li><a href="#all_server_addcontext_hostname_credentials">server.addContext(hostname, credentials)</a></li>
|
||
<li><a href="#all_server_maxconnections">server.maxConnections</a></li>
|
||
<li><a href="#all_server_connections">server.connections</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_class_tls_cleartextstream">Class: tls.CleartextStream</a><ul>
|
||
<li><a href="#all_event_secureconnect">Event: 'secureConnect'</a></li>
|
||
<li><a href="#all_cleartextstream_authorized">cleartextStream.authorized</a></li>
|
||
<li><a href="#all_cleartextstream_authorizationerror">cleartextStream.authorizationError</a></li>
|
||
<li><a href="#all_cleartextstream_getpeercertificate">cleartextStream.getPeerCertificate()</a></li>
|
||
<li><a href="#all_cleartextstream_getcipher">cleartextStream.getCipher()</a></li>
|
||
<li><a href="#all_cleartextstream_address">cleartextStream.address()</a></li>
|
||
<li><a href="#all_cleartextstream_remoteaddress">cleartextStream.remoteAddress</a></li>
|
||
<li><a href="#all_cleartextstream_remoteport">cleartextStream.remotePort</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_stringdecoder">StringDecoder</a><ul>
|
||
<li><a href="#all_class_stringdecoder">Class: StringDecoder</a><ul>
|
||
<li><a href="#all_stringdecoder_write_buffer">StringDecoder.write(buffer)</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_file_system">File System</a><ul>
|
||
<li><a href="#all_fs_rename_oldpath_newpath_callback">fs.rename(oldPath, newPath, [callback])</a></li>
|
||
<li><a href="#all_fs_renamesync_oldpath_newpath">fs.renameSync(oldPath, newPath)</a></li>
|
||
<li><a href="#all_fs_truncate_fd_len_callback">fs.truncate(fd, len, [callback])</a></li>
|
||
<li><a href="#all_fs_truncatesync_fd_len">fs.truncateSync(fd, len)</a></li>
|
||
<li><a href="#all_fs_chown_path_uid_gid_callback">fs.chown(path, uid, gid, [callback])</a></li>
|
||
<li><a href="#all_fs_chownsync_path_uid_gid">fs.chownSync(path, uid, gid)</a></li>
|
||
<li><a href="#all_fs_fchown_fd_uid_gid_callback">fs.fchown(fd, uid, gid, [callback])</a></li>
|
||
<li><a href="#all_fs_fchownsync_fd_uid_gid">fs.fchownSync(fd, uid, gid)</a></li>
|
||
<li><a href="#all_fs_lchown_path_uid_gid_callback">fs.lchown(path, uid, gid, [callback])</a></li>
|
||
<li><a href="#all_fs_lchownsync_path_uid_gid">fs.lchownSync(path, uid, gid)</a></li>
|
||
<li><a href="#all_fs_chmod_path_mode_callback">fs.chmod(path, mode, [callback])</a></li>
|
||
<li><a href="#all_fs_chmodsync_path_mode">fs.chmodSync(path, mode)</a></li>
|
||
<li><a href="#all_fs_fchmod_fd_mode_callback">fs.fchmod(fd, mode, [callback])</a></li>
|
||
<li><a href="#all_fs_fchmodsync_fd_mode">fs.fchmodSync(fd, mode)</a></li>
|
||
<li><a href="#all_fs_lchmod_path_mode_callback">fs.lchmod(path, mode, [callback])</a></li>
|
||
<li><a href="#all_fs_lchmodsync_path_mode">fs.lchmodSync(path, mode)</a></li>
|
||
<li><a href="#all_fs_stat_path_callback">fs.stat(path, [callback])</a></li>
|
||
<li><a href="#all_fs_lstat_path_callback">fs.lstat(path, [callback])</a></li>
|
||
<li><a href="#all_fs_fstat_fd_callback">fs.fstat(fd, [callback])</a></li>
|
||
<li><a href="#all_fs_statsync_path">fs.statSync(path)</a></li>
|
||
<li><a href="#all_fs_lstatsync_path">fs.lstatSync(path)</a></li>
|
||
<li><a href="#all_fs_fstatsync_fd">fs.fstatSync(fd)</a></li>
|
||
<li><a href="#all_fs_link_srcpath_dstpath_callback">fs.link(srcpath, dstpath, [callback])</a></li>
|
||
<li><a href="#all_fs_linksync_srcpath_dstpath">fs.linkSync(srcpath, dstpath)</a></li>
|
||
<li><a href="#all_fs_symlink_srcpath_dstpath_type_callback">fs.symlink(srcpath, dstpath, [type], [callback])</a></li>
|
||
<li><a href="#all_fs_symlinksync_srcpath_dstpath_type">fs.symlinkSync(srcpath, dstpath, [type])</a></li>
|
||
<li><a href="#all_fs_readlink_path_callback">fs.readlink(path, [callback])</a></li>
|
||
<li><a href="#all_fs_readlinksync_path">fs.readlinkSync(path)</a></li>
|
||
<li><a href="#all_fs_realpath_path_cache_callback">fs.realpath(path, [cache], callback)</a></li>
|
||
<li><a href="#all_fs_realpathsync_path_cache">fs.realpathSync(path, [cache])</a></li>
|
||
<li><a href="#all_fs_unlink_path_callback">fs.unlink(path, [callback])</a></li>
|
||
<li><a href="#all_fs_unlinksync_path">fs.unlinkSync(path)</a></li>
|
||
<li><a href="#all_fs_rmdir_path_callback">fs.rmdir(path, [callback])</a></li>
|
||
<li><a href="#all_fs_rmdirsync_path">fs.rmdirSync(path)</a></li>
|
||
<li><a href="#all_fs_mkdir_path_mode_callback">fs.mkdir(path, [mode], [callback])</a></li>
|
||
<li><a href="#all_fs_mkdirsync_path_mode">fs.mkdirSync(path, [mode])</a></li>
|
||
<li><a href="#all_fs_readdir_path_callback">fs.readdir(path, [callback])</a></li>
|
||
<li><a href="#all_fs_readdirsync_path">fs.readdirSync(path)</a></li>
|
||
<li><a href="#all_fs_close_fd_callback">fs.close(fd, [callback])</a></li>
|
||
<li><a href="#all_fs_closesync_fd">fs.closeSync(fd)</a></li>
|
||
<li><a href="#all_fs_open_path_flags_mode_callback">fs.open(path, flags, [mode], [callback])</a></li>
|
||
<li><a href="#all_fs_opensync_path_flags_mode">fs.openSync(path, flags, [mode])</a></li>
|
||
<li><a href="#all_fs_utimes_path_atime_mtime_callback">fs.utimes(path, atime, mtime, [callback])</a></li>
|
||
<li><a href="#all_fs_utimessync_path_atime_mtime">fs.utimesSync(path, atime, mtime)</a></li>
|
||
<li><a href="#all_fs_futimes_fd_atime_mtime_callback">fs.futimes(fd, atime, mtime, [callback])</a></li>
|
||
<li><a href="#all_fs_futimessync_fd_atime_mtime">fs.futimesSync(fd, atime, mtime)</a></li>
|
||
<li><a href="#all_fs_fsync_fd_callback">fs.fsync(fd, [callback])</a></li>
|
||
<li><a href="#all_fs_fsyncsync_fd">fs.fsyncSync(fd)</a></li>
|
||
<li><a href="#all_fs_write_fd_buffer_offset_length_position_callback">fs.write(fd, buffer, offset, length, position, [callback])</a></li>
|
||
<li><a href="#all_fs_writesync_fd_buffer_offset_length_position">fs.writeSync(fd, buffer, offset, length, position)</a></li>
|
||
<li><a href="#all_fs_read_fd_buffer_offset_length_position_callback">fs.read(fd, buffer, offset, length, position, [callback])</a></li>
|
||
<li><a href="#all_fs_readsync_fd_buffer_offset_length_position">fs.readSync(fd, buffer, offset, length, position)</a></li>
|
||
<li><a href="#all_fs_readfile_filename_encoding_callback">fs.readFile(filename, [encoding], [callback])</a></li>
|
||
<li><a href="#all_fs_readfilesync_filename_encoding">fs.readFileSync(filename, [encoding])</a></li>
|
||
<li><a href="#all_fs_writefile_filename_data_encoding_callback">fs.writeFile(filename, data, [encoding], [callback])</a></li>
|
||
<li><a href="#all_fs_writefilesync_filename_data_encoding">fs.writeFileSync(filename, data, [encoding])</a></li>
|
||
<li><a href="#all_fs_appendfile_filename_data_encoding_utf8_callback">fs.appendFile(filename, data, encoding='utf8', [callback])</a></li>
|
||
<li><a href="#all_fs_appendfilesync_filename_data_encoding_utf8">fs.appendFileSync(filename, data, encoding='utf8')</a></li>
|
||
<li><a href="#all_fs_watchfile_filename_options_listener">fs.watchFile(filename, [options], listener)</a></li>
|
||
<li><a href="#all_fs_unwatchfile_filename_listener">fs.unwatchFile(filename, [listener])</a></li>
|
||
<li><a href="#all_fs_watch_filename_options_listener">fs.watch(filename, [options], [listener])</a><ul>
|
||
<li><a href="#all_caveats">Caveats</a><ul>
|
||
<li><a href="#all_availability">Availability</a></li>
|
||
<li><a href="#all_filename_argument">Filename Argument</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_fs_exists_path_callback">fs.exists(path, [callback])</a></li>
|
||
<li><a href="#all_fs_existssync_path">fs.existsSync(path)</a></li>
|
||
<li><a href="#all_class_fs_stats">Class: fs.Stats</a></li>
|
||
<li><a href="#all_fs_createreadstream_path_options">fs.createReadStream(path, [options])</a></li>
|
||
<li><a href="#all_class_fs_readstream">Class: fs.ReadStream</a><ul>
|
||
<li><a href="#all_event_open">Event: 'open'</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_fs_createwritestream_path_options">fs.createWriteStream(path, [options])</a></li>
|
||
<li><a href="#all_fs_writestream">fs.WriteStream</a><ul>
|
||
<li><a href="#all_event_open_1">Event: 'open'</a></li>
|
||
<li><a href="#all_file_byteswritten">file.bytesWritten</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_class_fs_fswatcher">Class: fs.FSWatcher</a><ul>
|
||
<li><a href="#all_watcher_close">watcher.close()</a></li>
|
||
<li><a href="#all_event_change">Event: 'change'</a></li>
|
||
<li><a href="#all_event_error_2">Event: 'error'</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_path">Path</a><ul>
|
||
<li><a href="#all_path_normalize_p">path.normalize(p)</a></li>
|
||
<li><a href="#all_path_join_path1_path2">path.join([path1], [path2], [...])</a></li>
|
||
<li><a href="#all_path_resolve_from_to">path.resolve([from ...], to)</a></li>
|
||
<li><a href="#all_path_relative_from_to">path.relative(from, to)</a></li>
|
||
<li><a href="#all_path_dirname_p">path.dirname(p)</a></li>
|
||
<li><a href="#all_path_basename_p_ext">path.basename(p, [ext])</a></li>
|
||
<li><a href="#all_path_extname_p">path.extname(p)</a></li>
|
||
<li><a href="#all_path_sep">path.sep</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_net">net</a><ul>
|
||
<li><a href="#all_net_createserver_options_connectionlistener">net.createServer([options], [connectionListener])</a></li>
|
||
<li><a href="#all_net_connect_options_connectionlistener">net.connect(options, [connectionListener])</a></li>
|
||
<li><a href="#all_net_createconnection_options_connectionlistener">net.createConnection(options, [connectionListener])</a></li>
|
||
<li><a href="#all_net_connect_port_host_connectlistener">net.connect(port, [host], [connectListener])</a></li>
|
||
<li><a href="#all_net_createconnection_port_host_connectlistener">net.createConnection(port, [host], [connectListener])</a></li>
|
||
<li><a href="#all_net_connect_path_connectlistener">net.connect(path, [connectListener])</a></li>
|
||
<li><a href="#all_net_createconnection_path_connectlistener">net.createConnection(path, [connectListener])</a></li>
|
||
<li><a href="#all_class_net_server">Class: net.Server</a><ul>
|
||
<li><a href="#all_server_listen_port_host_backlog_callback">server.listen(port, [host], [backlog], [callback])</a></li>
|
||
<li><a href="#all_server_listen_path_callback">server.listen(path, [callback])</a></li>
|
||
<li><a href="#all_server_listen_handle_callback">server.listen(handle, [callback])</a></li>
|
||
<li><a href="#all_server_close_callback">server.close([callback])</a></li>
|
||
<li><a href="#all_server_address_1">server.address()</a></li>
|
||
<li><a href="#all_server_maxconnections_1">server.maxConnections</a></li>
|
||
<li><a href="#all_server_connections_1">server.connections</a></li>
|
||
<li><a href="#all_event_listening">Event: 'listening'</a></li>
|
||
<li><a href="#all_event_connection">Event: 'connection'</a></li>
|
||
<li><a href="#all_event_close_2">Event: 'close'</a></li>
|
||
<li><a href="#all_event_error_3">Event: 'error'</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_class_net_socket">Class: net.Socket</a><ul>
|
||
<li><a href="#all_new_net_socket_options">new net.Socket([options])</a></li>
|
||
<li><a href="#all_socket_connect_port_host_connectlistener">socket.connect(port, [host], [connectListener])</a></li>
|
||
<li><a href="#all_socket_connect_path_connectlistener">socket.connect(path, [connectListener])</a></li>
|
||
<li><a href="#all_socket_buffersize">socket.bufferSize</a></li>
|
||
<li><a href="#all_socket_setencoding_encoding">socket.setEncoding([encoding])</a></li>
|
||
<li><a href="#all_socket_write_data_encoding_callback">socket.write(data, [encoding], [callback])</a></li>
|
||
<li><a href="#all_socket_end_data_encoding">socket.end([data], [encoding])</a></li>
|
||
<li><a href="#all_socket_destroy">socket.destroy()</a></li>
|
||
<li><a href="#all_socket_pause">socket.pause()</a></li>
|
||
<li><a href="#all_socket_resume">socket.resume()</a></li>
|
||
<li><a href="#all_socket_settimeout_timeout_callback">socket.setTimeout(timeout, [callback])</a></li>
|
||
<li><a href="#all_socket_setnodelay_nodelay">socket.setNoDelay([noDelay])</a></li>
|
||
<li><a href="#all_socket_setkeepalive_enable_initialdelay">socket.setKeepAlive([enable], [initialDelay])</a></li>
|
||
<li><a href="#all_socket_address">socket.address()</a></li>
|
||
<li><a href="#all_socket_remoteaddress">socket.remoteAddress</a></li>
|
||
<li><a href="#all_socket_remoteport">socket.remotePort</a></li>
|
||
<li><a href="#all_socket_bytesread">socket.bytesRead</a></li>
|
||
<li><a href="#all_socket_byteswritten">socket.bytesWritten</a></li>
|
||
<li><a href="#all_event_connect">Event: 'connect'</a></li>
|
||
<li><a href="#all_event_data_1">Event: 'data'</a></li>
|
||
<li><a href="#all_event_end_1">Event: 'end'</a></li>
|
||
<li><a href="#all_event_timeout">Event: 'timeout'</a></li>
|
||
<li><a href="#all_event_drain_1">Event: 'drain'</a></li>
|
||
<li><a href="#all_event_error_4">Event: 'error'</a></li>
|
||
<li><a href="#all_event_close_3">Event: 'close'</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_net_isip_input">net.isIP(input)</a></li>
|
||
<li><a href="#all_net_isipv4_input">net.isIPv4(input)</a></li>
|
||
<li><a href="#all_net_isipv6_input">net.isIPv6(input)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_udp_datagram_sockets">UDP / Datagram Sockets</a><ul>
|
||
<li><a href="#all_dgram_createsocket_type_callback">dgram.createSocket(type, [callback])</a></li>
|
||
<li><a href="#all_class_socket">Class: Socket</a><ul>
|
||
<li><a href="#all_event_message">Event: 'message'</a></li>
|
||
<li><a href="#all_event_listening_1">Event: 'listening'</a></li>
|
||
<li><a href="#all_event_close_4">Event: 'close'</a></li>
|
||
<li><a href="#all_event_error_5">Event: 'error'</a></li>
|
||
<li><a href="#all_dgram_send_buf_offset_length_port_address_callback">dgram.send(buf, offset, length, port, address, [callback])</a></li>
|
||
<li><a href="#all_dgram_bind_port_address">dgram.bind(port, [address])</a></li>
|
||
<li><a href="#all_dgram_close">dgram.close()</a></li>
|
||
<li><a href="#all_dgram_address">dgram.address()</a></li>
|
||
<li><a href="#all_dgram_setbroadcast_flag">dgram.setBroadcast(flag)</a></li>
|
||
<li><a href="#all_dgram_setttl_ttl">dgram.setTTL(ttl)</a></li>
|
||
<li><a href="#all_dgram_setmulticastttl_ttl">dgram.setMulticastTTL(ttl)</a></li>
|
||
<li><a href="#all_dgram_setmulticastloopback_flag">dgram.setMulticastLoopback(flag)</a></li>
|
||
<li><a href="#all_dgram_addmembership_multicastaddress_multicastinterface">dgram.addMembership(multicastAddress, [multicastInterface])</a></li>
|
||
<li><a href="#all_dgram_dropmembership_multicastaddress_multicastinterface">dgram.dropMembership(multicastAddress, [multicastInterface])</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_dns">DNS</a><ul>
|
||
<li><a href="#all_dns_lookup_domain_family_callback">dns.lookup(domain, [family], callback)</a></li>
|
||
<li><a href="#all_dns_resolve_domain_rrtype_callback">dns.resolve(domain, [rrtype], callback)</a></li>
|
||
<li><a href="#all_dns_resolve4_domain_callback">dns.resolve4(domain, callback)</a></li>
|
||
<li><a href="#all_dns_resolve6_domain_callback">dns.resolve6(domain, callback)</a></li>
|
||
<li><a href="#all_dns_resolvemx_domain_callback">dns.resolveMx(domain, callback)</a></li>
|
||
<li><a href="#all_dns_resolvetxt_domain_callback">dns.resolveTxt(domain, callback)</a></li>
|
||
<li><a href="#all_dns_resolvesrv_domain_callback">dns.resolveSrv(domain, callback)</a></li>
|
||
<li><a href="#all_dns_resolvens_domain_callback">dns.resolveNs(domain, callback)</a></li>
|
||
<li><a href="#all_dns_resolvecname_domain_callback">dns.resolveCname(domain, callback)</a></li>
|
||
<li><a href="#all_dns_reverse_ip_callback">dns.reverse(ip, callback)</a></li>
|
||
<li><a href="#all_error_codes">Error codes</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_http">HTTP</a><ul>
|
||
<li><a href="#all_http_status_codes">http.STATUS_CODES</a></li>
|
||
<li><a href="#all_http_createserver_requestlistener">http.createServer([requestListener])</a></li>
|
||
<li><a href="#all_http_createclient_port_host">http.createClient([port], [host])</a></li>
|
||
<li><a href="#all_class_http_server">Class: http.Server</a><ul>
|
||
<li><a href="#all_event_request">Event: 'request'</a></li>
|
||
<li><a href="#all_event_connection_1">Event: 'connection'</a></li>
|
||
<li><a href="#all_event_close_5">Event: 'close'</a></li>
|
||
<li><a href="#all_event_checkcontinue">Event: 'checkContinue'</a></li>
|
||
<li><a href="#all_event_connect_1">Event: 'connect'</a></li>
|
||
<li><a href="#all_event_upgrade">Event: 'upgrade'</a></li>
|
||
<li><a href="#all_event_clienterror_1">Event: 'clientError'</a></li>
|
||
<li><a href="#all_server_listen_port_hostname_backlog_callback">server.listen(port, [hostname], [backlog], [callback])</a></li>
|
||
<li><a href="#all_server_listen_path_callback_1">server.listen(path, [callback])</a></li>
|
||
<li><a href="#all_server_listen_handle_callback_1">server.listen(handle, [callback])</a></li>
|
||
<li><a href="#all_server_close_callback_1">server.close([callback])</a></li>
|
||
<li><a href="#all_server_maxheaderscount">server.maxHeadersCount</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_class_http_serverrequest">Class: http.ServerRequest</a><ul>
|
||
<li><a href="#all_event_data_2">Event: 'data'</a></li>
|
||
<li><a href="#all_event_end_2">Event: 'end'</a></li>
|
||
<li><a href="#all_event_close_6">Event: 'close'</a></li>
|
||
<li><a href="#all_request_method">request.method</a></li>
|
||
<li><a href="#all_request_url">request.url</a></li>
|
||
<li><a href="#all_request_headers">request.headers</a></li>
|
||
<li><a href="#all_request_trailers">request.trailers</a></li>
|
||
<li><a href="#all_request_httpversion">request.httpVersion</a></li>
|
||
<li><a href="#all_request_setencoding_encoding">request.setEncoding([encoding])</a></li>
|
||
<li><a href="#all_request_pause">request.pause()</a></li>
|
||
<li><a href="#all_request_resume">request.resume()</a></li>
|
||
<li><a href="#all_request_connection">request.connection</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_class_http_serverresponse">Class: http.ServerResponse</a><ul>
|
||
<li><a href="#all_event_close_7">Event: 'close'</a></li>
|
||
<li><a href="#all_response_writecontinue">response.writeContinue()</a></li>
|
||
<li><a href="#all_response_writehead_statuscode_reasonphrase_headers">response.writeHead(statusCode, [reasonPhrase], [headers])</a></li>
|
||
<li><a href="#all_response_statuscode">response.statusCode</a></li>
|
||
<li><a href="#all_response_setheader_name_value">response.setHeader(name, value)</a></li>
|
||
<li><a href="#all_response_senddate">response.sendDate</a></li>
|
||
<li><a href="#all_response_getheader_name">response.getHeader(name)</a></li>
|
||
<li><a href="#all_response_removeheader_name">response.removeHeader(name)</a></li>
|
||
<li><a href="#all_response_write_chunk_encoding">response.write(chunk, [encoding])</a></li>
|
||
<li><a href="#all_response_addtrailers_headers">response.addTrailers(headers)</a></li>
|
||
<li><a href="#all_response_end_data_encoding">response.end([data], [encoding])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_http_request_options_callback">http.request(options, callback)</a></li>
|
||
<li><a href="#all_http_get_options_callback">http.get(options, callback)</a></li>
|
||
<li><a href="#all_class_http_agent">Class: http.Agent</a><ul>
|
||
<li><a href="#all_agent_maxsockets">agent.maxSockets</a></li>
|
||
<li><a href="#all_agent_sockets">agent.sockets</a></li>
|
||
<li><a href="#all_agent_requests">agent.requests</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_http_globalagent">http.globalAgent</a></li>
|
||
<li><a href="#all_class_http_clientrequest">Class: http.ClientRequest</a><ul>
|
||
<li><a href="#all_event_response">Event 'response'</a></li>
|
||
<li><a href="#all_event_socket">Event: 'socket'</a></li>
|
||
<li><a href="#all_event_connect_2">Event: 'connect'</a></li>
|
||
<li><a href="#all_event_upgrade_1">Event: 'upgrade'</a></li>
|
||
<li><a href="#all_event_continue">Event: 'continue'</a></li>
|
||
<li><a href="#all_request_write_chunk_encoding">request.write(chunk, [encoding])</a></li>
|
||
<li><a href="#all_request_end_data_encoding">request.end([data], [encoding])</a></li>
|
||
<li><a href="#all_request_abort">request.abort()</a></li>
|
||
<li><a href="#all_request_settimeout_timeout_callback">request.setTimeout(timeout, [callback])</a></li>
|
||
<li><a href="#all_request_setnodelay_nodelay">request.setNoDelay([noDelay])</a></li>
|
||
<li><a href="#all_request_setsocketkeepalive_enable_initialdelay">request.setSocketKeepAlive([enable], [initialDelay])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_http_clientresponse">http.ClientResponse</a><ul>
|
||
<li><a href="#all_event_data_3">Event: 'data'</a></li>
|
||
<li><a href="#all_event_end_3">Event: 'end'</a></li>
|
||
<li><a href="#all_event_close_8">Event: 'close'</a></li>
|
||
<li><a href="#all_response_statuscode_1">response.statusCode</a></li>
|
||
<li><a href="#all_response_httpversion">response.httpVersion</a></li>
|
||
<li><a href="#all_response_headers">response.headers</a></li>
|
||
<li><a href="#all_response_trailers">response.trailers</a></li>
|
||
<li><a href="#all_response_setencoding_encoding">response.setEncoding([encoding])</a></li>
|
||
<li><a href="#all_response_pause">response.pause()</a></li>
|
||
<li><a href="#all_response_resume">response.resume()</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_https">HTTPS</a><ul>
|
||
<li><a href="#all_class_https_server">Class: https.Server</a></li>
|
||
<li><a href="#all_https_createserver_options_requestlistener">https.createServer(options, [requestListener])</a><ul>
|
||
<li><a href="#all_server_listen_port_host_backlog_callback_1">server.listen(port, [host], [backlog], [callback])</a></li>
|
||
<li><a href="#all_server_listen_path_callback_2">server.listen(path, [callback])</a></li>
|
||
<li><a href="#all_server_listen_handle_callback_2">server.listen(handle, [callback])</a></li>
|
||
<li><a href="#all_server_close_callback_2">server.close([callback])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_https_request_options_callback">https.request(options, callback)</a></li>
|
||
<li><a href="#all_https_get_options_callback">https.get(options, callback)</a></li>
|
||
<li><a href="#all_class_https_agent">Class: https.Agent</a></li>
|
||
<li><a href="#all_https_globalagent">https.globalAgent</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_url">URL</a><ul>
|
||
<li><a href="#all_url_parse_urlstr_parsequerystring_slashesdenotehost">url.parse(urlStr, [parseQueryString], [slashesDenoteHost])</a></li>
|
||
<li><a href="#all_url_format_urlobj">url.format(urlObj)</a></li>
|
||
<li><a href="#all_url_resolve_from_to">url.resolve(from, to)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_query_string">Query String</a><ul>
|
||
<li><a href="#all_querystring_stringify_obj_sep_eq">querystring.stringify(obj, [sep], [eq])</a></li>
|
||
<li><a href="#all_querystring_parse_str_sep_eq_options">querystring.parse(str, [sep], [eq], [options])</a></li>
|
||
<li><a href="#all_querystring_escape">querystring.escape</a></li>
|
||
<li><a href="#all_querystring_unescape">querystring.unescape</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_punycode">punycode</a><ul>
|
||
<li><a href="#all_punycode_decode_string">punycode.decode(string)</a></li>
|
||
<li><a href="#all_punycode_encode_string">punycode.encode(string)</a></li>
|
||
<li><a href="#all_punycode_tounicode_domain">punycode.toUnicode(domain)</a></li>
|
||
<li><a href="#all_punycode_toascii_domain">punycode.toASCII(domain)</a></li>
|
||
<li><a href="#all_punycode_ucs2">punycode.ucs2</a><ul>
|
||
<li><a href="#all_punycode_ucs2_decode_string">punycode.ucs2.decode(string)</a></li>
|
||
<li><a href="#all_punycode_ucs2_encode_codepoints">punycode.ucs2.encode(codePoints)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_punycode_version">punycode.version</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_readline">Readline</a><ul>
|
||
<li><a href="#all_readline_createinterface_options">readline.createInterface(options)</a></li>
|
||
<li><a href="#all_class_interface">Class: Interface</a><ul>
|
||
<li><a href="#all_rl_setprompt_prompt_length">rl.setPrompt(prompt, length)</a></li>
|
||
<li><a href="#all_rl_prompt_preservecursor">rl.prompt([preserveCursor])</a></li>
|
||
<li><a href="#all_rl_question_query_callback">rl.question(query, callback)</a></li>
|
||
<li><a href="#all_rl_pause">rl.pause()</a></li>
|
||
<li><a href="#all_rl_resume">rl.resume()</a></li>
|
||
<li><a href="#all_rl_close">rl.close()</a></li>
|
||
<li><a href="#all_rl_write_data_key">rl.write(data, [key])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_events_1">Events</a><ul>
|
||
<li><a href="#all_event_line">Event: 'line'</a></li>
|
||
<li><a href="#all_event_pause">Event: 'pause'</a></li>
|
||
<li><a href="#all_event_resume">Event: 'resume'</a></li>
|
||
<li><a href="#all_event_close_9">Event: 'close'</a></li>
|
||
<li><a href="#all_event_sigint">Event: 'SIGINT'</a></li>
|
||
<li><a href="#all_event_sigtstp">Event: 'SIGTSTP'</a></li>
|
||
<li><a href="#all_event_sigcont">Event: 'SIGCONT'</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_example_tiny_cli">Example: Tiny CLI</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_repl">REPL</a><ul>
|
||
<li><a href="#all_repl_start_options">repl.start(options)</a><ul>
|
||
<li><a href="#all_event_exit_1">Event: 'exit'</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_repl_features">REPL Features</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_executing_javascript">Executing JavaScript</a><ul>
|
||
<li><a href="#all_caveats_1">Caveats</a><ul>
|
||
<li><a href="#all_sandboxes">Sandboxes</a></li>
|
||
<li><a href="#all_globals">Globals</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_vm_runinthiscontext_code_filename">vm.runInThisContext(code, [filename])</a></li>
|
||
<li><a href="#all_vm_runinnewcontext_code_sandbox_filename">vm.runInNewContext(code, [sandbox], [filename])</a></li>
|
||
<li><a href="#all_vm_runincontext_code_context_filename">vm.runInContext(code, context, [filename])</a></li>
|
||
<li><a href="#all_vm_createcontext_initsandbox">vm.createContext([initSandbox])</a></li>
|
||
<li><a href="#all_vm_createscript_code_filename">vm.createScript(code, [filename])</a></li>
|
||
<li><a href="#all_class_script">Class: Script</a><ul>
|
||
<li><a href="#all_script_runinthiscontext">script.runInThisContext()</a></li>
|
||
<li><a href="#all_script_runinnewcontext_sandbox">script.runInNewContext([sandbox])</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_child_process">Child Process</a><ul>
|
||
<li><a href="#all_class_childprocess">Class: ChildProcess</a><ul>
|
||
<li><a href="#all_event_exit_2">Event: 'exit'</a></li>
|
||
<li><a href="#all_event_close_10">Event: 'close'</a></li>
|
||
<li><a href="#all_event_disconnect">Event: 'disconnect'</a></li>
|
||
<li><a href="#all_event_message_1">Event: 'message'</a></li>
|
||
<li><a href="#all_child_stdin">child.stdin</a></li>
|
||
<li><a href="#all_child_stdout">child.stdout</a></li>
|
||
<li><a href="#all_child_stderr">child.stderr</a></li>
|
||
<li><a href="#all_child_pid">child.pid</a></li>
|
||
<li><a href="#all_child_kill_signal">child.kill([signal])</a></li>
|
||
<li><a href="#all_child_send_message_sendhandle">child.send(message, [sendHandle])</a></li>
|
||
<li><a href="#all_child_disconnect">child.disconnect()</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_child_process_spawn_command_args_options">child_process.spawn(command, [args], [options])</a></li>
|
||
<li><a href="#all_child_process_exec_command_options_callback">child_process.exec(command, [options], callback)</a></li>
|
||
<li><a href="#all_child_process_execfile_file_args_options_callback">child_process.execFile(file, args, options, callback)</a></li>
|
||
<li><a href="#all_child_process_fork_modulepath_args_options">child_process.fork(modulePath, [args], [options])</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_assert">Assert</a><ul>
|
||
<li><a href="#all_assert_fail_actual_expected_message_operator">assert.fail(actual, expected, message, operator)</a></li>
|
||
<li><a href="#all_assert_value_message_assert_ok_value_message">assert(value, message), assert.ok(value, [message])</a></li>
|
||
<li><a href="#all_assert_equal_actual_expected_message">assert.equal(actual, expected, [message])</a></li>
|
||
<li><a href="#all_assert_notequal_actual_expected_message">assert.notEqual(actual, expected, [message])</a></li>
|
||
<li><a href="#all_assert_deepequal_actual_expected_message">assert.deepEqual(actual, expected, [message])</a></li>
|
||
<li><a href="#all_assert_notdeepequal_actual_expected_message">assert.notDeepEqual(actual, expected, [message])</a></li>
|
||
<li><a href="#all_assert_strictequal_actual_expected_message">assert.strictEqual(actual, expected, [message])</a></li>
|
||
<li><a href="#all_assert_notstrictequal_actual_expected_message">assert.notStrictEqual(actual, expected, [message])</a></li>
|
||
<li><a href="#all_assert_throws_block_error_message">assert.throws(block, [error], [message])</a></li>
|
||
<li><a href="#all_assert_doesnotthrow_block_error_message">assert.doesNotThrow(block, [error], [message])</a></li>
|
||
<li><a href="#all_assert_iferror_value">assert.ifError(value)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_tty">TTY</a><ul>
|
||
<li><a href="#all_tty_isatty_fd">tty.isatty(fd)</a></li>
|
||
<li><a href="#all_tty_setrawmode_mode">tty.setRawMode(mode)</a></li>
|
||
<li><a href="#all_class_readstream">Class: ReadStream</a><ul>
|
||
<li><a href="#all_rs_israw">rs.isRaw</a></li>
|
||
<li><a href="#all_rs_setrawmode_mode">rs.setRawMode(mode)</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_class_writestream">Class WriteStream</a><ul>
|
||
<li><a href="#all_ws_columns">ws.columns</a></li>
|
||
<li><a href="#all_ws_rows">ws.rows</a></li>
|
||
<li><a href="#all_event_resize">Event: 'resize'</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_zlib">Zlib</a><ul>
|
||
<li><a href="#all_examples">Examples</a></li>
|
||
<li><a href="#all_zlib_creategzip_options">zlib.createGzip([options])</a></li>
|
||
<li><a href="#all_zlib_creategunzip_options">zlib.createGunzip([options])</a></li>
|
||
<li><a href="#all_zlib_createdeflate_options">zlib.createDeflate([options])</a></li>
|
||
<li><a href="#all_zlib_createinflate_options">zlib.createInflate([options])</a></li>
|
||
<li><a href="#all_zlib_createdeflateraw_options">zlib.createDeflateRaw([options])</a></li>
|
||
<li><a href="#all_zlib_createinflateraw_options">zlib.createInflateRaw([options])</a></li>
|
||
<li><a href="#all_zlib_createunzip_options">zlib.createUnzip([options])</a></li>
|
||
<li><a href="#all_class_zlib_gzip">Class: zlib.Gzip</a></li>
|
||
<li><a href="#all_class_zlib_gunzip">Class: zlib.Gunzip</a></li>
|
||
<li><a href="#all_class_zlib_deflate">Class: zlib.Deflate</a></li>
|
||
<li><a href="#all_class_zlib_inflate">Class: zlib.Inflate</a></li>
|
||
<li><a href="#all_class_zlib_deflateraw">Class: zlib.DeflateRaw</a></li>
|
||
<li><a href="#all_class_zlib_inflateraw">Class: zlib.InflateRaw</a></li>
|
||
<li><a href="#all_class_zlib_unzip">Class: zlib.Unzip</a></li>
|
||
<li><a href="#all_convenience_methods">Convenience Methods</a></li>
|
||
<li><a href="#all_zlib_deflate_buf_callback">zlib.deflate(buf, callback)</a></li>
|
||
<li><a href="#all_zlib_deflateraw_buf_callback">zlib.deflateRaw(buf, callback)</a></li>
|
||
<li><a href="#all_zlib_gzip_buf_callback">zlib.gzip(buf, callback)</a></li>
|
||
<li><a href="#all_zlib_gunzip_buf_callback">zlib.gunzip(buf, callback)</a></li>
|
||
<li><a href="#all_zlib_inflate_buf_callback">zlib.inflate(buf, callback)</a></li>
|
||
<li><a href="#all_zlib_inflateraw_buf_callback">zlib.inflateRaw(buf, callback)</a></li>
|
||
<li><a href="#all_zlib_unzip_buf_callback">zlib.unzip(buf, callback)</a></li>
|
||
<li><a href="#all_options">Options</a></li>
|
||
<li><a href="#all_memory_usage_tuning">Memory Usage Tuning</a></li>
|
||
<li><a href="#all_constants">Constants</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_os">os</a><ul>
|
||
<li><a href="#all_os_tmpdir">os.tmpDir()</a></li>
|
||
<li><a href="#all_os_hostname">os.hostname()</a></li>
|
||
<li><a href="#all_os_type">os.type()</a></li>
|
||
<li><a href="#all_os_platform">os.platform()</a></li>
|
||
<li><a href="#all_os_arch">os.arch()</a></li>
|
||
<li><a href="#all_os_release">os.release()</a></li>
|
||
<li><a href="#all_os_uptime">os.uptime()</a></li>
|
||
<li><a href="#all_os_loadavg">os.loadavg()</a></li>
|
||
<li><a href="#all_os_totalmem">os.totalmem()</a></li>
|
||
<li><a href="#all_os_freemem">os.freemem()</a></li>
|
||
<li><a href="#all_os_cpus">os.cpus()</a></li>
|
||
<li><a href="#all_os_networkinterfaces">os.networkInterfaces()</a></li>
|
||
<li><a href="#all_os_eol">os.EOL</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_debugger">Debugger</a><ul>
|
||
<li><a href="#all_watchers">Watchers</a></li>
|
||
<li><a href="#all_commands_reference">Commands reference</a><ul>
|
||
<li><a href="#all_stepping">Stepping</a></li>
|
||
<li><a href="#all_breakpoints">Breakpoints</a></li>
|
||
<li><a href="#all_info">Info</a></li>
|
||
<li><a href="#all_execution_control">Execution control</a></li>
|
||
<li><a href="#all_various">Various</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_advanced_usage">Advanced Usage</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#all_cluster">Cluster</a><ul>
|
||
<li><a href="#all_how_it_works">How It Works</a></li>
|
||
<li><a href="#all_cluster_settings">cluster.settings</a></li>
|
||
<li><a href="#all_cluster_ismaster">cluster.isMaster</a></li>
|
||
<li><a href="#all_cluster_isworker">cluster.isWorker</a></li>
|
||
<li><a href="#all_event_fork">Event: 'fork'</a></li>
|
||
<li><a href="#all_event_online">Event: 'online'</a></li>
|
||
<li><a href="#all_event_listening_2">Event: 'listening'</a></li>
|
||
<li><a href="#all_event_disconnect_1">Event: 'disconnect'</a></li>
|
||
<li><a href="#all_event_exit_3">Event: 'exit'</a></li>
|
||
<li><a href="#all_event_setup">Event: 'setup'</a></li>
|
||
<li><a href="#all_cluster_setupmaster_settings">cluster.setupMaster([settings])</a></li>
|
||
<li><a href="#all_cluster_fork_env">cluster.fork([env])</a></li>
|
||
<li><a href="#all_cluster_disconnect_callback">cluster.disconnect([callback])</a></li>
|
||
<li><a href="#all_cluster_worker">cluster.worker</a></li>
|
||
<li><a href="#all_cluster_workers">cluster.workers</a></li>
|
||
<li><a href="#all_class_worker">Class: Worker</a><ul>
|
||
<li><a href="#all_worker_id">worker.id</a></li>
|
||
<li><a href="#all_worker_process">worker.process</a></li>
|
||
<li><a href="#all_worker_suicide">worker.suicide</a></li>
|
||
<li><a href="#all_worker_send_message_sendhandle">worker.send(message, [sendHandle])</a></li>
|
||
<li><a href="#all_worker_destroy">worker.destroy()</a></li>
|
||
<li><a href="#all_worker_disconnect">worker.disconnect()</a></li>
|
||
<li><a href="#all_event_message_2">Event: 'message'</a></li>
|
||
<li><a href="#all_event_online_1">Event: 'online'</a></li>
|
||
<li><a href="#all_event_listening_3">Event: 'listening'</a></li>
|
||
<li><a href="#all_event_disconnect_2">Event: 'disconnect'</a></li>
|
||
<li><a href="#all_event_exit_4">Event: 'exit'</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
|
||
</div>
|
||
|
||
<div id="apicontent">
|
||
<h1>About this Documentation<span><a class="mark" href="#all_about_this_documentation" id="all_about_this_documentation">#</a></span></h1>
|
||
<!-- type=misc -->
|
||
|
||
<p>The goal of this documentation is to comprehensively explain the Node.js
|
||
API, both from a reference as well as a conceptual point of view. Each
|
||
section describes a built-in module or high-level concept.
|
||
|
||
</p>
|
||
<p>Where appropriate, property types, method arguments, and the arguments
|
||
provided to event handlers are detailed in a list underneath the topic
|
||
heading.
|
||
|
||
</p>
|
||
<p>Every <code>.html</code> document has a corresponding <code>.json</code> document presenting
|
||
the same information in a structured manner. This feature is
|
||
experimental, and added for the benefit of IDEs and other utilities that
|
||
wish to do programmatic things with the documentation.
|
||
|
||
</p>
|
||
<p>Every <code>.html</code> and <code>.json</code> file is generated based on the corresponding
|
||
<code>.markdown</code> file in the <code>doc/api/</code> folder in node's source tree. The
|
||
documentation is generated using the <code>tools/doc/generate.js</code> program.
|
||
The HTML template is located at <code>doc/template.html</code>.
|
||
|
||
</p>
|
||
<h2>Stability Index<span><a class="mark" href="#all_stability_index" id="all_stability_index">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>Throughout the documentation, you will see indications of a section's
|
||
stability. The Node.js API is still somewhat changing, and as it
|
||
matures, certain parts are more reliable than others. Some are so
|
||
proven, and so relied upon, that they are unlikely to ever change at
|
||
all. Others are brand new and experimental, or known to be hazardous
|
||
and in the process of being redesigned.
|
||
|
||
</p>
|
||
<p>The notices look like this:
|
||
|
||
</p>
|
||
<pre><code>Stability: 1 Experimental</code></pre>
|
||
<p>The stability indices are as follows:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><strong>0 - Deprecated</strong> This feature is known to be problematic, and changes are
|
||
planned. Do not rely on it. Use of the feature may cause warnings. Backwards
|
||
compatibility should not be expected.</li>
|
||
</ul>
|
||
<ul>
|
||
<li><strong>1 - Experimental</strong> This feature was introduced recently, and may change
|
||
or be removed in future versions. Please try it out and provide feedback.
|
||
If it addresses a use-case that is important to you, tell the node core team.</li>
|
||
</ul>
|
||
<ul>
|
||
<li><strong>2 - Unstable</strong> The API is in the process of settling, but has not yet had
|
||
sufficient real-world testing to be considered stable. Backwards-compatibility
|
||
will be maintained if reasonable.</li>
|
||
</ul>
|
||
<ul>
|
||
<li><strong>3 - Stable</strong> The API has proven satisfactory, but cleanup in the underlying
|
||
code may cause minor changes. Backwards-compatibility is guaranteed.</li>
|
||
</ul>
|
||
<ul>
|
||
<li><strong>4 - API Frozen</strong> This API has been tested extensively in production and is
|
||
unlikely to ever have to change.</li>
|
||
</ul>
|
||
<ul>
|
||
<li><strong>5 - Locked</strong> Unless serious bugs are found, this code will not ever
|
||
change. Please do not suggest changes in this area; they will be refused.</li>
|
||
</ul>
|
||
<h2>JSON Output<span><a class="mark" href="#all_json_output" id="all_json_output">#</a></span></h2>
|
||
<pre><code>Stability: 1 - Experimental</code></pre>
|
||
<p>Every HTML file in the markdown has a corresponding JSON file with the
|
||
same data.
|
||
|
||
</p>
|
||
<p>This feature is new as of node v0.6.12. It is experimental.
|
||
|
||
</p>
|
||
<h1>Synopsis<span><a class="mark" href="#all_synopsis" id="all_synopsis">#</a></span></h1>
|
||
<!--type=misc-->
|
||
|
||
<p>An example of a <a href="http.html">web server</a> written with Node which responds with 'Hello
|
||
World':
|
||
|
||
</p>
|
||
<pre><code>var http = require('http');
|
||
|
||
http.createServer(function (request, response) {
|
||
response.writeHead(200, {'Content-Type': 'text/plain'});
|
||
response.end('Hello World\n');
|
||
}).listen(8124);
|
||
|
||
console.log('Server running at http://127.0.0.1:8124/');</code></pre>
|
||
<p>To run the server, put the code into a file called <code>example.js</code> and execute
|
||
it with the node program
|
||
|
||
</p>
|
||
<pre><code>> node example.js
|
||
Server running at http://127.0.0.1:8124/</code></pre>
|
||
<p>All of the examples in the documentation can be run similarly.
|
||
|
||
</p>
|
||
<h1>Global Objects<span><a class="mark" href="#all_global_objects" id="all_global_objects">#</a></span></h1>
|
||
<!-- type=misc -->
|
||
|
||
<p>These objects are available in all modules. Some of these objects aren't
|
||
actually in the global scope but in the module scope - this will be noted.
|
||
|
||
</p>
|
||
<h2>global<span><a class="mark" href="#all_global" id="all_global">#</a></span></h2>
|
||
<!-- type=global -->
|
||
|
||
<ul>
|
||
<li>{Object} The global namespace object.</li>
|
||
</ul>
|
||
<p>In browsers, the top-level scope is the global scope. That means that in
|
||
browsers if you're in the global scope <code>var something</code> will define a global
|
||
variable. In Node this is different. The top-level scope is not the global
|
||
scope; <code>var something</code> inside a Node module will be local to that module.
|
||
|
||
</p>
|
||
<h2>process<span><a class="mark" href="#all_process" id="all_process">#</a></span></h2>
|
||
<!-- type=global -->
|
||
|
||
<ul>
|
||
<li>{Object}</li>
|
||
</ul>
|
||
<p>The process object. See the <a href="process.html#process_process">process object</a> section.
|
||
|
||
</p>
|
||
<h2>console<span><a class="mark" href="#all_console" id="all_console">#</a></span></h2>
|
||
<!-- type=global -->
|
||
|
||
<ul>
|
||
<li>{Object}</li>
|
||
</ul>
|
||
<p>Used to print to stdout and stderr. See the <a href="stdio.html">stdio</a> section.
|
||
|
||
</p>
|
||
<h2>Class: Buffer<span><a class="mark" href="#all_class_buffer" id="all_class_buffer">#</a></span></h2>
|
||
<!-- type=global -->
|
||
|
||
<ul>
|
||
<li>{Function}</li>
|
||
</ul>
|
||
<p>Used to handle binary data. See the <a href="buffer.html">buffer section</a>
|
||
|
||
</p>
|
||
<h2>require()<span><a class="mark" href="#all_require" id="all_require">#</a></span></h2>
|
||
<!-- type=var -->
|
||
|
||
<ul>
|
||
<li>{Function}</li>
|
||
</ul>
|
||
<p>To require modules. See the <a href="modules.html#modules_modules">Modules</a> section. <code>require</code> isn't actually a
|
||
global but rather local to each module.
|
||
|
||
</p>
|
||
<h3>require.resolve()<span><a class="mark" href="#all_require_resolve" id="all_require_resolve">#</a></span></h3>
|
||
<p>Use the internal <code>require()</code> machinery to look up the location of a module,
|
||
but rather than loading the module, just return the resolved filename.
|
||
|
||
</p>
|
||
<h3>require.cache<span><a class="mark" href="#all_require_cache" id="all_require_cache">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Object</span></li>
|
||
</div></ul>
|
||
<p>Modules are cached in this object when they are required. By deleting a key
|
||
value from this object, the next <code>require</code> will reload the module.
|
||
|
||
</p>
|
||
<h3>require.extensions<span><a class="mark" href="#all_require_extensions" id="all_require_extensions">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Array</span></li>
|
||
</div></ul>
|
||
<p>Instruct <code>require</code> on how to handle certain file extensions.
|
||
|
||
</p>
|
||
<p>Process files with the extension <code>.sjs</code> as <code>.js</code>:
|
||
|
||
</p>
|
||
<pre><code>require.extensions['.sjs'] = require.extensions['.js'];</code></pre>
|
||
<p>Write your own extension handler:
|
||
|
||
</p>
|
||
<pre><code>require.extensions['.sjs'] = function(module, filename) {
|
||
var content = fs.readFileSync(filename, 'utf8');
|
||
// Parse the file content and give to module.exports
|
||
module.exports = content;
|
||
};</code></pre>
|
||
<h2>__filename<span><a class="mark" href="#all_filename" id="all_filename">#</a></span></h2>
|
||
<!-- type=var -->
|
||
|
||
<ul>
|
||
<li>{String}</li>
|
||
</ul>
|
||
<p>The filename of the code being executed. This is the resolved absolute path
|
||
of this code file. For a main program this is not necessarily the same
|
||
filename used in the command line. The value inside a module is the path
|
||
to that module file.
|
||
|
||
</p>
|
||
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code>
|
||
|
||
</p>
|
||
<pre><code>console.log(__filename);
|
||
// /Users/mjr/example.js</code></pre>
|
||
<p><code>__filename</code> isn't actually a global but rather local to each module.
|
||
|
||
</p>
|
||
<h2>__dirname<span><a class="mark" href="#all_dirname" id="all_dirname">#</a></span></h2>
|
||
<!-- type=var -->
|
||
|
||
<ul>
|
||
<li>{String}</li>
|
||
</ul>
|
||
<p>The name of the directory that the currently executing script resides in.
|
||
|
||
</p>
|
||
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code>
|
||
|
||
</p>
|
||
<pre><code>console.log(__dirname);
|
||
// /Users/mjr</code></pre>
|
||
<p><code>__dirname</code> isn't actually a global but rather local to each module.
|
||
|
||
|
||
</p>
|
||
<h2>module<span><a class="mark" href="#all_module" id="all_module">#</a></span></h2>
|
||
<!-- type=var -->
|
||
|
||
<ul>
|
||
<li>{Object}</li>
|
||
</ul>
|
||
<p>A reference to the current module. In particular
|
||
<code>module.exports</code> is the same as the <code>exports</code> object.
|
||
<code>module</code> isn't actually a global but rather local to each module.
|
||
|
||
</p>
|
||
<p>See the <a href="modules.html">module system documentation</a> for more information.
|
||
|
||
</p>
|
||
<h2>exports<span><a class="mark" href="#all_exports" id="all_exports">#</a></span></h2>
|
||
<!-- type=var -->
|
||
|
||
<p>An object which is shared between all instances of the current module and
|
||
made accessible through <code>require()</code>.
|
||
<code>exports</code> is the same as the <code>module.exports</code> object.
|
||
<code>exports</code> isn't actually a global but rather local to each module.
|
||
|
||
</p>
|
||
<p>See the <a href="modules.html">module system documentation</a> for more information.
|
||
|
||
</p>
|
||
<p>See the <a href="modules.html">module section</a> for more information.
|
||
|
||
</p>
|
||
<h2>setTimeout(cb, ms)<span><a class="mark" href="#all_settimeout_cb_ms" id="all_settimeout_cb_ms">#</a></span></h2>
|
||
<p>Run callback <code>cb</code> after <em>at least</em> <code>ms</code> milliseconds. The actual delay depends
|
||
on external factors like OS timer granularity and system load.
|
||
|
||
</p>
|
||
<p>The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is
|
||
outside that range, it's changed to 1 millisecond. Broadly speaking, a timer
|
||
cannot span more than 24.8 days.
|
||
|
||
</p>
|
||
<p>Returns an opaque value that represents the timer.
|
||
|
||
</p>
|
||
<h2>clearTimeout(t)<span><a class="mark" href="#all_cleartimeout_t" id="all_cleartimeout_t">#</a></span></h2>
|
||
<p>Stop a timer that was previously created with <code>setTimeout()</code>. The callback will
|
||
not execute.
|
||
|
||
</p>
|
||
<h2>setInterval(cb, ms)<span><a class="mark" href="#all_setinterval_cb_ms" id="all_setinterval_cb_ms">#</a></span></h2>
|
||
<p>Run callback <code>cb</code> repeatedly every <code>ms</code> milliseconds. Note that the actual
|
||
interval may vary, depending on external factors like OS timer granularity and
|
||
system load. It's never less than <code>ms</code> but it may be longer.
|
||
|
||
</p>
|
||
<p>The interval must be in the range of 1-2,147,483,647 inclusive. If the value is
|
||
outside that range, it's changed to 1 millisecond. Broadly speaking, a timer
|
||
cannot span more than 24.8 days.
|
||
|
||
</p>
|
||
<p>Returns an opaque value that represents the timer.
|
||
|
||
</p>
|
||
<h2>clearInterval(t)<span><a class="mark" href="#all_clearinterval_t" id="all_clearinterval_t">#</a></span></h2>
|
||
<p>Stop a timer that was previously created with <code>setInterval()</code>. The callback
|
||
will not execute.
|
||
|
||
</p>
|
||
<!--type=global-->
|
||
|
||
<p>The timer functions are global variables. See the <a href="timers.html">timers</a> section.
|
||
|
||
</p>
|
||
<h1>console<span><a class="mark" href="#all_console_1" id="all_console_1">#</a></span></h1>
|
||
<pre><code>Stability: 4 - API Frozen</code></pre>
|
||
<ul>
|
||
<li>{Object}</li>
|
||
</ul>
|
||
<!--type=global-->
|
||
|
||
<p>For printing to stdout and stderr. Similar to the console object functions
|
||
provided by most web browsers, here the output is sent to stdout or stderr.
|
||
|
||
</p>
|
||
<h2>console.log([data], [...])<span><a class="mark" href="#all_console_log_data" id="all_console_log_data">#</a></span></h2>
|
||
<p>Prints to stdout with newline. This function can take multiple arguments in a
|
||
<code>printf()</code>-like way. Example:
|
||
|
||
</p>
|
||
<pre><code>console.log('count: %d', count);</code></pre>
|
||
<p>If formatting elements are not found in the first string then <code>util.inspect</code>
|
||
is used on each argument. See <a href="util.html#util_util_format_format">util.format()</a> for more information.
|
||
|
||
</p>
|
||
<h2>console.info([data], [...])<span><a class="mark" href="#all_console_info_data" id="all_console_info_data">#</a></span></h2>
|
||
<p>Same as <code>console.log</code>.
|
||
|
||
</p>
|
||
<h2>console.error([data], [...])<span><a class="mark" href="#all_console_error_data" id="all_console_error_data">#</a></span></h2>
|
||
<p>Same as <code>console.log</code> but prints to stderr.
|
||
|
||
</p>
|
||
<h2>console.warn([data], [...])<span><a class="mark" href="#all_console_warn_data" id="all_console_warn_data">#</a></span></h2>
|
||
<p>Same as <code>console.error</code>.
|
||
|
||
</p>
|
||
<h2>console.dir(obj)<span><a class="mark" href="#all_console_dir_obj" id="all_console_dir_obj">#</a></span></h2>
|
||
<p>Uses <code>util.inspect</code> on <code>obj</code> and prints resulting string to stdout.
|
||
|
||
</p>
|
||
<h2>console.time(label)<span><a class="mark" href="#all_console_time_label" id="all_console_time_label">#</a></span></h2>
|
||
<p>Mark a time.
|
||
|
||
</p>
|
||
<h2>console.timeEnd(label)<span><a class="mark" href="#all_console_timeend_label" id="all_console_timeend_label">#</a></span></h2>
|
||
<p>Finish timer, record output. Example:
|
||
|
||
</p>
|
||
<pre><code>console.time('100-elements');
|
||
for (var i = 0; i < 100; i++) {
|
||
;
|
||
}
|
||
console.timeEnd('100-elements');</code></pre>
|
||
<h2>console.trace(label)<span><a class="mark" href="#all_console_trace_label" id="all_console_trace_label">#</a></span></h2>
|
||
<p>Print a stack trace to stderr of the current position.
|
||
|
||
</p>
|
||
<h2>console.assert(expression, [message])<span><a class="mark" href="#all_console_assert_expression_message" id="all_console_assert_expression_message">#</a></span></h2>
|
||
<p>Same as <a href="assert.html#assert_assert_value_message_assert_ok_value_message">assert.ok()</a> where if the <code>expression</code> evaluates as <code>false</code> throw an
|
||
AssertionError with <code>message</code>.
|
||
|
||
</p>
|
||
<h1>Timers<span><a class="mark" href="#all_timers" id="all_timers">#</a></span></h1>
|
||
<pre><code>Stability: 5 - Locked</code></pre>
|
||
<p>All of the timer functions are globals. You do not need to <code>require()</code>
|
||
this module in order to use them.
|
||
|
||
</p>
|
||
<h2>setTimeout(callback, delay, [arg], [...])<span><a class="mark" href="#all_settimeout_callback_delay_arg" id="all_settimeout_callback_delay_arg">#</a></span></h2>
|
||
<p>To schedule execution of a one-time <code>callback</code> after <code>delay</code> milliseconds. Returns a
|
||
<code>timeoutId</code> for possible use with <code>clearTimeout()</code>. Optionally you can
|
||
also pass arguments to the callback.
|
||
|
||
</p>
|
||
<p>It is important to note that your callback will probably not be called in exactly
|
||
<code>delay</code> milliseconds - Node.js makes no guarantees about the exact timing of when
|
||
the callback will fire, nor of the ordering things will fire in. The callback will
|
||
be called as close as possible to the time specified.
|
||
|
||
</p>
|
||
<h2>clearTimeout(timeoutId)<span><a class="mark" href="#all_cleartimeout_timeoutid" id="all_cleartimeout_timeoutid">#</a></span></h2>
|
||
<p>Prevents a timeout from triggering.
|
||
|
||
</p>
|
||
<h2>setInterval(callback, delay, [arg], [...])<span><a class="mark" href="#all_setinterval_callback_delay_arg" id="all_setinterval_callback_delay_arg">#</a></span></h2>
|
||
<p>To schedule the repeated execution of <code>callback</code> every <code>delay</code> milliseconds.
|
||
Returns a <code>intervalId</code> for possible use with <code>clearInterval()</code>. Optionally
|
||
you can also pass arguments to the callback.
|
||
|
||
</p>
|
||
<h2>clearInterval(intervalId)<span><a class="mark" href="#all_clearinterval_intervalid" id="all_clearinterval_intervalid">#</a></span></h2>
|
||
<p>Stops a interval from triggering.
|
||
|
||
</p>
|
||
<h1>Modules<span><a class="mark" href="#all_modules" id="all_modules">#</a></span></h1>
|
||
<pre><code>Stability: 5 - Locked</code></pre>
|
||
<!--name=module-->
|
||
|
||
<p>Node has a simple module loading system. In Node, files and modules are in
|
||
one-to-one correspondence. As an example, <code>foo.js</code> loads the module
|
||
<code>circle.js</code> in the same directory.
|
||
|
||
</p>
|
||
<p>The contents of <code>foo.js</code>:
|
||
|
||
</p>
|
||
<pre><code>var circle = require('./circle.js');
|
||
console.log( 'The area of a circle of radius 4 is '
|
||
+ circle.area(4));</code></pre>
|
||
<p>The contents of <code>circle.js</code>:
|
||
|
||
</p>
|
||
<pre><code>var PI = Math.PI;
|
||
|
||
exports.area = function (r) {
|
||
return PI * r * r;
|
||
};
|
||
|
||
exports.circumference = function (r) {
|
||
return 2 * PI * r;
|
||
};</code></pre>
|
||
<p>The module <code>circle.js</code> has exported the functions <code>area()</code> and
|
||
<code>circumference()</code>. To export an object, add to the special <code>exports</code>
|
||
object.
|
||
|
||
</p>
|
||
<p>Variables
|
||
local to the module will be private. In this example the variable <code>PI</code> is
|
||
private to <code>circle.js</code>.
|
||
|
||
</p>
|
||
<p>The module system is implemented in the <code>require("module")</code> module.
|
||
|
||
</p>
|
||
<h2>Cycles<span><a class="mark" href="#all_cycles" id="all_cycles">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>When there are circular <code>require()</code> calls, a module might not be
|
||
done being executed when it is returned.
|
||
|
||
</p>
|
||
<p>Consider this situation:
|
||
|
||
</p>
|
||
<p><code>a.js</code>:
|
||
|
||
</p>
|
||
<pre><code>console.log('a starting');
|
||
exports.done = false;
|
||
var b = require('./b.js');
|
||
console.log('in a, b.done = %j', b.done);
|
||
exports.done = true;
|
||
console.log('a done');</code></pre>
|
||
<p><code>b.js</code>:
|
||
|
||
</p>
|
||
<pre><code>console.log('b starting');
|
||
exports.done = false;
|
||
var a = require('./a.js');
|
||
console.log('in b, a.done = %j', a.done);
|
||
exports.done = true;
|
||
console.log('b done');</code></pre>
|
||
<p><code>main.js</code>:
|
||
|
||
</p>
|
||
<pre><code>console.log('main starting');
|
||
var a = require('./a.js');
|
||
var b = require('./b.js');
|
||
console.log('in main, a.done=%j, b.done=%j', a.done, b.done);</code></pre>
|
||
<p>When <code>main.js</code> loads <code>a.js</code>, then <code>a.js</code> in turn loads <code>b.js</code>. At that
|
||
point, <code>b.js</code> tries to load <code>a.js</code>. In order to prevent an infinite
|
||
loop an <strong>unfinished copy</strong> of the <code>a.js</code> exports object is returned to the
|
||
<code>b.js</code> module. <code>b.js</code> then finishes loading, and its exports object is
|
||
provided to the <code>a.js</code> module.
|
||
|
||
</p>
|
||
<p>By the time <code>main.js</code> has loaded both modules, they're both finished.
|
||
The output of this program would thus be:
|
||
|
||
</p>
|
||
<pre><code>$ node main.js
|
||
main starting
|
||
a starting
|
||
b starting
|
||
in b, a.done = false
|
||
b done
|
||
in a, b.done = true
|
||
a done
|
||
in main, a.done=true, b.done=true</code></pre>
|
||
<p>If you have cyclic module dependencies in your program, make sure to
|
||
plan accordingly.
|
||
|
||
</p>
|
||
<h2>Core Modules<span><a class="mark" href="#all_core_modules" id="all_core_modules">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>Node has several modules compiled into the binary. These modules are
|
||
described in greater detail elsewhere in this documentation.
|
||
|
||
</p>
|
||
<p>The core modules are defined in node's source in the <code>lib/</code> folder.
|
||
|
||
</p>
|
||
<p>Core modules are always preferentially loaded if their identifier is
|
||
passed to <code>require()</code>. For instance, <code>require('http')</code> will always
|
||
return the built in HTTP module, even if there is a file by that name.
|
||
|
||
</p>
|
||
<h2>File Modules<span><a class="mark" href="#all_file_modules" id="all_file_modules">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>If the exact filename is not found, then node will attempt to load the
|
||
required filename with the added extension of <code>.js</code>, <code>.json</code>, and then <code>.node</code>.
|
||
|
||
</p>
|
||
<p><code>.js</code> files are interpreted as JavaScript text files, and <code>.json</code> files are
|
||
parsed as JSON text files. <code>.node</code> files are interpreted as compiled addon
|
||
modules loaded with <code>dlopen</code>.
|
||
|
||
</p>
|
||
<p>A module prefixed with <code>'/'</code> is an absolute path to the file. For
|
||
example, <code>require('/home/marco/foo.js')</code> will load the file at
|
||
<code>/home/marco/foo.js</code>.
|
||
|
||
</p>
|
||
<p>A module prefixed with <code>'./'</code> is relative to the file calling <code>require()</code>.
|
||
That is, <code>circle.js</code> must be in the same directory as <code>foo.js</code> for
|
||
<code>require('./circle')</code> to find it.
|
||
|
||
</p>
|
||
<p>Without a leading '/' or './' to indicate a file, the module is either a
|
||
"core module" or is loaded from a <code>node_modules</code> folder.
|
||
|
||
</p>
|
||
<p>If the given path does not exist, <code>require()</code> will throw an Error with its
|
||
<code>code</code> property set to <code>'MODULE_NOT_FOUND'</code>.
|
||
|
||
</p>
|
||
<h2>Loading from <code>node_modules</code> Folders<span><a class="mark" href="#all_loading_from_node_modules_folders" id="all_loading_from_node_modules_folders">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>If the module identifier passed to <code>require()</code> is not a native module,
|
||
and does not begin with <code>'/'</code>, <code>'../'</code>, or <code>'./'</code>, then node starts at the
|
||
parent directory of the current module, and adds <code>/node_modules</code>, and
|
||
attempts to load the module from that location.
|
||
|
||
</p>
|
||
<p>If it is not found there, then it moves to the parent directory, and so
|
||
on, until the root of the tree is reached.
|
||
|
||
</p>
|
||
<p>For example, if the file at <code>'/home/ry/projects/foo.js'</code> called
|
||
<code>require('bar.js')</code>, then node would look in the following locations, in
|
||
this order:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>/home/ry/projects/node_modules/bar.js</code></li>
|
||
<li><code>/home/ry/node_modules/bar.js</code></li>
|
||
<li><code>/home/node_modules/bar.js</code></li>
|
||
<li><code>/node_modules/bar.js</code></li>
|
||
</ul>
|
||
<p>This allows programs to localize their dependencies, so that they do not
|
||
clash.
|
||
|
||
</p>
|
||
<h2>Folders as Modules<span><a class="mark" href="#all_folders_as_modules" id="all_folders_as_modules">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>It is convenient to organize programs and libraries into self-contained
|
||
directories, and then provide a single entry point to that library.
|
||
There are three ways in which a folder may be passed to <code>require()</code> as
|
||
an argument.
|
||
|
||
</p>
|
||
<p>The first is to create a <code>package.json</code> file in the root of the folder,
|
||
which specifies a <code>main</code> module. An example package.json file might
|
||
look like this:
|
||
|
||
</p>
|
||
<pre><code>{ "name" : "some-library",
|
||
"main" : "./lib/some-library.js" }</code></pre>
|
||
<p>If this was in a folder at <code>./some-library</code>, then
|
||
<code>require('./some-library')</code> would attempt to load
|
||
<code>./some-library/lib/some-library.js</code>.
|
||
|
||
</p>
|
||
<p>This is the extent of Node's awareness of package.json files.
|
||
|
||
</p>
|
||
<p>If there is no package.json file present in the directory, then node
|
||
will attempt to load an <code>index.js</code> or <code>index.node</code> file out of that
|
||
directory. For example, if there was no package.json file in the above
|
||
example, then <code>require('./some-library')</code> would attempt to load:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>./some-library/index.js</code></li>
|
||
<li><code>./some-library/index.node</code></li>
|
||
</ul>
|
||
<h2>Caching<span><a class="mark" href="#all_caching" id="all_caching">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>Modules are cached after the first time they are loaded. This means
|
||
(among other things) that every call to <code>require('foo')</code> will get
|
||
exactly the same object returned, if it would resolve to the same file.
|
||
|
||
</p>
|
||
<p>Multiple calls to <code>require('foo')</code> may not cause the module code to be
|
||
executed multiple times. This is an important feature. With it,
|
||
"partially done" objects can be returned, thus allowing transitive
|
||
dependencies to be loaded even when they would cause cycles.
|
||
|
||
</p>
|
||
<p>If you want to have a module execute code multiple times, then export a
|
||
function, and call that function.
|
||
|
||
</p>
|
||
<h3>Module Caching Caveats<span><a class="mark" href="#all_module_caching_caveats" id="all_module_caching_caveats">#</a></span></h3>
|
||
<!--type=misc-->
|
||
|
||
<p>Modules are cached based on their resolved filename. Since modules may
|
||
resolve to a different filename based on the location of the calling
|
||
module (loading from <code>node_modules</code> folders), it is not a <em>guarantee</em>
|
||
that <code>require('foo')</code> will always return the exact same object, if it
|
||
would resolve to different files.
|
||
|
||
</p>
|
||
<h2>The <code>module</code> Object<span><a class="mark" href="#all_the_module_object" id="all_the_module_object">#</a></span></h2>
|
||
<!-- type=var -->
|
||
<!-- name=module -->
|
||
|
||
<ul>
|
||
<li>{Object}</li>
|
||
</ul>
|
||
<p>In each module, the <code>module</code> free variable is a reference to the object
|
||
representing the current module. In particular
|
||
<code>module.exports</code> is the same as the <code>exports</code> object.
|
||
<code>module</code> isn't actually a global but rather local to each module.
|
||
|
||
</p>
|
||
<h3>module.exports<span><a class="mark" href="#all_module_exports" id="all_module_exports">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Object</span></li>
|
||
</div></ul>
|
||
<p>The <code>exports</code> object is created by the Module system. Sometimes this is not
|
||
acceptable, many want their module to be an instance of some class. To do this
|
||
assign the desired export object to <code>module.exports</code>. For example suppose we
|
||
were making a module called <code>a.js</code>
|
||
|
||
</p>
|
||
<pre><code>var EventEmitter = require('events').EventEmitter;
|
||
|
||
module.exports = new EventEmitter();
|
||
|
||
// Do some work, and after some time emit
|
||
// the 'ready' event from the module itself.
|
||
setTimeout(function() {
|
||
module.exports.emit('ready');
|
||
}, 1000);</code></pre>
|
||
<p>Then in another file we could do
|
||
|
||
</p>
|
||
<pre><code>var a = require('./a');
|
||
a.on('ready', function() {
|
||
console.log('module a is ready');
|
||
});</code></pre>
|
||
<p>Note that assignment to <code>module.exports</code> must be done immediately. It cannot be
|
||
done in any callbacks. This does not work:
|
||
|
||
</p>
|
||
<p>x.js:
|
||
|
||
</p>
|
||
<pre><code>setTimeout(function() {
|
||
module.exports = { a: "hello" };
|
||
}, 0);</code></pre>
|
||
<p>y.js:
|
||
|
||
</p>
|
||
<pre><code>var x = require('./x');
|
||
console.log(x.a);</code></pre>
|
||
<h3>module.require(id)<span><a class="mark" href="#all_module_require_id" id="all_module_require_id">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>id</code> <span class="type">String</span></li>
|
||
<li>Return: <span class="type">Object</span> <code>exports</code> from the resolved module</li>
|
||
</div></ul>
|
||
<p>The <code>module.require</code> method provides a way to load a module as if
|
||
<code>require()</code> was called from the original module.
|
||
|
||
</p>
|
||
<p>Note that in order to do this, you must get a reference to the <code>module</code>
|
||
object. Since <code>require()</code> returns the <code>exports</code>, and the <code>module</code> is
|
||
typically <em>only</em> available within a specific module's code, it must be
|
||
explicitly exported in order to be used.
|
||
|
||
|
||
</p>
|
||
<h3>module.id<span><a class="mark" href="#all_module_id" id="all_module_id">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">String</span></li>
|
||
</div></ul>
|
||
<p>The identifier for the module. Typically this is the fully resolved
|
||
filename.
|
||
|
||
|
||
</p>
|
||
<h3>module.filename<span><a class="mark" href="#all_module_filename" id="all_module_filename">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">String</span></li>
|
||
</div></ul>
|
||
<p>The fully resolved filename to the module.
|
||
|
||
|
||
</p>
|
||
<h3>module.loaded<span><a class="mark" href="#all_module_loaded" id="all_module_loaded">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Boolean</span></li>
|
||
</div></ul>
|
||
<p>Whether or not the module is done loading, or is in the process of
|
||
loading.
|
||
|
||
|
||
</p>
|
||
<h3>module.parent<span><a class="mark" href="#all_module_parent" id="all_module_parent">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Module Object</span></li>
|
||
</div></ul>
|
||
<p>The module that required this one.
|
||
|
||
|
||
</p>
|
||
<h3>module.children<span><a class="mark" href="#all_module_children" id="all_module_children">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Array</span></li>
|
||
</div></ul>
|
||
<p>The module objects required by this one.
|
||
|
||
|
||
|
||
</p>
|
||
<h2>All Together...<span><a class="mark" href="#all_all_together" id="all_all_together">#</a></span></h2>
|
||
<!-- type=misc -->
|
||
|
||
<p>To get the exact filename that will be loaded when <code>require()</code> is called, use
|
||
the <code>require.resolve()</code> function.
|
||
|
||
</p>
|
||
<p>Putting together all of the above, here is the high-level algorithm
|
||
in pseudocode of what require.resolve does:
|
||
|
||
</p>
|
||
<pre><code>require(X) from module at path Y
|
||
1. If X is a core module,
|
||
a. return the core module
|
||
b. STOP
|
||
2. If X begins with './' or '/' or '../'
|
||
a. LOAD_AS_FILE(Y + X)
|
||
b. LOAD_AS_DIRECTORY(Y + X)
|
||
3. LOAD_NODE_MODULES(X, dirname(Y))
|
||
4. THROW "not found"
|
||
|
||
LOAD_AS_FILE(X)
|
||
1. If X is a file, load X as JavaScript text. STOP
|
||
2. If X.js is a file, load X.js as JavaScript text. STOP
|
||
3. If X.node is a file, load X.node as binary addon. STOP
|
||
|
||
LOAD_AS_DIRECTORY(X)
|
||
1. If X/package.json is a file,
|
||
a. Parse X/package.json, and look for "main" field.
|
||
b. let M = X + (json main field)
|
||
c. LOAD_AS_FILE(M)
|
||
2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
|
||
3. If X/index.node is a file, load X/index.node as binary addon. STOP
|
||
|
||
LOAD_NODE_MODULES(X, START)
|
||
1. let DIRS=NODE_MODULES_PATHS(START)
|
||
2. for each DIR in DIRS:
|
||
a. LOAD_AS_FILE(DIR/X)
|
||
b. LOAD_AS_DIRECTORY(DIR/X)
|
||
|
||
NODE_MODULES_PATHS(START)
|
||
1. let PARTS = path split(START)
|
||
2. let ROOT = index of first instance of "node_modules" in PARTS, or 0
|
||
3. let I = count of PARTS - 1
|
||
4. let DIRS = []
|
||
5. while I > ROOT,
|
||
a. if PARTS[I] = "node_modules" CONTINUE
|
||
c. DIR = path join(PARTS[0 .. I] + "node_modules")
|
||
b. DIRS = DIRS + DIR
|
||
c. let I = I - 1
|
||
6. return DIRS</code></pre>
|
||
<h2>Loading from the global folders<span><a class="mark" href="#all_loading_from_the_global_folders" id="all_loading_from_the_global_folders">#</a></span></h2>
|
||
<!-- type=misc -->
|
||
|
||
<p>If the <code>NODE_PATH</code> environment variable is set to a colon-delimited list
|
||
of absolute paths, then node will search those paths for modules if they
|
||
are not found elsewhere. (Note: On Windows, <code>NODE_PATH</code> is delimited by
|
||
semicolons instead of colons.)
|
||
|
||
</p>
|
||
<p>Additionally, node will search in the following locations:
|
||
|
||
</p>
|
||
<ul>
|
||
<li>1: <code>$HOME/.node_modules</code></li>
|
||
<li>2: <code>$HOME/.node_libraries</code></li>
|
||
<li>3: <code>$PREFIX/lib/node</code></li>
|
||
</ul>
|
||
<p>Where <code>$HOME</code> is the user's home directory, and <code>$PREFIX</code> is node's
|
||
configured <code>node_prefix</code>.
|
||
|
||
</p>
|
||
<p>These are mostly for historic reasons. You are highly encouraged to
|
||
place your dependencies locally in <code>node_modules</code> folders. They will be
|
||
loaded faster, and more reliably.
|
||
|
||
</p>
|
||
<h2>Accessing the main module<span><a class="mark" href="#all_accessing_the_main_module" id="all_accessing_the_main_module">#</a></span></h2>
|
||
<!-- type=misc -->
|
||
|
||
<p>When a file is run directly from Node, <code>require.main</code> is set to its
|
||
<code>module</code>. That means that you can determine whether a file has been run
|
||
directly by testing
|
||
|
||
</p>
|
||
<pre><code>require.main === module</code></pre>
|
||
<p>For a file <code>foo.js</code>, this will be <code>true</code> if run via <code>node foo.js</code>, but
|
||
<code>false</code> if run by <code>require('./foo')</code>.
|
||
|
||
</p>
|
||
<p>Because <code>module</code> provides a <code>filename</code> property (normally equivalent to
|
||
<code>__filename</code>), the entry point of the current application can be obtained
|
||
by checking <code>require.main.filename</code>.
|
||
|
||
</p>
|
||
<h2>Addenda: Package Manager Tips<span><a class="mark" href="#all_addenda_package_manager_tips" id="all_addenda_package_manager_tips">#</a></span></h2>
|
||
<!-- type=misc -->
|
||
|
||
<p>The semantics of Node's <code>require()</code> function were designed to be general
|
||
enough to support a number of sane directory structures. Package manager
|
||
programs such as <code>dpkg</code>, <code>rpm</code>, and <code>npm</code> will hopefully find it possible to
|
||
build native packages from Node modules without modification.
|
||
|
||
</p>
|
||
<p>Below we give a suggested directory structure that could work:
|
||
|
||
</p>
|
||
<p>Let's say that we wanted to have the folder at
|
||
<code>/usr/lib/node/<some-package>/<some-version></code> hold the contents of a
|
||
specific version of a package.
|
||
|
||
</p>
|
||
<p>Packages can depend on one another. In order to install package <code>foo</code>, you
|
||
may have to install a specific version of package <code>bar</code>. The <code>bar</code> package
|
||
may itself have dependencies, and in some cases, these dependencies may even
|
||
collide or form cycles.
|
||
|
||
</p>
|
||
<p>Since Node looks up the <code>realpath</code> of any modules it loads (that is,
|
||
resolves symlinks), and then looks for their dependencies in the
|
||
<code>node_modules</code> folders as described above, this situation is very simple to
|
||
resolve with the following architecture:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>/usr/lib/node/foo/1.2.3/</code> - Contents of the <code>foo</code> package, version 1.2.3.</li>
|
||
<li><code>/usr/lib/node/bar/4.3.2/</code> - Contents of the <code>bar</code> package that <code>foo</code>
|
||
depends on.</li>
|
||
<li><code>/usr/lib/node/foo/1.2.3/node_modules/bar</code> - Symbolic link to
|
||
<code>/usr/lib/node/bar/4.3.2/</code>.</li>
|
||
<li><code>/usr/lib/node/bar/4.3.2/node_modules/*</code> - Symbolic links to the packages
|
||
that <code>bar</code> depends on.</li>
|
||
</ul>
|
||
<p>Thus, even if a cycle is encountered, or if there are dependency
|
||
conflicts, every module will be able to get a version of its dependency
|
||
that it can use.
|
||
|
||
</p>
|
||
<p>When the code in the <code>foo</code> package does <code>require('bar')</code>, it will get the
|
||
version that is symlinked into <code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>.
|
||
Then, when the code in the <code>bar</code> package calls <code>require('quux')</code>, it'll get
|
||
the version that is symlinked into
|
||
<code>/usr/lib/node/bar/4.3.2/node_modules/quux</code>.
|
||
|
||
</p>
|
||
<p>Furthermore, to make the module lookup process even more optimal, rather
|
||
than putting packages directly in <code>/usr/lib/node</code>, we could put them in
|
||
<code>/usr/lib/node_modules/<name>/<version></code>. Then node will not bother
|
||
looking for missing dependencies in <code>/usr/node_modules</code> or <code>/node_modules</code>.
|
||
|
||
</p>
|
||
<p>In order to make modules available to the node REPL, it might be useful to
|
||
also add the <code>/usr/lib/node_modules</code> folder to the <code>$NODE_PATH</code> environment
|
||
variable. Since the module lookups using <code>node_modules</code> folders are all
|
||
relative, and based on the real path of the files making the calls to
|
||
<code>require()</code>, the packages themselves can be anywhere.
|
||
|
||
</p>
|
||
<h1>Addons<span><a class="mark" href="#all_addons" id="all_addons">#</a></span></h1>
|
||
<p>Addons are dynamically linked shared objects. They can provide glue to C and
|
||
C++ libraries. The API (at the moment) is rather complex, involving
|
||
knowledge of several libraries:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p>V8 JavaScript, a C++ library. Used for interfacing with JavaScript:
|
||
creating objects, calling functions, etc. Documented mostly in the
|
||
<code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node source tree),
|
||
which is also available <a href="http://izs.me/v8-docs/main.html">online</a>.</p>
|
||
</li>
|
||
<li><p><a href="https://github.com/joyent/libuv">libuv</a>, C event loop library. Anytime one
|
||
needs to wait for a file descriptor to become readable, wait for a timer, or
|
||
wait for a signal to received one will need to interface with libuv. That is,
|
||
if you perform any I/O, libuv will need to be used.</p>
|
||
</li>
|
||
<li><p>Internal Node libraries. Most importantly is the <code>node::ObjectWrap</code>
|
||
class which you will likely want to derive from.</p>
|
||
</li>
|
||
<li><p>Others. Look in <code>deps/</code> for what else is available.</p>
|
||
</li>
|
||
</ul>
|
||
<p>Node statically compiles all its dependencies into the executable. When
|
||
compiling your module, you don't need to worry about linking to any of these
|
||
libraries.
|
||
|
||
|
||
</p>
|
||
<h2>Hello world<span><a class="mark" href="#all_hello_world" id="all_hello_world">#</a></span></h2>
|
||
<p>To get started let's make a small Addon which is the C++ equivalent of
|
||
the following JavaScript code:
|
||
|
||
</p>
|
||
<pre><code>exports.hello = function() { return 'world'; };</code></pre>
|
||
<p>First we create a file <code>hello.cc</code>:
|
||
|
||
</p>
|
||
<pre><code>#include <node.h>
|
||
#include <v8.h>
|
||
|
||
using namespace v8;
|
||
|
||
Handle<Value> Method(const Arguments& args) {
|
||
HandleScope scope;
|
||
return scope.Close(String::New("world"));
|
||
}
|
||
|
||
void init(Handle<Object> target) {
|
||
target->Set(String::NewSymbol("hello"),
|
||
FunctionTemplate::New(Method)->GetFunction());
|
||
}
|
||
NODE_MODULE(hello, init)</code></pre>
|
||
<p>Note that all Node addons must export an initialization function:
|
||
|
||
</p>
|
||
<pre><code>void Initialize (Handle<Object> target);
|
||
NODE_MODULE(module_name, Initialize)</code></pre>
|
||
<p>There is no semi-colon after <code>NODE_MODULE</code> as it's not a function (see <code>node.h</code>).
|
||
|
||
</p>
|
||
<p>The <code>module_name</code> needs to match the filename of the final binary (minus the
|
||
.node suffix).
|
||
|
||
</p>
|
||
<p>The source code needs to be built into <code>hello.node</code>, the binary Addon. To
|
||
do this we create a file called <code>binding.gyp</code> which describes the configuration
|
||
to build your module in a JSON-like format. This file gets compiled by
|
||
<a href="https://github.com/TooTallNate/node-gyp">node-gyp</a>.
|
||
|
||
</p>
|
||
<pre><code>{
|
||
"targets": [
|
||
{
|
||
"target_name": "hello",
|
||
"sources": [ "hello.cc" ]
|
||
}
|
||
]
|
||
}</code></pre>
|
||
<p>The next step is to generate the appropriate project build files for the
|
||
current platform. Use <code>node-gyp configure</code> for that.
|
||
|
||
</p>
|
||
<p>Now you will have either a <code>Makefile</code> (on Unix platforms) or a <code>vcxproj</code> file
|
||
(on Windows) in the <code>build/</code> directory. Next invoke the <code>node-gyp build</code>
|
||
command.
|
||
|
||
</p>
|
||
<p>Now you have your compiled <code>.node</code> bindings file! The compiled bindings end up
|
||
in <code>build/Release/</code>.
|
||
|
||
</p>
|
||
<p>You can now use the binary addon in a Node project <code>hello.js</code> by pointing <code>require</code> to
|
||
the recently built <code>hello.node</code> module:
|
||
|
||
</p>
|
||
<pre><code>var addon = require('./build/Release/hello');
|
||
|
||
console.log(addon.hello()); // 'world'</code></pre>
|
||
<p>Please see patterns below for further information or
|
||
</p>
|
||
<p><a href="https://github.com/arturadib/node-qt">https://github.com/arturadib/node-qt</a> for an example in production.
|
||
|
||
|
||
</p>
|
||
<h2>Addon patterns<span><a class="mark" href="#all_addon_patterns" id="all_addon_patterns">#</a></span></h2>
|
||
<p>Below are some addon patterns to help you get started. Consult the online
|
||
<a href="http://izs.me/v8-docs/main.html">v8 reference</a> for help with the various v8
|
||
calls, and v8's <a href="http://code.google.com/apis/v8/embed.html">Embedder's Guide</a>
|
||
for an explanation of several concepts used such as handles, scopes,
|
||
function templates, etc.
|
||
|
||
</p>
|
||
<p>In order to use these examples you need to compile them using <code>node-gyp</code>.
|
||
Create the following <code>binding.gyp</code> file:
|
||
|
||
</p>
|
||
<pre><code>{
|
||
"targets": [
|
||
{
|
||
"target_name": "addon",
|
||
"sources": [ "addon.cc" ]
|
||
}
|
||
]
|
||
}</code></pre>
|
||
<p>In cases where there is more than one <code>.cc</code> file, simply add the file name to the
|
||
<code>sources</code> array, e.g.:
|
||
|
||
</p>
|
||
<pre><code>"sources": ["addon.cc", "myexample.cc"]</code></pre>
|
||
<p>Now that you have your <code>binding.gyp</code> ready, you can configure and build the
|
||
addon:
|
||
|
||
</p>
|
||
<pre><code>$ node-gyp configure build</code></pre>
|
||
<h3>Function arguments<span><a class="mark" href="#all_function_arguments" id="all_function_arguments">#</a></span></h3>
|
||
<p>The following pattern illustrates how to read arguments from JavaScript
|
||
function calls and return a result. This is the main and only needed source
|
||
<code>addon.cc</code>:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
|
||
using namespace v8;
|
||
|
||
Handle<Value> Add(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
if (args.Length() < 2) {
|
||
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
|
||
return scope.Close(Undefined());
|
||
}
|
||
|
||
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
|
||
ThrowException(Exception::TypeError(String::New("Wrong arguments")));
|
||
return scope.Close(Undefined());
|
||
}
|
||
|
||
Local<Number> num = Number::New(args[0]->NumberValue() +
|
||
args[1]->NumberValue());
|
||
return scope.Close(num);
|
||
}
|
||
|
||
void Init(Handle<Object> target) {
|
||
target->Set(String::NewSymbol("add"),
|
||
FunctionTemplate::New(Add)->GetFunction());
|
||
}
|
||
|
||
NODE_MODULE(addon, Init)</code></pre>
|
||
<p>You can test it with the following JavaScript snippet:
|
||
|
||
</p>
|
||
<pre><code>var addon = require('./build/Release/addon');
|
||
|
||
console.log( 'This should be eight:', addon.add(3,5) );</code></pre>
|
||
<h3>Callbacks<span><a class="mark" href="#all_callbacks" id="all_callbacks">#</a></span></h3>
|
||
<p>You can pass JavaScript functions to a C++ function and execute them from
|
||
there. Here's <code>addon.cc</code>:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
|
||
using namespace v8;
|
||
|
||
Handle<Value> RunCallback(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
Local<Function> cb = Local<Function>::Cast(args[0]);
|
||
const unsigned argc = 1;
|
||
Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };
|
||
cb->Call(Context::GetCurrent()->Global(), argc, argv);
|
||
|
||
return scope.Close(Undefined());
|
||
}
|
||
|
||
void Init(Handle<Object> target) {
|
||
target->Set(String::NewSymbol("runCallback"),
|
||
FunctionTemplate::New(RunCallback)->GetFunction());
|
||
}
|
||
|
||
NODE_MODULE(addon, Init)</code></pre>
|
||
<p>To test it run the following JavaScript snippet:
|
||
|
||
</p>
|
||
<pre><code>var addon = require('./build/Release/addon');
|
||
|
||
addon.runCallback(function(msg){
|
||
console.log(msg); // 'hello world'
|
||
});</code></pre>
|
||
<h3>Object factory<span><a class="mark" href="#all_object_factory" id="all_object_factory">#</a></span></h3>
|
||
<p>You can create and return new objects from within a C++ function with this
|
||
<code>addon.cc</code> pattern, which returns an object with property <code>msg</code> that echoes
|
||
the string passed to <code>createObject()</code>:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
|
||
using namespace v8;
|
||
|
||
Handle<Value> CreateObject(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
Local<Object> obj = Object::New();
|
||
obj->Set(String::NewSymbol("msg"), args[0]->ToString());
|
||
|
||
return scope.Close(obj);
|
||
}
|
||
|
||
void Init(Handle<Object> target) {
|
||
target->Set(String::NewSymbol("createObject"),
|
||
FunctionTemplate::New(CreateObject)->GetFunction());
|
||
}
|
||
|
||
NODE_MODULE(addon, Init)</code></pre>
|
||
<p>To test it in JavaScript:
|
||
|
||
</p>
|
||
<pre><code>var addon = require('./build/Release/addon');
|
||
|
||
var obj1 = addon.createObject('hello');
|
||
var obj2 = addon.createObject('world');
|
||
console.log(obj1.msg+' '+obj2.msg); // 'hello world'</code></pre>
|
||
<h3>Function factory<span><a class="mark" href="#all_function_factory" id="all_function_factory">#</a></span></h3>
|
||
<p>This pattern illustrates how to create and return a JavaScript function that
|
||
wraps a C++ function:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
|
||
using namespace v8;
|
||
|
||
Handle<Value> MyFunction(const Arguments& args) {
|
||
HandleScope scope;
|
||
return scope.Close(String::New("hello world"));
|
||
}
|
||
|
||
Handle<Value> CreateFunction(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);
|
||
Local<Function> fn = tpl->GetFunction();
|
||
fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous
|
||
|
||
return scope.Close(fn);
|
||
}
|
||
|
||
void Init(Handle<Object> target) {
|
||
target->Set(String::NewSymbol("createFunction"),
|
||
FunctionTemplate::New(CreateFunction)->GetFunction());
|
||
}
|
||
|
||
NODE_MODULE(addon, Init)</code></pre>
|
||
<p>To test:
|
||
|
||
</p>
|
||
<pre><code>var addon = require('./build/Release/addon');
|
||
|
||
var fn = addon.createFunction();
|
||
console.log(fn()); // 'hello world'</code></pre>
|
||
<h3>Wrapping C++ objects<span><a class="mark" href="#all_wrapping_c_objects" id="all_wrapping_c_objects">#</a></span></h3>
|
||
<p>Here we will create a wrapper for a C++ object/class <code>MyObject</code> that can be
|
||
instantiated in JavaScript through the <code>new</code> operator. First prepare the main
|
||
module <code>addon.cc</code>:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
#include "myobject.h"
|
||
|
||
using namespace v8;
|
||
|
||
void InitAll(Handle<Object> target) {
|
||
MyObject::Init(target);
|
||
}
|
||
|
||
NODE_MODULE(addon, InitAll)</code></pre>
|
||
<p>Then in <code>myobject.h</code> make your wrapper inherit from <code>node::ObjectWrap</code>:
|
||
|
||
</p>
|
||
<pre><code>#ifndef MYOBJECT_H
|
||
#define MYOBJECT_H
|
||
|
||
#include <node.h>
|
||
|
||
class MyObject : public node::ObjectWrap {
|
||
public:
|
||
static void Init(v8::Handle<v8::Object> target);
|
||
|
||
private:
|
||
MyObject();
|
||
~MyObject();
|
||
|
||
static v8::Handle<v8::Value> New(const v8::Arguments& args);
|
||
static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
|
||
double counter_;
|
||
};
|
||
|
||
#endif</code></pre>
|
||
<p>And in <code>myobject.cc</code> implement the various methods that you want to expose.
|
||
Here we expose the method <code>plusOne</code> by adding it to the constructor's
|
||
prototype:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
#include "myobject.h"
|
||
|
||
using namespace v8;
|
||
|
||
MyObject::MyObject() {};
|
||
MyObject::~MyObject() {};
|
||
|
||
void MyObject::Init(Handle<Object> target) {
|
||
// Prepare constructor template
|
||
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
|
||
tpl->SetClassName(String::NewSymbol("MyObject"));
|
||
tpl->InstanceTemplate()->SetInternalFieldCount(1);
|
||
// Prototype
|
||
tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
|
||
FunctionTemplate::New(PlusOne)->GetFunction());
|
||
|
||
Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
|
||
target->Set(String::NewSymbol("MyObject"), constructor);
|
||
}
|
||
|
||
Handle<Value> MyObject::New(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
MyObject* obj = new MyObject();
|
||
obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
|
||
obj->Wrap(args.This());
|
||
|
||
return args.This();
|
||
}
|
||
|
||
Handle<Value> MyObject::PlusOne(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
|
||
obj->counter_ += 1;
|
||
|
||
return scope.Close(Number::New(obj->counter_));
|
||
}</code></pre>
|
||
<p>Test it with:
|
||
|
||
</p>
|
||
<pre><code>var addon = require('./build/Release/addon');
|
||
|
||
var obj = new addon.MyObject(10);
|
||
console.log( obj.plusOne() ); // 11
|
||
console.log( obj.plusOne() ); // 12
|
||
console.log( obj.plusOne() ); // 13</code></pre>
|
||
<h3>Factory of wrapped objects<span><a class="mark" href="#all_factory_of_wrapped_objects" id="all_factory_of_wrapped_objects">#</a></span></h3>
|
||
<p>This is useful when you want to be able to create native objects without
|
||
explicitly instantiating them with the <code>new</code> operator in JavaScript, e.g.
|
||
|
||
</p>
|
||
<pre><code>var obj = addon.createObject();
|
||
// instead of:
|
||
// var obj = new addon.Object();</code></pre>
|
||
<p>Let's register our <code>createObject</code> method in <code>addon.cc</code>:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
#include "myobject.h"
|
||
|
||
using namespace v8;
|
||
|
||
Handle<Value> CreateObject(const Arguments& args) {
|
||
HandleScope scope;
|
||
return scope.Close(MyObject::NewInstance(args));
|
||
}
|
||
|
||
void InitAll(Handle<Object> target) {
|
||
MyObject::Init();
|
||
|
||
target->Set(String::NewSymbol("createObject"),
|
||
FunctionTemplate::New(CreateObject)->GetFunction());
|
||
}
|
||
|
||
NODE_MODULE(addon, InitAll)</code></pre>
|
||
<p>In <code>myobject.h</code> we now introduce the static method <code>NewInstance</code> that takes
|
||
care of instantiating the object (i.e. it does the job of <code>new</code> in JavaScript):
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#ifndef MYOBJECT_H
|
||
#define MYOBJECT_H
|
||
|
||
#include <node.h>
|
||
|
||
class MyObject : public node::ObjectWrap {
|
||
public:
|
||
static void Init();
|
||
static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
|
||
|
||
private:
|
||
MyObject();
|
||
~MyObject();
|
||
|
||
static v8::Persistent<v8::Function> constructor;
|
||
static v8::Handle<v8::Value> New(const v8::Arguments& args);
|
||
static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
|
||
double counter_;
|
||
};
|
||
|
||
#endif</code></pre>
|
||
<p>The implementation is similar to the above in <code>myobject.cc</code>:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
#include "myobject.h"
|
||
|
||
using namespace v8;
|
||
|
||
MyObject::MyObject() {};
|
||
MyObject::~MyObject() {};
|
||
|
||
Persistent<Function> MyObject::constructor;
|
||
|
||
void MyObject::Init() {
|
||
// Prepare constructor template
|
||
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
|
||
tpl->SetClassName(String::NewSymbol("MyObject"));
|
||
tpl->InstanceTemplate()->SetInternalFieldCount(1);
|
||
// Prototype
|
||
tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
|
||
FunctionTemplate::New(PlusOne)->GetFunction());
|
||
|
||
constructor = Persistent<Function>::New(tpl->GetFunction());
|
||
}
|
||
|
||
Handle<Value> MyObject::New(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
MyObject* obj = new MyObject();
|
||
obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
|
||
obj->Wrap(args.This());
|
||
|
||
return args.This();
|
||
}
|
||
|
||
Handle<Value> MyObject::NewInstance(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
const unsigned argc = 1;
|
||
Handle<Value> argv[argc] = { args[0] };
|
||
Local<Object> instance = constructor->NewInstance(argc, argv);
|
||
|
||
return scope.Close(instance);
|
||
}
|
||
|
||
Handle<Value> MyObject::PlusOne(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
|
||
obj->counter_ += 1;
|
||
|
||
return scope.Close(Number::New(obj->counter_));
|
||
}</code></pre>
|
||
<p>Test it with:
|
||
|
||
</p>
|
||
<pre><code>var addon = require('./build/Release/addon');
|
||
|
||
var obj = addon.createObject(10);
|
||
console.log( obj.plusOne() ); // 11
|
||
console.log( obj.plusOne() ); // 12
|
||
console.log( obj.plusOne() ); // 13
|
||
|
||
var obj2 = addon.createObject(20);
|
||
console.log( obj2.plusOne() ); // 21
|
||
console.log( obj2.plusOne() ); // 22
|
||
console.log( obj2.plusOne() ); // 23</code></pre>
|
||
<h3>Passing wrapped objects around<span><a class="mark" href="#all_passing_wrapped_objects_around" id="all_passing_wrapped_objects_around">#</a></span></h3>
|
||
<p>In addition to wrapping and returning C++ objects, you can pass them around
|
||
by unwrapping them with Node's <code>node::ObjectWrap::Unwrap</code> helper function.
|
||
In the following <code>addon.cc</code> we introduce a function <code>add()</code> that can take on two
|
||
<code>MyObject</code> objects:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
#include "myobject.h"
|
||
|
||
using namespace v8;
|
||
|
||
Handle<Value> CreateObject(const Arguments& args) {
|
||
HandleScope scope;
|
||
return scope.Close(MyObject::NewInstance(args));
|
||
}
|
||
|
||
Handle<Value> Add(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
|
||
args[0]->ToObject());
|
||
MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
|
||
args[1]->ToObject());
|
||
|
||
double sum = obj1->Val() + obj2->Val();
|
||
return scope.Close(Number::New(sum));
|
||
}
|
||
|
||
void InitAll(Handle<Object> target) {
|
||
MyObject::Init();
|
||
|
||
target->Set(String::NewSymbol("createObject"),
|
||
FunctionTemplate::New(CreateObject)->GetFunction());
|
||
|
||
target->Set(String::NewSymbol("add"),
|
||
FunctionTemplate::New(Add)->GetFunction());
|
||
}
|
||
|
||
NODE_MODULE(addon, InitAll)</code></pre>
|
||
<p>To make things interesting we introduce a public method in <code>myobject.h</code> so we
|
||
can probe private values after unwrapping the object:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#ifndef MYOBJECT_H
|
||
#define MYOBJECT_H
|
||
|
||
#include <node.h>
|
||
|
||
class MyObject : public node::ObjectWrap {
|
||
public:
|
||
static void Init();
|
||
static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
|
||
double Val() const { return val_; }
|
||
|
||
private:
|
||
MyObject();
|
||
~MyObject();
|
||
|
||
static v8::Persistent<v8::Function> constructor;
|
||
static v8::Handle<v8::Value> New(const v8::Arguments& args);
|
||
double val_;
|
||
};
|
||
|
||
#endif</code></pre>
|
||
<p>The implementation of <code>myobject.cc</code> is similar as before:
|
||
|
||
</p>
|
||
<pre><code>#define BUILDING_NODE_EXTENSION
|
||
#include <node.h>
|
||
#include "myobject.h"
|
||
|
||
using namespace v8;
|
||
|
||
MyObject::MyObject() {};
|
||
MyObject::~MyObject() {};
|
||
|
||
Persistent<Function> MyObject::constructor;
|
||
|
||
void MyObject::Init() {
|
||
// Prepare constructor template
|
||
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
|
||
tpl->SetClassName(String::NewSymbol("MyObject"));
|
||
tpl->InstanceTemplate()->SetInternalFieldCount(1);
|
||
|
||
constructor = Persistent<Function>::New(tpl->GetFunction());
|
||
}
|
||
|
||
Handle<Value> MyObject::New(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
MyObject* obj = new MyObject();
|
||
obj->val_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
|
||
obj->Wrap(args.This());
|
||
|
||
return args.This();
|
||
}
|
||
|
||
Handle<Value> MyObject::NewInstance(const Arguments& args) {
|
||
HandleScope scope;
|
||
|
||
const unsigned argc = 1;
|
||
Handle<Value> argv[argc] = { args[0] };
|
||
Local<Object> instance = constructor->NewInstance(argc, argv);
|
||
|
||
return scope.Close(instance);
|
||
}</code></pre>
|
||
<p>Test it with:
|
||
|
||
</p>
|
||
<pre><code>var addon = require('./build/Release/addon');
|
||
|
||
var obj1 = addon.createObject(10);
|
||
var obj2 = addon.createObject(20);
|
||
var result = addon.add(obj1, obj2);
|
||
|
||
console.log(result); // 30</code></pre>
|
||
<h1>process<span><a class="mark" href="#all_process_1" id="all_process_1">#</a></span></h1>
|
||
<!-- type=global -->
|
||
|
||
<p>The <code>process</code> object is a global object and can be accessed from anywhere.
|
||
It is an instance of <a href="events.html#events_class_events_eventemitter">EventEmitter</a>.
|
||
|
||
|
||
</p>
|
||
<h2>Event: 'exit'<span><a class="mark" href="#all_event_exit" id="all_event_exit">#</a></span></h2>
|
||
<p>Emitted when the process is about to exit. This is a good hook to perform
|
||
constant time checks of the module's state (like for unit tests). The main
|
||
event loop will no longer be run after the 'exit' callback finishes, so
|
||
timers may not be scheduled.
|
||
|
||
</p>
|
||
<p>Example of listening for <code>exit</code>:
|
||
|
||
</p>
|
||
<pre><code>process.on('exit', function () {
|
||
process.nextTick(function () {
|
||
console.log('This will not run');
|
||
});
|
||
console.log('About to exit.');
|
||
});</code></pre>
|
||
<h2>Event: 'uncaughtException'<span><a class="mark" href="#all_event_uncaughtexception" id="all_event_uncaughtexception">#</a></span></h2>
|
||
<p>Emitted when an exception bubbles all the way back to the event loop. If a
|
||
listener is added for this exception, the default action (which is to print
|
||
a stack trace and exit) will not occur.
|
||
|
||
</p>
|
||
<p>Example of listening for <code>uncaughtException</code>:
|
||
|
||
</p>
|
||
<pre><code>process.on('uncaughtException', function (err) {
|
||
console.log('Caught exception: ' + err);
|
||
});
|
||
|
||
setTimeout(function () {
|
||
console.log('This will still run.');
|
||
}, 500);
|
||
|
||
// Intentionally cause an exception, but don't catch it.
|
||
nonexistentFunc();
|
||
console.log('This will not run.');</code></pre>
|
||
<p>Note that <code>uncaughtException</code> is a very crude mechanism for exception
|
||
handling and may be removed in the future.
|
||
|
||
</p>
|
||
<p>Don't use it, use <a href="domain.html">domains</a> instead. If you do use it, restart
|
||
your application after every unhandled exception!
|
||
|
||
</p>
|
||
<p>Do <em>not</em> use it as the node.js equivalent of <code>On Error Resume Next</code>. An
|
||
unhandled exception means your application - and by extension node.js itself -
|
||
is in an undefined state. Blindly resuming means <em>anything</em> could happen.
|
||
|
||
</p>
|
||
<p>Think of resuming as pulling the power cord when you are upgrading your system.
|
||
Nine out of ten times nothing happens - but the 10th time, your system is bust.
|
||
|
||
</p>
|
||
<p>You have been warned.
|
||
|
||
</p>
|
||
<h2>Signal Events<span><a class="mark" href="#all_signal_events" id="all_signal_events">#</a></span></h2>
|
||
<!--type=event-->
|
||
<!--name=SIGINT, SIGUSR1, etc.-->
|
||
|
||
<p>Emitted when the processes receives a signal. See sigaction(2) for a list of
|
||
standard POSIX signal names such as SIGINT, SIGUSR1, etc.
|
||
|
||
</p>
|
||
<p>Example of listening for <code>SIGINT</code>:
|
||
|
||
</p>
|
||
<pre><code>// Start reading from stdin so we don't exit.
|
||
process.stdin.resume();
|
||
|
||
process.on('SIGINT', function () {
|
||
console.log('Got SIGINT. Press Control-D to exit.');
|
||
});</code></pre>
|
||
<p>An easy way to send the <code>SIGINT</code> signal is with <code>Control-C</code> in most terminal
|
||
programs.
|
||
|
||
|
||
</p>
|
||
<h2>process.stdout<span><a class="mark" href="#all_process_stdout" id="all_process_stdout">#</a></span></h2>
|
||
<p>A <code>Writable Stream</code> to <code>stdout</code>.
|
||
|
||
</p>
|
||
<p>Example: the definition of <code>console.log</code>
|
||
|
||
</p>
|
||
<pre><code>console.log = function (d) {
|
||
process.stdout.write(d + '\n');
|
||
};</code></pre>
|
||
<p><code>process.stderr</code> and <code>process.stdout</code> are unlike other streams in Node in
|
||
that writes to them are usually blocking. They are blocking in the case
|
||
that they refer to regular files or TTY file descriptors. In the case they
|
||
refer to pipes, they are non-blocking like other streams.
|
||
|
||
|
||
</p>
|
||
<h2>process.stderr<span><a class="mark" href="#all_process_stderr" id="all_process_stderr">#</a></span></h2>
|
||
<p>A writable stream to stderr.
|
||
|
||
</p>
|
||
<p><code>process.stderr</code> and <code>process.stdout</code> are unlike other streams in Node in
|
||
that writes to them are usually blocking. They are blocking in the case
|
||
that they refer to regular files or TTY file descriptors. In the case they
|
||
refer to pipes, they are non-blocking like other streams.
|
||
|
||
|
||
</p>
|
||
<h2>process.stdin<span><a class="mark" href="#all_process_stdin" id="all_process_stdin">#</a></span></h2>
|
||
<p>A <code>Readable Stream</code> for stdin. The stdin stream is paused by default, so one
|
||
must call <code>process.stdin.resume()</code> to read from it.
|
||
|
||
</p>
|
||
<p>Example of opening standard input and listening for both events:
|
||
|
||
</p>
|
||
<pre><code>process.stdin.resume();
|
||
process.stdin.setEncoding('utf8');
|
||
|
||
process.stdin.on('data', function (chunk) {
|
||
process.stdout.write('data: ' + chunk);
|
||
});
|
||
|
||
process.stdin.on('end', function () {
|
||
process.stdout.write('end');
|
||
});</code></pre>
|
||
<h2>process.argv<span><a class="mark" href="#all_process_argv" id="all_process_argv">#</a></span></h2>
|
||
<p>An array containing the command line arguments. The first element will be
|
||
'node', the second element will be the name of the JavaScript file. The
|
||
next elements will be any additional command line arguments.
|
||
|
||
</p>
|
||
<pre><code>// print process.argv
|
||
process.argv.forEach(function (val, index, array) {
|
||
console.log(index + ': ' + val);
|
||
});</code></pre>
|
||
<p>This will generate:
|
||
|
||
</p>
|
||
<pre><code>$ node process-2.js one two=three four
|
||
0: node
|
||
1: /Users/mjr/work/node/process-2.js
|
||
2: one
|
||
3: two=three
|
||
4: four</code></pre>
|
||
<h2>process.execPath<span><a class="mark" href="#all_process_execpath" id="all_process_execpath">#</a></span></h2>
|
||
<p>This is the absolute pathname of the executable that started the process.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>/usr/local/bin/node</code></pre>
|
||
<h2>process.abort()<span><a class="mark" href="#all_process_abort" id="all_process_abort">#</a></span></h2>
|
||
<p>This causes node to emit an abort. This will cause node to exit and
|
||
generate a core file.
|
||
|
||
</p>
|
||
<h2>process.chdir(directory)<span><a class="mark" href="#all_process_chdir_directory" id="all_process_chdir_directory">#</a></span></h2>
|
||
<p>Changes the current working directory of the process or throws an exception if that fails.
|
||
|
||
</p>
|
||
<pre><code>console.log('Starting directory: ' + process.cwd());
|
||
try {
|
||
process.chdir('/tmp');
|
||
console.log('New directory: ' + process.cwd());
|
||
}
|
||
catch (err) {
|
||
console.log('chdir: ' + err);
|
||
}</code></pre>
|
||
<h2>process.cwd()<span><a class="mark" href="#all_process_cwd" id="all_process_cwd">#</a></span></h2>
|
||
<p>Returns the current working directory of the process.
|
||
|
||
</p>
|
||
<pre><code>console.log('Current directory: ' + process.cwd());</code></pre>
|
||
<h2>process.env<span><a class="mark" href="#all_process_env" id="all_process_env">#</a></span></h2>
|
||
<p>An object containing the user environment. See environ(7).
|
||
|
||
|
||
</p>
|
||
<h2>process.exit([code])<span><a class="mark" href="#all_process_exit_code" id="all_process_exit_code">#</a></span></h2>
|
||
<p>Ends the process with the specified <code>code</code>. If omitted, exit uses the
|
||
'success' code <code>0</code>.
|
||
|
||
</p>
|
||
<p>To exit with a 'failure' code:
|
||
|
||
</p>
|
||
<pre><code>process.exit(1);</code></pre>
|
||
<p>The shell that executed node should see the exit code as 1.
|
||
|
||
|
||
</p>
|
||
<h2>process.getgid()<span><a class="mark" href="#all_process_getgid" id="all_process_getgid">#</a></span></h2>
|
||
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
|
||
|
||
</p>
|
||
<p>Gets the group identity of the process. (See getgid(2).)
|
||
This is the numerical group id, not the group name.
|
||
|
||
</p>
|
||
<pre><code>if (process.getgid) {
|
||
console.log('Current gid: ' + process.getgid());
|
||
}</code></pre>
|
||
<h2>process.setgid(id)<span><a class="mark" href="#all_process_setgid_id" id="all_process_setgid_id">#</a></span></h2>
|
||
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
|
||
|
||
</p>
|
||
<p>Sets the group identity of the process. (See setgid(2).) This accepts either
|
||
a numerical ID or a groupname string. If a groupname is specified, this method
|
||
blocks while resolving it to a numerical ID.
|
||
|
||
</p>
|
||
<pre><code>if (process.getgid && process.setgid) {
|
||
console.log('Current gid: ' + process.getgid());
|
||
try {
|
||
process.setgid(501);
|
||
console.log('New gid: ' + process.getgid());
|
||
}
|
||
catch (err) {
|
||
console.log('Failed to set gid: ' + err);
|
||
}
|
||
}</code></pre>
|
||
<h2>process.getuid()<span><a class="mark" href="#all_process_getuid" id="all_process_getuid">#</a></span></h2>
|
||
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
|
||
|
||
</p>
|
||
<p>Gets the user identity of the process. (See getuid(2).)
|
||
This is the numerical userid, not the username.
|
||
|
||
</p>
|
||
<pre><code>if (process.getuid) {
|
||
console.log('Current uid: ' + process.getuid());
|
||
}</code></pre>
|
||
<h2>process.setuid(id)<span><a class="mark" href="#all_process_setuid_id" id="all_process_setuid_id">#</a></span></h2>
|
||
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
|
||
|
||
</p>
|
||
<p>Sets the user identity of the process. (See setuid(2).) This accepts either
|
||
a numerical ID or a username string. If a username is specified, this method
|
||
blocks while resolving it to a numerical ID.
|
||
|
||
</p>
|
||
<pre><code>if (process.getuid && process.setuid) {
|
||
console.log('Current uid: ' + process.getuid());
|
||
try {
|
||
process.setuid(501);
|
||
console.log('New uid: ' + process.getuid());
|
||
}
|
||
catch (err) {
|
||
console.log('Failed to set uid: ' + err);
|
||
}
|
||
}</code></pre>
|
||
<h2>process.version<span><a class="mark" href="#all_process_version" id="all_process_version">#</a></span></h2>
|
||
<p>A compiled-in property that exposes <code>NODE_VERSION</code>.
|
||
|
||
</p>
|
||
<pre><code>console.log('Version: ' + process.version);</code></pre>
|
||
<h2>process.versions<span><a class="mark" href="#all_process_versions" id="all_process_versions">#</a></span></h2>
|
||
<p>A property exposing version strings of node and its dependencies.
|
||
|
||
</p>
|
||
<pre><code>console.log(process.versions);</code></pre>
|
||
<p>Will output:
|
||
|
||
</p>
|
||
<pre><code>{ node: '0.4.12',
|
||
v8: '3.1.8.26',
|
||
ares: '1.7.4',
|
||
ev: '4.4',
|
||
openssl: '1.0.0e-fips' }</code></pre>
|
||
<h2>process.config<span><a class="mark" href="#all_process_config" id="all_process_config">#</a></span></h2>
|
||
<p>An Object containing the JavaScript representation of the configure options
|
||
that were used to compile the current node executable. This is the same as
|
||
the "config.gypi" file that was produced when running the <code>./configure</code> script.
|
||
|
||
</p>
|
||
<p>An example of the possible output looks like:
|
||
|
||
</p>
|
||
<pre><code>{ target_defaults:
|
||
{ cflags: [],
|
||
default_configuration: 'Release',
|
||
defines: [],
|
||
include_dirs: [],
|
||
libraries: [] },
|
||
variables:
|
||
{ host_arch: 'x64',
|
||
node_install_npm: 'true',
|
||
node_install_waf: 'true',
|
||
node_prefix: '',
|
||
node_shared_v8: 'false',
|
||
node_shared_zlib: 'false',
|
||
node_use_dtrace: 'false',
|
||
node_use_openssl: 'true',
|
||
node_shared_openssl: 'false',
|
||
strict_aliasing: 'true',
|
||
target_arch: 'x64',
|
||
v8_use_snapshot: 'true' } }</code></pre>
|
||
<h2>process.kill(pid, [signal])<span><a class="mark" href="#all_process_kill_pid_signal" id="all_process_kill_pid_signal">#</a></span></h2>
|
||
<p>Send a signal to a process. <code>pid</code> is the process id and <code>signal</code> is the
|
||
string describing the signal to send. Signal names are strings like
|
||
'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'.
|
||
See kill(2) for more information.
|
||
|
||
</p>
|
||
<p>Note that just because the name of this function is <code>process.kill</code>, it is
|
||
really just a signal sender, like the <code>kill</code> system call. The signal sent
|
||
may do something other than kill the target process.
|
||
|
||
</p>
|
||
<p>Example of sending a signal to yourself:
|
||
|
||
</p>
|
||
<pre><code>process.on('SIGHUP', function () {
|
||
console.log('Got SIGHUP signal.');
|
||
});
|
||
|
||
setTimeout(function () {
|
||
console.log('Exiting.');
|
||
process.exit(0);
|
||
}, 100);
|
||
|
||
process.kill(process.pid, 'SIGHUP');</code></pre>
|
||
<h2>process.pid<span><a class="mark" href="#all_process_pid" id="all_process_pid">#</a></span></h2>
|
||
<p>The PID of the process.
|
||
|
||
</p>
|
||
<pre><code>console.log('This process is pid ' + process.pid);</code></pre>
|
||
<h2>process.title<span><a class="mark" href="#all_process_title" id="all_process_title">#</a></span></h2>
|
||
<p>Getter/setter to set what is displayed in 'ps'.
|
||
|
||
|
||
</p>
|
||
<h2>process.arch<span><a class="mark" href="#all_process_arch" id="all_process_arch">#</a></span></h2>
|
||
<p>What processor architecture you're running on: <code>'arm'</code>, <code>'ia32'</code>, or <code>'x64'</code>.
|
||
|
||
</p>
|
||
<pre><code>console.log('This processor architecture is ' + process.arch);</code></pre>
|
||
<h2>process.platform<span><a class="mark" href="#all_process_platform" id="all_process_platform">#</a></span></h2>
|
||
<p>What platform you're running on:
|
||
<code>'darwin'</code>, <code>'freebsd'</code>, <code>'linux'</code>, <code>'sunos'</code> or <code>'win32'</code>
|
||
|
||
</p>
|
||
<pre><code>console.log('This platform is ' + process.platform);</code></pre>
|
||
<h2>process.memoryUsage()<span><a class="mark" href="#all_process_memoryusage" id="all_process_memoryusage">#</a></span></h2>
|
||
<p>Returns an object describing the memory usage of the Node process
|
||
measured in bytes.
|
||
|
||
</p>
|
||
<pre><code>var util = require('util');
|
||
|
||
console.log(util.inspect(process.memoryUsage()));</code></pre>
|
||
<p>This will generate:
|
||
|
||
</p>
|
||
<pre><code>{ rss: 4935680,
|
||
heapTotal: 1826816,
|
||
heapUsed: 650472 }</code></pre>
|
||
<p><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage.
|
||
|
||
|
||
</p>
|
||
<h2>process.nextTick(callback)<span><a class="mark" href="#all_process_nexttick_callback" id="all_process_nexttick_callback">#</a></span></h2>
|
||
<p>On the next loop around the event loop call this callback.
|
||
This is <em>not</em> a simple alias to <code>setTimeout(fn, 0)</code>, it's much more
|
||
efficient.
|
||
|
||
</p>
|
||
<pre><code>process.nextTick(function () {
|
||
console.log('nextTick callback');
|
||
});</code></pre>
|
||
<h2>process.umask([mask])<span><a class="mark" href="#all_process_umask_mask" id="all_process_umask_mask">#</a></span></h2>
|
||
<p>Sets or reads the process's file mode creation mask. Child processes inherit
|
||
the mask from the parent process. Returns the old mask if <code>mask</code> argument is
|
||
given, otherwise returns the current mask.
|
||
|
||
</p>
|
||
<pre><code>var oldmask, newmask = 0644;
|
||
|
||
oldmask = process.umask(newmask);
|
||
console.log('Changed umask from: ' + oldmask.toString(8) +
|
||
' to ' + newmask.toString(8));</code></pre>
|
||
<h2>process.uptime()<span><a class="mark" href="#all_process_uptime" id="all_process_uptime">#</a></span></h2>
|
||
<p>Number of seconds Node has been running.
|
||
|
||
|
||
</p>
|
||
<h2>process.hrtime()<span><a class="mark" href="#all_process_hrtime" id="all_process_hrtime">#</a></span></h2>
|
||
<p>Returns the current high-resolution real time in a <code>[seconds, nanoseconds]</code>
|
||
tuple Array. It is relative to an arbitrary time in the past. It is not
|
||
related to the time of day and therefore not subject to clock drift. The
|
||
primary use is for measuring performance between intervals.
|
||
|
||
</p>
|
||
<p>You may pass in the result of a previous call to <code>process.hrtime()</code> to get
|
||
a diff reading, useful for benchmarks and measuring intervals:
|
||
|
||
</p>
|
||
<pre><code>var time = process.hrtime();
|
||
// [ 1800216, 927643717 ]
|
||
|
||
setTimeout(function () {
|
||
var diff = process.hrtime(time);
|
||
// [ 1, 6962306 ]
|
||
|
||
console.log('benchmark took %d seconds and %d nanoseconds',
|
||
diff[0], diff[1]);
|
||
// benchmark took 1 seconds and 6962306 nanoseconds
|
||
}, 1000);</code></pre>
|
||
<h1>util<span><a class="mark" href="#all_util" id="all_util">#</a></span></h1>
|
||
<pre><code>Stability: 5 - Locked</code></pre>
|
||
<p>These functions are in the module <code>'util'</code>. Use <code>require('util')</code> to access
|
||
them.
|
||
|
||
|
||
</p>
|
||
<h2>util.format(format, [...])<span><a class="mark" href="#all_util_format_format" id="all_util_format_format">#</a></span></h2>
|
||
<p>Returns a formatted string using the first argument as a <code>printf</code>-like format.
|
||
|
||
</p>
|
||
<p>The first argument is a string that contains zero or more <em>placeholders</em>.
|
||
Each placeholder is replaced with the converted value from its corresponding
|
||
argument. Supported placeholders are:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>%s</code> - String.</li>
|
||
<li><code>%d</code> - Number (both integer and float).</li>
|
||
<li><code>%j</code> - JSON.</li>
|
||
<li><code>%</code> - single percent sign (<code>'%'</code>). This does not consume an argument.</li>
|
||
</ul>
|
||
<p>If the placeholder does not have a corresponding argument, the placeholder is
|
||
not replaced.
|
||
|
||
</p>
|
||
<pre><code>util.format('%s:%s', 'foo'); // 'foo:%s'</code></pre>
|
||
<p>If there are more arguments than placeholders, the extra arguments are
|
||
converted to strings with <code>util.inspect()</code> and these strings are concatenated,
|
||
delimited by a space.
|
||
|
||
</p>
|
||
<pre><code>util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'</code></pre>
|
||
<p>If the first argument is not a format string then <code>util.format()</code> returns
|
||
a string that is the concatenation of all its arguments separated by spaces.
|
||
Each argument is converted to a string with <code>util.inspect()</code>.
|
||
|
||
</p>
|
||
<pre><code>util.format(1, 2, 3); // '1 2 3'</code></pre>
|
||
<h2>util.debug(string)<span><a class="mark" href="#all_util_debug_string" id="all_util_debug_string">#</a></span></h2>
|
||
<p>A synchronous output function. Will block the process and
|
||
output <code>string</code> immediately to <code>stderr</code>.
|
||
|
||
</p>
|
||
<pre><code>require('util').debug('message on stderr');</code></pre>
|
||
<h2>util.error([...])<span><a class="mark" href="#all_util_error" id="all_util_error">#</a></span></h2>
|
||
<p>Same as <code>util.debug()</code> except this will output all arguments immediately to
|
||
<code>stderr</code>.
|
||
|
||
</p>
|
||
<h2>util.puts([...])<span><a class="mark" href="#all_util_puts" id="all_util_puts">#</a></span></h2>
|
||
<p>A synchronous output function. Will block the process and output all arguments
|
||
to <code>stdout</code> with newlines after each argument.
|
||
|
||
</p>
|
||
<h2>util.print([...])<span><a class="mark" href="#all_util_print" id="all_util_print">#</a></span></h2>
|
||
<p>A synchronous output function. Will block the process, cast each argument to a
|
||
string then output to <code>stdout</code>. Does not place newlines after each argument.
|
||
|
||
</p>
|
||
<h2>util.log(string)<span><a class="mark" href="#all_util_log_string" id="all_util_log_string">#</a></span></h2>
|
||
<p>Output with timestamp on <code>stdout</code>.
|
||
|
||
</p>
|
||
<pre><code>require('util').log('Timestamped message.');</code></pre>
|
||
<h2>util.inspect(object, [showHidden], [depth], [colors])<span><a class="mark" href="#all_util_inspect_object_showhidden_depth_colors" id="all_util_inspect_object_showhidden_depth_colors">#</a></span></h2>
|
||
<p>Return a string representation of <code>object</code>, which is useful for debugging.
|
||
|
||
</p>
|
||
<p>If <code>showHidden</code> is <code>true</code>, then the object's non-enumerable properties will be
|
||
shown too. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>If <code>depth</code> is provided, it tells <code>inspect</code> how many times to recurse while
|
||
formatting the object. This is useful for inspecting large complicated objects.
|
||
|
||
</p>
|
||
<p>The default is to only recurse twice. To make it recurse indefinitely, pass
|
||
in <code>null</code> for <code>depth</code>.
|
||
|
||
</p>
|
||
<p>If <code>colors</code> is <code>true</code>, the output will be styled with ANSI color codes.
|
||
Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example of inspecting all properties of the <code>util</code> object:
|
||
|
||
</p>
|
||
<pre><code>var util = require('util');
|
||
|
||
console.log(util.inspect(util, true, null));</code></pre>
|
||
<p>Objects also may define their own <code>inspect(depth)</code> function which <code>util.inspect()</code>
|
||
will invoke and use the result of when inspecting the object:
|
||
|
||
</p>
|
||
<pre><code>var util = require('util');
|
||
|
||
var obj = { name: 'nate' };
|
||
obj.inspect = function(depth) {
|
||
return '{' + this.name + '}';
|
||
};
|
||
|
||
util.inspect(obj);
|
||
// "{nate}"</code></pre>
|
||
<h2>util.isArray(object)<span><a class="mark" href="#all_util_isarray_object" id="all_util_isarray_object">#</a></span></h2>
|
||
<p>Returns <code>true</code> if the given "object" is an <code>Array</code>. <code>false</code> otherwise.
|
||
|
||
</p>
|
||
<pre><code>var util = require('util');
|
||
|
||
util.isArray([])
|
||
// true
|
||
util.isArray(new Array)
|
||
// true
|
||
util.isArray({})
|
||
// false</code></pre>
|
||
<h2>util.isRegExp(object)<span><a class="mark" href="#all_util_isregexp_object" id="all_util_isregexp_object">#</a></span></h2>
|
||
<p>Returns <code>true</code> if the given "object" is a <code>RegExp</code>. <code>false</code> otherwise.
|
||
|
||
</p>
|
||
<pre><code>var util = require('util');
|
||
|
||
util.isRegExp(/some regexp/)
|
||
// true
|
||
util.isRegExp(new RegExp('another regexp'))
|
||
// true
|
||
util.isRegExp({})
|
||
// false</code></pre>
|
||
<h2>util.isDate(object)<span><a class="mark" href="#all_util_isdate_object" id="all_util_isdate_object">#</a></span></h2>
|
||
<p>Returns <code>true</code> if the given "object" is a <code>Date</code>. <code>false</code> otherwise.
|
||
|
||
</p>
|
||
<pre><code>var util = require('util');
|
||
|
||
util.isDate(new Date())
|
||
// true
|
||
util.isDate(Date())
|
||
// false (without 'new' returns a String)
|
||
util.isDate({})
|
||
// false</code></pre>
|
||
<h2>util.isError(object)<span><a class="mark" href="#all_util_iserror_object" id="all_util_iserror_object">#</a></span></h2>
|
||
<p>Returns <code>true</code> if the given "object" is an <code>Error</code>. <code>false</code> otherwise.
|
||
|
||
</p>
|
||
<pre><code>var util = require('util');
|
||
|
||
util.isError(new Error())
|
||
// true
|
||
util.isError(new TypeError())
|
||
// true
|
||
util.isError({ name: 'Error', message: 'an error occurred' })
|
||
// false</code></pre>
|
||
<h2>util.pump(readableStream, writableStream, [callback])<span><a class="mark" href="#all_util_pump_readablestream_writablestream_callback" id="all_util_pump_readablestream_writablestream_callback">#</a></span></h2>
|
||
<pre><code>Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)</code></pre>
|
||
<p>Read the data from <code>readableStream</code> and send it to the <code>writableStream</code>.
|
||
When <code>writableStream.write(data)</code> returns <code>false</code> <code>readableStream</code> will be
|
||
paused until the <code>drain</code> event occurs on the <code>writableStream</code>. <code>callback</code> gets
|
||
an error as its only argument and is called when <code>writableStream</code> is closed or
|
||
when an error occurs.
|
||
|
||
|
||
</p>
|
||
<h2>util.inherits(constructor, superConstructor)<span><a class="mark" href="#all_util_inherits_constructor_superconstructor" id="all_util_inherits_constructor_superconstructor">#</a></span></h2>
|
||
<p>Inherit the prototype methods from one
|
||
<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a>
|
||
into another. The prototype of <code>constructor</code> will be set to a new
|
||
object created from <code>superConstructor</code>.
|
||
|
||
</p>
|
||
<p>As an additional convenience, <code>superConstructor</code> will be accessible
|
||
through the <code>constructor.super_</code> property.
|
||
|
||
</p>
|
||
<pre><code>var util = require("util");
|
||
var events = require("events");
|
||
|
||
function MyStream() {
|
||
events.EventEmitter.call(this);
|
||
}
|
||
|
||
util.inherits(MyStream, events.EventEmitter);
|
||
|
||
MyStream.prototype.write = function(data) {
|
||
this.emit("data", data);
|
||
}
|
||
|
||
var stream = new MyStream();
|
||
|
||
console.log(stream instanceof events.EventEmitter); // true
|
||
console.log(MyStream.super_ === events.EventEmitter); // true
|
||
|
||
stream.on("data", function(data) {
|
||
console.log('Received data: "' + data + '"');
|
||
})
|
||
stream.write("It works!"); // Received data: "It works!"</code></pre>
|
||
<h1>Events<span><a class="mark" href="#all_events" id="all_events">#</a></span></h1>
|
||
<pre><code>Stability: 4 - API Frozen</code></pre>
|
||
<!--type=module-->
|
||
|
||
<p>Many objects in Node emit events: a <code>net.Server</code> emits an event each time
|
||
a peer connects to it, a <code>fs.readStream</code> emits an event when the file is
|
||
opened. All objects which emit events are instances of <code>events.EventEmitter</code>.
|
||
You can access this module by doing: <code>require("events");</code>
|
||
|
||
</p>
|
||
<p>Typically, event names are represented by a camel-cased string, however,
|
||
there aren't any strict restrictions on that, as any string will be accepted.
|
||
|
||
</p>
|
||
<p>Functions can then be attached to objects, to be executed when an event
|
||
is emitted. These functions are called <em>listeners</em>.
|
||
|
||
|
||
</p>
|
||
<h2>Class: events.EventEmitter<span><a class="mark" href="#all_class_events_eventemitter" id="all_class_events_eventemitter">#</a></span></h2>
|
||
<p>To access the EventEmitter class, <code>require('events').EventEmitter</code>.
|
||
|
||
</p>
|
||
<p>When an <code>EventEmitter</code> instance experiences an error, the typical action is
|
||
to emit an <code>'error'</code> event. Error events are treated as a special case in node.
|
||
If there is no listener for it, then the default action is to print a stack
|
||
trace and exit the program.
|
||
|
||
</p>
|
||
<p>All EventEmitters emit the event <code>'newListener'</code> when new listeners are
|
||
added.
|
||
|
||
</p>
|
||
<h3>emitter.addListener(event, listener)<span><a class="mark" href="#all_emitter_addlistener_event_listener" id="all_emitter_addlistener_event_listener">#</a></span></h3>
|
||
<h3>emitter.on(event, listener)<span><a class="mark" href="#all_emitter_on_event_listener" id="all_emitter_on_event_listener">#</a></span></h3>
|
||
<p>Adds a listener to the end of the listeners array for the specified event.
|
||
|
||
</p>
|
||
<pre><code>server.on('connection', function (stream) {
|
||
console.log('someone connected!');
|
||
});</code></pre>
|
||
<h3>emitter.once(event, listener)<span><a class="mark" href="#all_emitter_once_event_listener" id="all_emitter_once_event_listener">#</a></span></h3>
|
||
<p>Adds a <strong>one time</strong> listener for the event. This listener is
|
||
invoked only the next time the event is fired, after which
|
||
it is removed.
|
||
|
||
</p>
|
||
<pre><code>server.once('connection', function (stream) {
|
||
console.log('Ah, we have our first user!');
|
||
});</code></pre>
|
||
<h3>emitter.removeListener(event, listener)<span><a class="mark" href="#all_emitter_removelistener_event_listener" id="all_emitter_removelistener_event_listener">#</a></span></h3>
|
||
<p>Remove a listener from the listener array for the specified event.
|
||
<strong>Caution</strong>: changes array indices in the listener array behind the listener.
|
||
|
||
</p>
|
||
<pre><code>var callback = function(stream) {
|
||
console.log('someone connected!');
|
||
};
|
||
server.on('connection', callback);
|
||
// ...
|
||
server.removeListener('connection', callback);</code></pre>
|
||
<h3>emitter.removeAllListeners([event])<span><a class="mark" href="#all_emitter_removealllisteners_event" id="all_emitter_removealllisteners_event">#</a></span></h3>
|
||
<p>Removes all listeners, or those of the specified event.
|
||
|
||
</p>
|
||
<p>Note that this will <strong>invalidate</strong> any arrays that have previously been
|
||
returned by <code>emitter.listeners(event)</code>.
|
||
|
||
|
||
</p>
|
||
<h3>emitter.setMaxListeners(n)<span><a class="mark" href="#all_emitter_setmaxlisteners_n" id="all_emitter_setmaxlisteners_n">#</a></span></h3>
|
||
<p>By default EventEmitters will print a warning if more than 10 listeners are
|
||
added for a particular event. This is a useful default which helps finding memory leaks.
|
||
Obviously not all Emitters should be limited to 10. This function allows
|
||
that to be increased. Set to zero for unlimited.
|
||
|
||
|
||
</p>
|
||
<h3>emitter.listeners(event)<span><a class="mark" href="#all_emitter_listeners_event" id="all_emitter_listeners_event">#</a></span></h3>
|
||
<p>Returns an array of listeners for the specified event.
|
||
|
||
</p>
|
||
<pre><code>server.on('connection', function (stream) {
|
||
console.log('someone connected!');
|
||
});
|
||
console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]</code></pre>
|
||
<p>This array <strong>may</strong> be a mutable reference to the same underlying list of
|
||
listeners that is used by the event subsystem. However, certain
|
||
actions (specifically, removeAllListeners) will invalidate this
|
||
reference.
|
||
|
||
</p>
|
||
<p>If you would like to get a copy of the listeners at a specific point in
|
||
time that is guaranteed not to change, make a copy, for example by doing
|
||
<code>emitter.listeners(event).slice(0)</code>.
|
||
|
||
</p>
|
||
<p>In a future release of node, this behavior <strong>may</strong> change to always
|
||
return a copy, for consistency. In your programs, please do not rely on
|
||
being able to modify the EventEmitter listeners using array methods.
|
||
Always use the 'on' method to add new listeners.
|
||
|
||
</p>
|
||
<h3>emitter.emit(event, [arg1], [arg2], [...])<span><a class="mark" href="#all_emitter_emit_event_arg1_arg2" id="all_emitter_emit_event_arg1_arg2">#</a></span></h3>
|
||
<p>Execute each of the listeners in order with the supplied arguments.
|
||
|
||
</p>
|
||
<h3>Event: 'newListener'<span><a class="mark" href="#all_event_newlistener" id="all_event_newlistener">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>event</code> <span class="type">String</span> The event name</li>
|
||
<li><code>listener</code> <span class="type">Function</span> The event handler function</li>
|
||
</div></ul>
|
||
<p>This event is emitted any time someone adds a new listener.
|
||
|
||
</p>
|
||
<h1>Domain<span><a class="mark" href="#all_domain" id="all_domain">#</a></span></h1>
|
||
<pre><code>Stability: 1 - Experimental</code></pre>
|
||
<p>Domains provide a way to handle multiple different IO operations as a
|
||
single group. If any of the event emitters or callbacks registered to a
|
||
domain emit an <code>error</code> event, or throw an error, then the domain object
|
||
will be notified, rather than losing the context of the error in the
|
||
<code>process.on('uncaughtException')</code> handler, or causing the program to
|
||
exit with an error code.
|
||
|
||
</p>
|
||
<p>This feature is new in Node version 0.8. It is a first pass, and is
|
||
expected to change significantly in future versions. Please use it and
|
||
provide feedback.
|
||
|
||
</p>
|
||
<p>Due to their experimental nature, the Domains features are disabled unless
|
||
the <code>domain</code> module is loaded at least once. No domains are created or
|
||
registered by default. This is by design, to prevent adverse effects on
|
||
current programs. It is expected to be enabled by default in future
|
||
Node.js versions.
|
||
|
||
</p>
|
||
<h2>Additions to Error objects<span><a class="mark" href="#all_additions_to_error_objects" id="all_additions_to_error_objects">#</a></span></h2>
|
||
<!-- type=misc -->
|
||
|
||
<p>Any time an Error object is routed through a domain, a few extra fields
|
||
are added to it.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>error.domain</code> The domain that first handled the error.</li>
|
||
<li><code>error.domain_emitter</code> The event emitter that emitted an 'error' event
|
||
with the error object.</li>
|
||
<li><code>error.domain_bound</code> The callback function which was bound to the
|
||
domain, and passed an error as its first argument.</li>
|
||
<li><code>error.domain_thrown</code> A boolean indicating whether the error was
|
||
thrown, emitted, or passed to a bound callback function.</li>
|
||
</ul>
|
||
<h2>Implicit Binding<span><a class="mark" href="#all_implicit_binding" id="all_implicit_binding">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>If domains are in use, then all new EventEmitter objects (including
|
||
Stream objects, requests, responses, etc.) will be implicitly bound to
|
||
the active domain at the time of their creation.
|
||
|
||
</p>
|
||
<p>Additionally, callbacks passed to lowlevel event loop requests (such as
|
||
to fs.open, or other callback-taking methods) will automatically be
|
||
bound to the active domain. If they throw, then the domain will catch
|
||
the error.
|
||
|
||
</p>
|
||
<p>In order to prevent excessive memory usage, Domain objects themselves
|
||
are not implicitly added as children of the active domain. If they
|
||
were, then it would be too easy to prevent request and response objects
|
||
from being properly garbage collected.
|
||
|
||
</p>
|
||
<p>If you <em>want</em> to nest Domain objects as children of a parent Domain,
|
||
then you must explicitly add them, and then dispose of them later.
|
||
|
||
</p>
|
||
<p>Implicit binding routes thrown errors and <code>'error'</code> events to the
|
||
Domain's <code>error</code> event, but does not register the EventEmitter on the
|
||
Domain, so <code>domain.dispose()</code> will not shut down the EventEmitter.
|
||
Implicit binding only takes care of thrown errors and <code>'error'</code> events.
|
||
|
||
</p>
|
||
<h2>Explicit Binding<span><a class="mark" href="#all_explicit_binding" id="all_explicit_binding">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>Sometimes, the domain in use is not the one that ought to be used for a
|
||
specific event emitter. Or, the event emitter could have been created
|
||
in the context of one domain, but ought to instead be bound to some
|
||
other domain.
|
||
|
||
</p>
|
||
<p>For example, there could be one domain in use for an HTTP server, but
|
||
perhaps we would like to have a separate domain to use for each request.
|
||
|
||
</p>
|
||
<p>That is possible via explicit binding.
|
||
|
||
</p>
|
||
<p>For example:
|
||
|
||
</p>
|
||
<pre><code>// create a top-level domain for the server
|
||
var serverDomain = domain.create();
|
||
|
||
serverDomain.run(function() {
|
||
// server is created in the scope of serverDomain
|
||
http.createServer(function(req, res) {
|
||
// req and res are also created in the scope of serverDomain
|
||
// however, we'd prefer to have a separate domain for each request.
|
||
// create it first thing, and add req and res to it.
|
||
var reqd = domain.create();
|
||
reqd.add(req);
|
||
reqd.add(res);
|
||
reqd.on('error', function(er) {
|
||
console.error('Error', er, req.url);
|
||
try {
|
||
res.writeHead(500);
|
||
res.end('Error occurred, sorry.');
|
||
res.on('close', function() {
|
||
// forcibly shut down any other things added to this domain
|
||
reqd.dispose();
|
||
});
|
||
} catch (er) {
|
||
console.error('Error sending 500', er, req.url);
|
||
// tried our best. clean up anything remaining.
|
||
reqd.dispose();
|
||
}
|
||
});
|
||
}).listen(1337);
|
||
});</code></pre>
|
||
<h2>domain.create()<span><a class="mark" href="#all_domain_create" id="all_domain_create">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li>return: <span class="type">Domain</span></li>
|
||
</div></ul>
|
||
<p>Returns a new Domain object.
|
||
|
||
</p>
|
||
<h2>Class: Domain<span><a class="mark" href="#all_class_domain" id="all_class_domain">#</a></span></h2>
|
||
<p>The Domain class encapsulates the functionality of routing errors and
|
||
uncaught exceptions to the active Domain object.
|
||
|
||
</p>
|
||
<p>Domain is a child class of <a href="events.html#events_class_events_eventemitter">EventEmitter</a>. To handle the errors that it
|
||
catches, listen to its <code>error</code> event.
|
||
|
||
</p>
|
||
<h3>domain.run(fn)<span><a class="mark" href="#all_domain_run_fn" id="all_domain_run_fn">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>fn</code> <span class="type">Function</span></li>
|
||
</div></ul>
|
||
<p>Run the supplied function in the context of the domain, implicitly
|
||
binding all event emitters, timers, and lowlevel requests that are
|
||
created in that context.
|
||
|
||
</p>
|
||
<p>This is the most basic way to use a domain.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var d = domain.create();
|
||
d.on('error', function(er) {
|
||
console.error('Caught error!', er);
|
||
});
|
||
d.run(function() {
|
||
process.nextTick(function() {
|
||
setTimeout(function() { // simulating some various async stuff
|
||
fs.open('non-existent file', 'r', function(er, fd) {
|
||
if (er) throw er;
|
||
// proceed...
|
||
});
|
||
}, 100);
|
||
});
|
||
});</code></pre>
|
||
<p>In this example, the <code>d.on('error')</code> handler will be triggered, rather
|
||
than crashing the program.
|
||
|
||
</p>
|
||
<h3>domain.members<span><a class="mark" href="#all_domain_members" id="all_domain_members">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Array</span></li>
|
||
</div></ul>
|
||
<p>An array of timers and event emitters that have been explicitly added
|
||
to the domain.
|
||
|
||
</p>
|
||
<h3>domain.add(emitter)<span><a class="mark" href="#all_domain_add_emitter" id="all_domain_add_emitter">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>emitter</code> <span class="type">EventEmitter | Timer</span> emitter or timer to be added to the domain</li>
|
||
</div></ul>
|
||
<p>Explicitly adds an emitter to the domain. If any event handlers called by
|
||
the emitter throw an error, or if the emitter emits an <code>error</code> event, it
|
||
will be routed to the domain's <code>error</code> event, just like with implicit
|
||
binding.
|
||
|
||
</p>
|
||
<p>This also works with timers that are returned from <code>setInterval</code> and
|
||
<code>setTimeout</code>. If their callback function throws, it will be caught by
|
||
the domain 'error' handler.
|
||
|
||
</p>
|
||
<p>If the Timer or EventEmitter was already bound to a domain, it is removed
|
||
from that one, and bound to this one instead.
|
||
|
||
</p>
|
||
<h3>domain.remove(emitter)<span><a class="mark" href="#all_domain_remove_emitter" id="all_domain_remove_emitter">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>emitter</code> <span class="type">EventEmitter | Timer</span> emitter or timer to be removed from the domain</li>
|
||
</div></ul>
|
||
<p>The opposite of <code>domain.add(emitter)</code>. Removes domain handling from the
|
||
specified emitter.
|
||
|
||
</p>
|
||
<h3>domain.bind(callback)<span><a class="mark" href="#all_domain_bind_callback" id="all_domain_bind_callback">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>callback</code> <span class="type">Function</span> The callback function</li>
|
||
<li>return: <span class="type">Function</span> The bound function</li>
|
||
</div></ul>
|
||
<p>The returned function will be a wrapper around the supplied callback
|
||
function. When the returned function is called, any errors that are
|
||
thrown will be routed to the domain's <code>error</code> event.
|
||
|
||
</p>
|
||
<h4>Example<span><a class="mark" href="#all_example" id="all_example">#</a></span></h4>
|
||
<pre><code>var d = domain.create();
|
||
|
||
function readSomeFile(filename, cb) {
|
||
fs.readFile(filename, 'utf8', d.bind(function(er, data) {
|
||
// if this throws, it will also be passed to the domain
|
||
return cb(er, data ? JSON.parse(data) : null);
|
||
}));
|
||
}
|
||
|
||
d.on('error', function(er) {
|
||
// an error occurred somewhere.
|
||
// if we throw it now, it will crash the program
|
||
// with the normal line number and stack message.
|
||
});</code></pre>
|
||
<h3>domain.intercept(callback)<span><a class="mark" href="#all_domain_intercept_callback" id="all_domain_intercept_callback">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>callback</code> <span class="type">Function</span> The callback function</li>
|
||
<li>return: <span class="type">Function</span> The intercepted function</li>
|
||
</div></ul>
|
||
<p>This method is almost identical to <code>domain.bind(callback)</code>. However, in
|
||
addition to catching thrown errors, it will also intercept <code>Error</code>
|
||
objects sent as the first argument to the function.
|
||
|
||
</p>
|
||
<p>In this way, the common <code>if (er) return callback(er);</code> pattern can be replaced
|
||
with a single error handler in a single place.
|
||
|
||
</p>
|
||
<h4>Example<span><a class="mark" href="#all_example_1" id="all_example_1">#</a></span></h4>
|
||
<pre><code>var d = domain.create();
|
||
|
||
function readSomeFile(filename, cb) {
|
||
fs.readFile(filename, 'utf8', d.intercept(function(data) {
|
||
// note, the first argument is never passed to the
|
||
// callback since it is assumed to be the 'Error' argument
|
||
// and thus intercepted by the domain.
|
||
|
||
// if this throws, it will also be passed to the domain
|
||
// so the error-handling logic can be moved to the 'error'
|
||
// event on the domain instead of being repeated throughout
|
||
// the program.
|
||
return cb(null, JSON.parse(data));
|
||
}));
|
||
}
|
||
|
||
d.on('error', function(er) {
|
||
// an error occurred somewhere.
|
||
// if we throw it now, it will crash the program
|
||
// with the normal line number and stack message.
|
||
});</code></pre>
|
||
<h3>domain.dispose()<span><a class="mark" href="#all_domain_dispose" id="all_domain_dispose">#</a></span></h3>
|
||
<p>The dispose method destroys a domain, and makes a best effort attempt to
|
||
clean up any and all IO that is associated with the domain. Streams are
|
||
aborted, ended, closed, and/or destroyed. Timers are cleared.
|
||
Explicitly bound callbacks are no longer called. Any error events that
|
||
are raised as a result of this are ignored.
|
||
|
||
</p>
|
||
<p>The intention of calling <code>dispose</code> is generally to prevent cascading
|
||
errors when a critical part of the Domain context is found to be in an
|
||
error state.
|
||
|
||
</p>
|
||
<p>Once the domain is disposed the <code>dispose</code> event will emit.
|
||
|
||
</p>
|
||
<p>Note that IO might still be performed. However, to the highest degree
|
||
possible, once a domain is disposed, further errors from the emitters in
|
||
that set will be ignored. So, even if some remaining actions are still
|
||
in flight, Node.js will not communicate further about them.
|
||
|
||
</p>
|
||
<h1>Buffer<span><a class="mark" href="#all_buffer" id="all_buffer">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>Pure JavaScript is Unicode friendly but not nice to binary data. When
|
||
dealing with TCP streams or the file system, it's necessary to handle octet
|
||
streams. Node has several strategies for manipulating, creating, and
|
||
consuming octet streams.
|
||
|
||
</p>
|
||
<p>Raw data is stored in instances of the <code>Buffer</code> class. A <code>Buffer</code> is similar
|
||
to an array of integers but corresponds to a raw memory allocation outside
|
||
the V8 heap. A <code>Buffer</code> cannot be resized.
|
||
|
||
</p>
|
||
<p>The <code>Buffer</code> class is a global, making it very rare that one would need
|
||
to ever <code>require('buffer')</code>.
|
||
|
||
</p>
|
||
<p>Converting between Buffers and JavaScript string objects requires an explicit
|
||
encoding method. Here are the different string encodings.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>'ascii'</code> - for 7 bit ASCII data only. This encoding method is very fast, and
|
||
will strip the high bit if set.
|
||
Note that this encoding converts a null character (<code>'\0'</code> or <code>'\u0000'</code>) into
|
||
<code>0x20</code> (character code of a space). If you want to convert a null character
|
||
into <code>0x00</code>, you should use <code>'utf8'</code>.</p>
|
||
</li>
|
||
<li><p><code>'utf8'</code> - Multibyte encoded Unicode characters. Many web pages and other
|
||
document formats use UTF-8.</p>
|
||
</li>
|
||
<li><p><code>'utf16le'</code> - 2 or 4 bytes, little endian encoded Unicode characters.
|
||
Surrogate pairs (U+10000 to U+10FFFF) are supported.</p>
|
||
</li>
|
||
<li><p><code>'ucs2'</code> - Alias of <code>'utf16le'</code>.</p>
|
||
</li>
|
||
<li><p><code>'base64'</code> - Base64 string encoding.</p>
|
||
</li>
|
||
<li><p><code>'binary'</code> - A way of encoding raw binary data into strings by using only
|
||
the first 8 bits of each character. This encoding method is deprecated and
|
||
should be avoided in favor of <code>Buffer</code> objects where possible. This encoding
|
||
will be removed in future versions of Node.</p>
|
||
</li>
|
||
<li><p><code>'hex'</code> - Encode each byte as two hexadecimal characters.</p>
|
||
</li>
|
||
</ul>
|
||
<h2>Class: Buffer<span><a class="mark" href="#all_class_buffer_1" id="all_class_buffer_1">#</a></span></h2>
|
||
<p>The Buffer class is a global type for dealing with binary data directly.
|
||
It can be constructed in a variety of ways.
|
||
|
||
</p>
|
||
<h3>new Buffer(size)<span><a class="mark" href="#all_new_buffer_size" id="all_new_buffer_size">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>size</code> Number</li>
|
||
</div></ul>
|
||
<p>Allocates a new buffer of <code>size</code> octets.
|
||
|
||
</p>
|
||
<h3>new Buffer(array)<span><a class="mark" href="#all_new_buffer_array" id="all_new_buffer_array">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>array</code> Array</li>
|
||
</div></ul>
|
||
<p>Allocates a new buffer using an <code>array</code> of octets.
|
||
|
||
</p>
|
||
<h3>new Buffer(str, [encoding])<span><a class="mark" href="#all_new_buffer_str_encoding" id="all_new_buffer_str_encoding">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>str</code> String - string to encode.</li>
|
||
<li><code>encoding</code> String - encoding to use, Optional.</li>
|
||
</div></ul>
|
||
<p>Allocates a new buffer containing the given <code>str</code>.
|
||
<code>encoding</code> defaults to <code>'utf8'</code>.
|
||
|
||
</p>
|
||
<h3>buf.write(string, [offset], [length], [encoding])<span><a class="mark" href="#all_buf_write_string_offset_length_encoding" id="all_buf_write_string_offset_length_encoding">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>string</code> String - data to be written to buffer</li>
|
||
<li><code>offset</code> Number, Optional, Default: 0</li>
|
||
<li><code>length</code> Number, Optional, Default: <code>buffer.length - offset</code></li>
|
||
<li><code>encoding</code> String, Optional, Default: 'utf8'</li>
|
||
</div></ul>
|
||
<p>Writes <code>string</code> to the buffer at <code>offset</code> using the given encoding.
|
||
<code>offset</code> defaults to <code>0</code>, <code>encoding</code> defaults to <code>'utf8'</code>. <code>length</code> is
|
||
the number of bytes to write. Returns number of octets written. If <code>buffer</code> did
|
||
not contain enough space to fit the entire string, it will write a partial
|
||
amount of the string. <code>length</code> defaults to <code>buffer.length - offset</code>.
|
||
The method will not write partial characters.
|
||
|
||
</p>
|
||
<pre><code>buf = new Buffer(256);
|
||
len = buf.write('\u00bd + \u00bc = \u00be', 0);
|
||
console.log(len + " bytes: " + buf.toString('utf8', 0, len));</code></pre>
|
||
<p>The number of characters written (which may be different than the number of
|
||
bytes written) is set in <code>Buffer._charsWritten</code> and will be overwritten the
|
||
next time <code>buf.write()</code> is called.
|
||
|
||
|
||
</p>
|
||
<h3>buf.toString([encoding], [start], [end])<span><a class="mark" href="#all_buf_tostring_encoding_start_end" id="all_buf_tostring_encoding_start_end">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>encoding</code> String, Optional, Default: 'utf8'</li>
|
||
<li><code>start</code> Number, Optional, Default: 0</li>
|
||
<li><code>end</code> Number, Optional, Default: <code>buffer.length</code></li>
|
||
</div></ul>
|
||
<p>Decodes and returns a string from buffer data encoded with <code>encoding</code>
|
||
(defaults to <code>'utf8'</code>) beginning at <code>start</code> (defaults to <code>0</code>) and ending at
|
||
<code>end</code> (defaults to <code>buffer.length</code>).
|
||
|
||
</p>
|
||
<p>See <code>buffer.write()</code> example, above.
|
||
|
||
|
||
</p>
|
||
<h3>buf[index]<span><a class="mark" href="#all_buf_index" id="all_buf_index">#</a></span></h3>
|
||
<!--type=property-->
|
||
<!--name=[index]-->
|
||
|
||
<p>Get and set the octet at <code>index</code>. The values refer to individual bytes,
|
||
so the legal range is between <code>0x00</code> and <code>0xFF</code> hex or <code>0</code> and <code>255</code>.
|
||
|
||
</p>
|
||
<p>Example: copy an ASCII string into a buffer, one byte at a time:
|
||
|
||
</p>
|
||
<pre><code>str = "node.js";
|
||
buf = new Buffer(str.length);
|
||
|
||
for (var i = 0; i < str.length ; i++) {
|
||
buf[i] = str.charCodeAt(i);
|
||
}
|
||
|
||
console.log(buf);
|
||
|
||
// node.js</code></pre>
|
||
<h3>Class Method: Buffer.isBuffer(obj)<span><a class="mark" href="#all_class_method_buffer_isbuffer_obj" id="all_class_method_buffer_isbuffer_obj">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>obj</code> Object</li>
|
||
<li>Return: Boolean</li>
|
||
</div></ul>
|
||
<p>Tests if <code>obj</code> is a <code>Buffer</code>.
|
||
|
||
</p>
|
||
<h3>Class Method: Buffer.byteLength(string, [encoding])<span><a class="mark" href="#all_class_method_buffer_bytelength_string_encoding" id="all_class_method_buffer_bytelength_string_encoding">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>string</code> String</li>
|
||
<li><code>encoding</code> String, Optional, Default: 'utf8'</li>
|
||
<li>Return: Number</li>
|
||
</div></ul>
|
||
<p>Gives the actual byte length of a string. <code>encoding</code> defaults to <code>'utf8'</code>.
|
||
This is not the same as <code>String.prototype.length</code> since that returns the
|
||
number of <em>characters</em> in a string.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>str = '\u00bd + \u00bc = \u00be';
|
||
|
||
console.log(str + ": " + str.length + " characters, " +
|
||
Buffer.byteLength(str, 'utf8') + " bytes");
|
||
|
||
// ½ + ¼ = ¾: 9 characters, 12 bytes</code></pre>
|
||
<h3>Class Method: Buffer.concat(list, [totalLength])<span><a class="mark" href="#all_class_method_buffer_concat_list_totallength" id="all_class_method_buffer_concat_list_totallength">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>list</code> <span class="type">Array</span> List of Buffer objects to concat</li>
|
||
<li><code>totalLength</code> <span class="type">Number</span> Total length of the buffers when concatenated</li>
|
||
</div></ul>
|
||
<p>Returns a buffer which is the result of concatenating all the buffers in
|
||
the list together.
|
||
|
||
</p>
|
||
<p>If the list has no items, or if the totalLength is 0, then it returns a
|
||
zero-length buffer.
|
||
|
||
</p>
|
||
<p>If the list has exactly one item, then the first item of the list is
|
||
returned.
|
||
|
||
</p>
|
||
<p>If the list has more than one item, then a new Buffer is created.
|
||
|
||
</p>
|
||
<p>If totalLength is not provided, it is read from the buffers in the list.
|
||
However, this adds an additional loop to the function, so it is faster
|
||
to provide the length explicitly.
|
||
|
||
</p>
|
||
<h3>buf.length<span><a class="mark" href="#all_buf_length" id="all_buf_length">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li>Number</li>
|
||
</div></ul>
|
||
<p>The size of the buffer in bytes. Note that this is not necessarily the size
|
||
of the contents. <code>length</code> refers to the amount of memory allocated for the
|
||
buffer object. It does not change when the contents of the buffer are changed.
|
||
|
||
</p>
|
||
<pre><code>buf = new Buffer(1234);
|
||
|
||
console.log(buf.length);
|
||
buf.write("some string", 0, "ascii");
|
||
console.log(buf.length);
|
||
|
||
// 1234
|
||
// 1234</code></pre>
|
||
<h3>buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])<span><a class="mark" href="#all_buf_copy_targetbuffer_targetstart_sourcestart_sourceend" id="all_buf_copy_targetbuffer_targetstart_sourcestart_sourceend">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>targetBuffer</code> Buffer object - Buffer to copy into</li>
|
||
<li><code>targetStart</code> Number, Optional, Default: 0</li>
|
||
<li><code>sourceStart</code> Number, Optional, Default: 0</li>
|
||
<li><code>sourceEnd</code> Number, Optional, Default: <code>buffer.length</code></li>
|
||
</div></ul>
|
||
<p>Does copy between buffers. The source and target regions can be overlapped.
|
||
<code>targetStart</code> and <code>sourceStart</code> default to <code>0</code>.
|
||
<code>sourceEnd</code> defaults to <code>buffer.length</code>.
|
||
|
||
</p>
|
||
<p>Example: build two Buffers, then copy <code>buf1</code> from byte 16 through byte 19
|
||
into <code>buf2</code>, starting at the 8th byte in <code>buf2</code>.
|
||
|
||
</p>
|
||
<pre><code>buf1 = new Buffer(26);
|
||
buf2 = new Buffer(26);
|
||
|
||
for (var i = 0 ; i < 26 ; i++) {
|
||
buf1[i] = i + 97; // 97 is ASCII a
|
||
buf2[i] = 33; // ASCII !
|
||
}
|
||
|
||
buf1.copy(buf2, 8, 16, 20);
|
||
console.log(buf2.toString('ascii', 0, 25));
|
||
|
||
// !!!!!!!!qrst!!!!!!!!!!!!!</code></pre>
|
||
<h3>buf.slice([start], [end])<span><a class="mark" href="#all_buf_slice_start_end" id="all_buf_slice_start_end">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>start</code> Number, Optional, Default: 0</li>
|
||
<li><code>end</code> Number, Optional, Default: <code>buffer.length</code></li>
|
||
</div></ul>
|
||
<p>Returns a new buffer which references the same memory as the old, but offset
|
||
and cropped by the <code>start</code> (defaults to <code>0</code>) and <code>end</code> (defaults to
|
||
<code>buffer.length</code>) indexes.
|
||
|
||
</p>
|
||
<p><strong>Modifying the new buffer slice will modify memory in the original buffer!</strong>
|
||
|
||
</p>
|
||
<p>Example: build a Buffer with the ASCII alphabet, take a slice, then modify one
|
||
byte from the original Buffer.
|
||
|
||
</p>
|
||
<pre><code>var buf1 = new Buffer(26);
|
||
|
||
for (var i = 0 ; i < 26 ; i++) {
|
||
buf1[i] = i + 97; // 97 is ASCII a
|
||
}
|
||
|
||
var buf2 = buf1.slice(0, 3);
|
||
console.log(buf2.toString('ascii', 0, buf2.length));
|
||
buf1[0] = 33;
|
||
console.log(buf2.toString('ascii', 0, buf2.length));
|
||
|
||
// abc
|
||
// !bc</code></pre>
|
||
<h3>buf.readUInt8(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint8_offset_noassert" id="all_buf_readuint8_offset_noassert">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
<li>Return: Number</li>
|
||
</div></ul>
|
||
<p>Reads an unsigned 8 bit integer from the buffer at the specified offset.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
|
||
may be beyond the end of the buffer. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(4);
|
||
|
||
buf[0] = 0x3;
|
||
buf[1] = 0x4;
|
||
buf[2] = 0x23;
|
||
buf[3] = 0x42;
|
||
|
||
for (ii = 0; ii < buf.length; ii++) {
|
||
console.log(buf.readUInt8(ii));
|
||
}
|
||
|
||
// 0x3
|
||
// 0x4
|
||
// 0x23
|
||
// 0x42</code></pre>
|
||
<h3>buf.readUInt16LE(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint16le_offset_noassert" id="all_buf_readuint16le_offset_noassert">#</a></span></h3>
|
||
<h3>buf.readUInt16BE(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint16be_offset_noassert" id="all_buf_readuint16be_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
<li>Return: Number</li>
|
||
</ul>
|
||
<p>Reads an unsigned 16 bit integer from the buffer at the specified offset with
|
||
specified endian format.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
|
||
may be beyond the end of the buffer. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(4);
|
||
|
||
buf[0] = 0x3;
|
||
buf[1] = 0x4;
|
||
buf[2] = 0x23;
|
||
buf[3] = 0x42;
|
||
|
||
console.log(buf.readUInt16BE(0));
|
||
console.log(buf.readUInt16LE(0));
|
||
console.log(buf.readUInt16BE(1));
|
||
console.log(buf.readUInt16LE(1));
|
||
console.log(buf.readUInt16BE(2));
|
||
console.log(buf.readUInt16LE(2));
|
||
|
||
// 0x0304
|
||
// 0x0403
|
||
// 0x0423
|
||
// 0x2304
|
||
// 0x2342
|
||
// 0x4223</code></pre>
|
||
<h3>buf.readUInt32LE(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint32le_offset_noassert" id="all_buf_readuint32le_offset_noassert">#</a></span></h3>
|
||
<h3>buf.readUInt32BE(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint32be_offset_noassert" id="all_buf_readuint32be_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
<li>Return: Number</li>
|
||
</ul>
|
||
<p>Reads an unsigned 32 bit integer from the buffer at the specified offset with
|
||
specified endian format.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
|
||
may be beyond the end of the buffer. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(4);
|
||
|
||
buf[0] = 0x3;
|
||
buf[1] = 0x4;
|
||
buf[2] = 0x23;
|
||
buf[3] = 0x42;
|
||
|
||
console.log(buf.readUInt32BE(0));
|
||
console.log(buf.readUInt32LE(0));
|
||
|
||
// 0x03042342
|
||
// 0x42230403</code></pre>
|
||
<h3>buf.readInt8(offset, [noAssert])<span><a class="mark" href="#all_buf_readint8_offset_noassert" id="all_buf_readint8_offset_noassert">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
<li>Return: Number</li>
|
||
</div></ul>
|
||
<p>Reads a signed 8 bit integer from the buffer at the specified offset.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
|
||
may be beyond the end of the buffer. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Works as <code>buffer.readUInt8</code>, except buffer contents are treated as two's
|
||
complement signed values.
|
||
|
||
</p>
|
||
<h3>buf.readInt16LE(offset, [noAssert])<span><a class="mark" href="#all_buf_readint16le_offset_noassert" id="all_buf_readint16le_offset_noassert">#</a></span></h3>
|
||
<h3>buf.readInt16BE(offset, [noAssert])<span><a class="mark" href="#all_buf_readint16be_offset_noassert" id="all_buf_readint16be_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
<li>Return: Number</li>
|
||
</ul>
|
||
<p>Reads a signed 16 bit integer from the buffer at the specified offset with
|
||
specified endian format.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
|
||
may be beyond the end of the buffer. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Works as <code>buffer.readUInt16*</code>, except buffer contents are treated as two's
|
||
complement signed values.
|
||
|
||
</p>
|
||
<h3>buf.readInt32LE(offset, [noAssert])<span><a class="mark" href="#all_buf_readint32le_offset_noassert" id="all_buf_readint32le_offset_noassert">#</a></span></h3>
|
||
<h3>buf.readInt32BE(offset, [noAssert])<span><a class="mark" href="#all_buf_readint32be_offset_noassert" id="all_buf_readint32be_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
<li>Return: Number</li>
|
||
</ul>
|
||
<p>Reads a signed 32 bit integer from the buffer at the specified offset with
|
||
specified endian format.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
|
||
may be beyond the end of the buffer. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Works as <code>buffer.readUInt32*</code>, except buffer contents are treated as two's
|
||
complement signed values.
|
||
|
||
</p>
|
||
<h3>buf.readFloatLE(offset, [noAssert])<span><a class="mark" href="#all_buf_readfloatle_offset_noassert" id="all_buf_readfloatle_offset_noassert">#</a></span></h3>
|
||
<h3>buf.readFloatBE(offset, [noAssert])<span><a class="mark" href="#all_buf_readfloatbe_offset_noassert" id="all_buf_readfloatbe_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
<li>Return: Number</li>
|
||
</ul>
|
||
<p>Reads a 32 bit float from the buffer at the specified offset with specified
|
||
endian format.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
|
||
may be beyond the end of the buffer. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(4);
|
||
|
||
buf[0] = 0x00;
|
||
buf[1] = 0x00;
|
||
buf[2] = 0x80;
|
||
buf[3] = 0x3f;
|
||
|
||
console.log(buf.readFloatLE(0));
|
||
|
||
// 0x01</code></pre>
|
||
<h3>buf.readDoubleLE(offset, [noAssert])<span><a class="mark" href="#all_buf_readdoublele_offset_noassert" id="all_buf_readdoublele_offset_noassert">#</a></span></h3>
|
||
<h3>buf.readDoubleBE(offset, [noAssert])<span><a class="mark" href="#all_buf_readdoublebe_offset_noassert" id="all_buf_readdoublebe_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
<li>Return: Number</li>
|
||
</ul>
|
||
<p>Reads a 64 bit double from the buffer at the specified offset with specified
|
||
endian format.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
|
||
may be beyond the end of the buffer. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(8);
|
||
|
||
buf[0] = 0x55;
|
||
buf[1] = 0x55;
|
||
buf[2] = 0x55;
|
||
buf[3] = 0x55;
|
||
buf[4] = 0x55;
|
||
buf[5] = 0x55;
|
||
buf[6] = 0xd5;
|
||
buf[7] = 0x3f;
|
||
|
||
console.log(buf.readDoubleLE(0));
|
||
|
||
// 0.3333333333333333</code></pre>
|
||
<h3>buf.writeUInt8(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint8_value_offset_noassert" id="all_buf_writeuint8_value_offset_noassert">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>value</code> Number</li>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
</div></ul>
|
||
<p>Writes <code>value</code> to the buffer at the specified offset. Note, <code>value</code> must be a
|
||
valid unsigned 8 bit integer.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
|
||
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
|
||
beyond the end of the buffer leading to the values being silently dropped. This
|
||
should not be used unless you are certain of correctness. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(4);
|
||
buf.writeUInt8(0x3, 0);
|
||
buf.writeUInt8(0x4, 1);
|
||
buf.writeUInt8(0x23, 2);
|
||
buf.writeUInt8(0x42, 3);
|
||
|
||
console.log(buf);
|
||
|
||
// <Buffer 03 04 23 42></code></pre>
|
||
<h3>buf.writeUInt16LE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint16le_value_offset_noassert" id="all_buf_writeuint16le_value_offset_noassert">#</a></span></h3>
|
||
<h3>buf.writeUInt16BE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint16be_value_offset_noassert" id="all_buf_writeuint16be_value_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>value</code> Number</li>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
</ul>
|
||
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
|
||
format. Note, <code>value</code> must be a valid unsigned 16 bit integer.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
|
||
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
|
||
beyond the end of the buffer leading to the values being silently dropped. This
|
||
should not be used unless you are certain of correctness. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(4);
|
||
buf.writeUInt16BE(0xdead, 0);
|
||
buf.writeUInt16BE(0xbeef, 2);
|
||
|
||
console.log(buf);
|
||
|
||
buf.writeUInt16LE(0xdead, 0);
|
||
buf.writeUInt16LE(0xbeef, 2);
|
||
|
||
console.log(buf);
|
||
|
||
// <Buffer de ad be ef>
|
||
// <Buffer ad de ef be></code></pre>
|
||
<h3>buf.writeUInt32LE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint32le_value_offset_noassert" id="all_buf_writeuint32le_value_offset_noassert">#</a></span></h3>
|
||
<h3>buf.writeUInt32BE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint32be_value_offset_noassert" id="all_buf_writeuint32be_value_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>value</code> Number</li>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
</ul>
|
||
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
|
||
format. Note, <code>value</code> must be a valid unsigned 32 bit integer.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
|
||
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
|
||
beyond the end of the buffer leading to the values being silently dropped. This
|
||
should not be used unless you are certain of correctness. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(4);
|
||
buf.writeUInt32BE(0xfeedface, 0);
|
||
|
||
console.log(buf);
|
||
|
||
buf.writeUInt32LE(0xfeedface, 0);
|
||
|
||
console.log(buf);
|
||
|
||
// <Buffer fe ed fa ce>
|
||
// <Buffer ce fa ed fe></code></pre>
|
||
<h3>buf.writeInt8(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint8_value_offset_noassert" id="all_buf_writeint8_value_offset_noassert">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>value</code> Number</li>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
</div></ul>
|
||
<p>Writes <code>value</code> to the buffer at the specified offset. Note, <code>value</code> must be a
|
||
valid signed 8 bit integer.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
|
||
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
|
||
beyond the end of the buffer leading to the values being silently dropped. This
|
||
should not be used unless you are certain of correctness. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Works as <code>buffer.writeUInt8</code>, except value is written out as a two's complement
|
||
signed integer into <code>buffer</code>.
|
||
|
||
</p>
|
||
<h3>buf.writeInt16LE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint16le_value_offset_noassert" id="all_buf_writeint16le_value_offset_noassert">#</a></span></h3>
|
||
<h3>buf.writeInt16BE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint16be_value_offset_noassert" id="all_buf_writeint16be_value_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>value</code> Number</li>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
</ul>
|
||
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
|
||
format. Note, <code>value</code> must be a valid signed 16 bit integer.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
|
||
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
|
||
beyond the end of the buffer leading to the values being silently dropped. This
|
||
should not be used unless you are certain of correctness. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Works as <code>buffer.writeUInt16*</code>, except value is written out as a two's
|
||
complement signed integer into <code>buffer</code>.
|
||
|
||
</p>
|
||
<h3>buf.writeInt32LE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint32le_value_offset_noassert" id="all_buf_writeint32le_value_offset_noassert">#</a></span></h3>
|
||
<h3>buf.writeInt32BE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint32be_value_offset_noassert" id="all_buf_writeint32be_value_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>value</code> Number</li>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
</ul>
|
||
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
|
||
format. Note, <code>value</code> must be a valid signed 32 bit integer.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
|
||
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
|
||
beyond the end of the buffer leading to the values being silently dropped. This
|
||
should not be used unless you are certain of correctness. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Works as <code>buffer.writeUInt32*</code>, except value is written out as a two's
|
||
complement signed integer into <code>buffer</code>.
|
||
|
||
</p>
|
||
<h3>buf.writeFloatLE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writefloatle_value_offset_noassert" id="all_buf_writefloatle_value_offset_noassert">#</a></span></h3>
|
||
<h3>buf.writeFloatBE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writefloatbe_value_offset_noassert" id="all_buf_writefloatbe_value_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>value</code> Number</li>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
</ul>
|
||
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
|
||
format. Note, <code>value</code> must be a valid 32 bit float.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
|
||
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
|
||
beyond the end of the buffer leading to the values being silently dropped. This
|
||
should not be used unless you are certain of correctness. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(4);
|
||
buf.writeFloatBE(0xcafebabe, 0);
|
||
|
||
console.log(buf);
|
||
|
||
buf.writeFloatLE(0xcafebabe, 0);
|
||
|
||
console.log(buf);
|
||
|
||
// <Buffer 4f 4a fe bb>
|
||
// <Buffer bb fe 4a 4f></code></pre>
|
||
<h3>buf.writeDoubleLE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writedoublele_value_offset_noassert" id="all_buf_writedoublele_value_offset_noassert">#</a></span></h3>
|
||
<h3>buf.writeDoubleBE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writedoublebe_value_offset_noassert" id="all_buf_writedoublebe_value_offset_noassert">#</a></span></h3>
|
||
<ul>
|
||
<li><code>value</code> Number</li>
|
||
<li><code>offset</code> Number</li>
|
||
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
|
||
</ul>
|
||
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
|
||
format. Note, <code>value</code> must be a valid 64 bit double.
|
||
|
||
</p>
|
||
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
|
||
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
|
||
beyond the end of the buffer leading to the values being silently dropped. This
|
||
should not be used unless you are certain of correctness. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var buf = new Buffer(8);
|
||
buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
|
||
|
||
console.log(buf);
|
||
|
||
buf.writeDoubleLE(0xdeadbeefcafebabe, 0);
|
||
|
||
console.log(buf);
|
||
|
||
// <Buffer 43 eb d5 b7 dd f9 5f d7>
|
||
// <Buffer d7 5f f9 dd b7 d5 eb 43></code></pre>
|
||
<h3>buf.fill(value, [offset], [end])<span><a class="mark" href="#all_buf_fill_value_offset_end" id="all_buf_fill_value_offset_end">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>value</code></li>
|
||
<li><code>offset</code> Number, Optional</li>
|
||
<li><code>end</code> Number, Optional</li>
|
||
</div></ul>
|
||
<p>Fills the buffer with the specified value. If the <code>offset</code> (defaults to <code>0</code>)
|
||
and <code>end</code> (defaults to <code>buffer.length</code>) are not given it will fill the entire
|
||
buffer.
|
||
|
||
</p>
|
||
<pre><code>var b = new Buffer(50);
|
||
b.fill("h");</code></pre>
|
||
<h2>buffer.INSPECT_MAX_BYTES<span><a class="mark" href="#all_buffer_inspect_max_bytes" id="all_buffer_inspect_max_bytes">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li>Number, Default: 50</li>
|
||
</div></ul>
|
||
<p>How many bytes will be returned when <code>buffer.inspect()</code> is called. This can
|
||
be overridden by user modules.
|
||
|
||
</p>
|
||
<p>Note that this is a property on the buffer module returned by
|
||
<code>require('buffer')</code>, not on the Buffer global, or a buffer instance.
|
||
|
||
</p>
|
||
<h2>Class: SlowBuffer<span><a class="mark" href="#all_class_slowbuffer" id="all_class_slowbuffer">#</a></span></h2>
|
||
<p>This class is primarily for internal use. JavaScript programs should
|
||
use Buffer instead of using SlowBuffer.
|
||
|
||
</p>
|
||
<p>In order to avoid the overhead of allocating many C++ Buffer objects for
|
||
small blocks of memory in the lifetime of a server, Node allocates memory
|
||
in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it
|
||
will be backed by a parent SlowBuffer object. If it is larger than this,
|
||
then Node will allocate a SlowBuffer slab for it directly.
|
||
|
||
</p>
|
||
<h1>Stream<span><a class="mark" href="#all_stream" id="all_stream">#</a></span></h1>
|
||
<pre><code>Stability: 2 - Unstable</code></pre>
|
||
<p>A stream is an abstract interface implemented by various objects in
|
||
Node. For example a request to an HTTP server is a stream, as is
|
||
stdout. Streams are readable, writable, or both. All streams are
|
||
instances of <a href="events.html#events_class_events_eventemitter">EventEmitter</a>
|
||
|
||
</p>
|
||
<p>You can load up the Stream base class by doing <code>require('stream')</code>.
|
||
|
||
</p>
|
||
<h2>Readable Stream<span><a class="mark" href="#all_readable_stream" id="all_readable_stream">#</a></span></h2>
|
||
<!--type=class-->
|
||
|
||
<p>A <code>Readable Stream</code> has the following methods, members, and events.
|
||
|
||
</p>
|
||
<h3>Event: 'data'<span><a class="mark" href="#all_event_data" id="all_event_data">#</a></span></h3>
|
||
<p><code>function (data) { }</code>
|
||
|
||
</p>
|
||
<p>The <code>'data'</code> event emits either a <code>Buffer</code> (by default) or a string if
|
||
<code>setEncoding()</code> was used.
|
||
|
||
</p>
|
||
<p>Note that the <strong>data will be lost</strong> if there is no listener when a
|
||
<code>Readable Stream</code> emits a <code>'data'</code> event.
|
||
|
||
</p>
|
||
<h3>Event: 'end'<span><a class="mark" href="#all_event_end" id="all_event_end">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Emitted when the stream has received an EOF (FIN in TCP terminology).
|
||
Indicates that no more <code>'data'</code> events will happen. If the stream is
|
||
also writable, it may be possible to continue writing.
|
||
|
||
</p>
|
||
<h3>Event: 'error'<span><a class="mark" href="#all_event_error" id="all_event_error">#</a></span></h3>
|
||
<p><code>function (exception) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted if there was an error receiving data.
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close" id="all_event_close">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Emitted when the underlying resource (for example, the backing file
|
||
descriptor) has been closed. Not all streams will emit this.
|
||
|
||
</p>
|
||
<h3>stream.readable<span><a class="mark" href="#all_stream_readable" id="all_stream_readable">#</a></span></h3>
|
||
<p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an
|
||
<code>'error'</code> occurred, the stream came to an <code>'end'</code>, or <code>destroy()</code> was
|
||
called.
|
||
|
||
</p>
|
||
<h3>stream.setEncoding([encoding])<span><a class="mark" href="#all_stream_setencoding_encoding" id="all_stream_setencoding_encoding">#</a></span></h3>
|
||
<p>Makes the <code>'data'</code> event emit a string instead of a <code>Buffer</code>. <code>encoding</code>
|
||
can be <code>'utf8'</code>, <code>'utf16le'</code> (<code>'ucs2'</code>), <code>'ascii'</code>, or <code>'hex'</code>. Defaults
|
||
to <code>'utf8'</code>.
|
||
|
||
</p>
|
||
<h3>stream.pause()<span><a class="mark" href="#all_stream_pause" id="all_stream_pause">#</a></span></h3>
|
||
<p>Issues an advisory signal to the underlying communication layer,
|
||
requesting that no further data be sent until <code>resume()</code> is called.
|
||
|
||
</p>
|
||
<p>Note that, due to the advisory nature, certain streams will not be
|
||
paused immediately, and so <code>'data'</code> events may be emitted for some
|
||
indeterminate period of time even after <code>pause()</code> is called. You may
|
||
wish to buffer such <code>'data'</code> events.
|
||
|
||
</p>
|
||
<h3>stream.resume()<span><a class="mark" href="#all_stream_resume" id="all_stream_resume">#</a></span></h3>
|
||
<p>Resumes the incoming <code>'data'</code> events after a <code>pause()</code>.
|
||
|
||
</p>
|
||
<h3>stream.destroy()<span><a class="mark" href="#all_stream_destroy" id="all_stream_destroy">#</a></span></h3>
|
||
<p>Closes the underlying file descriptor. Stream is no longer <code>writable</code>
|
||
nor <code>readable</code>. The stream will not emit any more 'data', or 'end'
|
||
events. Any queued write data will not be sent. The stream should emit
|
||
'close' event once its resources have been disposed of.
|
||
|
||
|
||
</p>
|
||
<h3>stream.pipe(destination, [options])<span><a class="mark" href="#all_stream_pipe_destination_options" id="all_stream_pipe_destination_options">#</a></span></h3>
|
||
<p>This is a <code>Stream.prototype</code> method available on all <code>Stream</code>s.
|
||
|
||
</p>
|
||
<p>Connects this read stream to <code>destination</code> WriteStream. Incoming data on
|
||
this stream gets written to <code>destination</code>. The destination and source
|
||
streams are kept in sync by pausing and resuming as necessary.
|
||
|
||
</p>
|
||
<p>This function returns the <code>destination</code> stream.
|
||
|
||
</p>
|
||
<p>Emulating the Unix <code>cat</code> command:
|
||
|
||
</p>
|
||
<pre><code>process.stdin.resume(); process.stdin.pipe(process.stdout);</code></pre>
|
||
<p>By default <code>end()</code> is called on the destination when the source stream
|
||
emits <code>end</code>, so that <code>destination</code> is no longer writable. Pass <code>{ end:
|
||
false }</code> as <code>options</code> to keep the destination stream open.
|
||
|
||
</p>
|
||
<p>This keeps <code>process.stdout</code> open so that "Goodbye" can be written at the
|
||
end.
|
||
|
||
</p>
|
||
<pre><code>process.stdin.resume();
|
||
|
||
process.stdin.pipe(process.stdout, { end: false });
|
||
|
||
process.stdin.on("end", function() {
|
||
process.stdout.write("Goodbye\n"); });</code></pre>
|
||
<h2>Writable Stream<span><a class="mark" href="#all_writable_stream" id="all_writable_stream">#</a></span></h2>
|
||
<!--type=class-->
|
||
|
||
<p>A <code>Writable Stream</code> has the following methods, members, and events.
|
||
|
||
</p>
|
||
<h3>Event: 'drain'<span><a class="mark" href="#all_event_drain" id="all_event_drain">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Emitted when the stream's write queue empties and it's safe to write without
|
||
buffering again. Listen for it when <code>stream.write()</code> returns <code>false</code>.
|
||
|
||
</p>
|
||
<p>The <code>'drain'</code> event can happen at <em>any</em> time, regardless of whether or not
|
||
<code>stream.write()</code> has previously returned <code>false</code>. To avoid receiving unwanted
|
||
<code>'drain'</code> events, listen using <code>stream.once()</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'error'<span><a class="mark" href="#all_event_error_1" id="all_event_error_1">#</a></span></h3>
|
||
<p><code>function (exception) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted on error with the exception <code>exception</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_1" id="all_event_close_1">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Emitted when the underlying file descriptor has been closed.
|
||
|
||
</p>
|
||
<h3>Event: 'pipe'<span><a class="mark" href="#all_event_pipe" id="all_event_pipe">#</a></span></h3>
|
||
<p><code>function (src) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted when the stream is passed to a readable stream's pipe method.
|
||
|
||
</p>
|
||
<h3>stream.writable<span><a class="mark" href="#all_stream_writable" id="all_stream_writable">#</a></span></h3>
|
||
<p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an
|
||
<code>'error'</code> occurred or <code>end()</code> / <code>destroy()</code> was called.
|
||
|
||
</p>
|
||
<h3>stream.write(string, [encoding])<span><a class="mark" href="#all_stream_write_string_encoding" id="all_stream_write_string_encoding">#</a></span></h3>
|
||
<p>Writes <code>string</code> with the given <code>encoding</code> to the stream. Returns <code>true</code>
|
||
if the string has been flushed to the kernel buffer. Returns <code>false</code> to
|
||
indicate that the kernel buffer is full, and the data will be sent out
|
||
in the future. The <code>'drain'</code> event will indicate when the kernel buffer
|
||
is empty again. The <code>encoding</code> defaults to <code>'utf8'</code>.
|
||
|
||
</p>
|
||
<h3>stream.write(buffer)<span><a class="mark" href="#all_stream_write_buffer" id="all_stream_write_buffer">#</a></span></h3>
|
||
<p>Same as the above except with a raw buffer.
|
||
|
||
</p>
|
||
<h3>stream.end()<span><a class="mark" href="#all_stream_end" id="all_stream_end">#</a></span></h3>
|
||
<p>Terminates the stream with EOF or FIN. This call will allow queued
|
||
write data to be sent before closing the stream.
|
||
|
||
</p>
|
||
<h3>stream.end(string, encoding)<span><a class="mark" href="#all_stream_end_string_encoding" id="all_stream_end_string_encoding">#</a></span></h3>
|
||
<p>Sends <code>string</code> with the given <code>encoding</code> and terminates the stream with
|
||
EOF or FIN. This is useful to reduce the number of packets sent.
|
||
|
||
</p>
|
||
<h3>stream.end(buffer)<span><a class="mark" href="#all_stream_end_buffer" id="all_stream_end_buffer">#</a></span></h3>
|
||
<p>Same as above but with a <code>buffer</code>.
|
||
|
||
</p>
|
||
<h3>stream.destroy()<span><a class="mark" href="#all_stream_destroy_1" id="all_stream_destroy_1">#</a></span></h3>
|
||
<p>Closes the underlying file descriptor. Stream is no longer <code>writable</code>
|
||
nor <code>readable</code>. The stream will not emit any more 'data', or 'end'
|
||
events. Any queued write data will not be sent. The stream should emit
|
||
'close' event once its resources have been disposed of.
|
||
|
||
</p>
|
||
<h3>stream.destroySoon()<span><a class="mark" href="#all_stream_destroysoon" id="all_stream_destroysoon">#</a></span></h3>
|
||
<p>After the write queue is drained, close the file descriptor.
|
||
<code>destroySoon()</code> can still destroy straight away, as long as there is no
|
||
data left in the queue for writes.
|
||
|
||
</p>
|
||
<h1>Crypto<span><a class="mark" href="#all_crypto" id="all_crypto">#</a></span></h1>
|
||
<pre><code>Stability: 2 - Unstable; API changes are being discussed for
|
||
future versions. Breaking changes will be minimized. See below.</code></pre>
|
||
<p>Use <code>require('crypto')</code> to access this module.
|
||
|
||
</p>
|
||
<p>The crypto module requires OpenSSL to be available on the underlying platform.
|
||
It offers a way of encapsulating secure credentials to be used as part
|
||
of a secure HTTPS net or http connection.
|
||
|
||
</p>
|
||
<p>It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.
|
||
|
||
</p>
|
||
<h2>crypto.createCredentials(details)<span><a class="mark" href="#all_crypto_createcredentials_details" id="all_crypto_createcredentials_details">#</a></span></h2>
|
||
<p>Creates a credentials object, with the optional details being a dictionary with keys:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>pfx</code> : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates</li>
|
||
<li><code>key</code> : A string holding the PEM encoded private key</li>
|
||
<li><code>passphrase</code> : A string of passphrase for the private key or pfx</li>
|
||
<li><code>cert</code> : A string holding the PEM encoded certificate</li>
|
||
<li><code>ca</code> : Either a string or list of strings of PEM encoded CA certificates to trust.</li>
|
||
<li><code>crl</code> : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)</li>
|
||
<li><code>ciphers</code>: A string describing the ciphers to use or exclude. Consult
|
||
<a href="http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT</a> for details
|
||
on the format.</li>
|
||
</ul>
|
||
<p>If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in
|
||
</p>
|
||
<p><a href="http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt">http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt</a>.
|
||
|
||
|
||
</p>
|
||
<h2>crypto.createHash(algorithm)<span><a class="mark" href="#all_crypto_createhash_algorithm" id="all_crypto_createhash_algorithm">#</a></span></h2>
|
||
<p>Creates and returns a hash object, a cryptographic hash with the given algorithm
|
||
which can be used to generate hash digests.
|
||
|
||
</p>
|
||
<p><code>algorithm</code> is dependent on the available algorithms supported by the version
|
||
of OpenSSL on the platform. Examples are <code>'sha1'</code>, <code>'md5'</code>, <code>'sha256'</code>, <code>'sha512'</code>, etc.
|
||
On recent releases, <code>openssl list-message-digest-algorithms</code> will display the available digest algorithms.
|
||
|
||
</p>
|
||
<p>Example: this program that takes the sha1 sum of a file
|
||
|
||
</p>
|
||
<pre><code>var filename = process.argv[2];
|
||
var crypto = require('crypto');
|
||
var fs = require('fs');
|
||
|
||
var shasum = crypto.createHash('sha1');
|
||
|
||
var s = fs.ReadStream(filename);
|
||
s.on('data', function(d) {
|
||
shasum.update(d);
|
||
});
|
||
|
||
s.on('end', function() {
|
||
var d = shasum.digest('hex');
|
||
console.log(d + ' ' + filename);
|
||
});</code></pre>
|
||
<h2>Class: Hash<span><a class="mark" href="#all_class_hash" id="all_class_hash">#</a></span></h2>
|
||
<p>The class for creating hash digests of data.
|
||
|
||
</p>
|
||
<p>Returned by <code>crypto.createHash</code>.
|
||
|
||
</p>
|
||
<h3>hash.update(data, [input_encoding])<span><a class="mark" href="#all_hash_update_data_input_encoding" id="all_hash_update_data_input_encoding">#</a></span></h3>
|
||
<p>Updates the hash content with the given <code>data</code>, the encoding of which is given
|
||
in <code>input_encoding</code> and can be <code>'utf8'</code>, <code>'ascii'</code> or <code>'binary'</code>.
|
||
Defaults to <code>'binary'</code>.
|
||
This can be called many times with new data as it is streamed.
|
||
|
||
</p>
|
||
<h3>hash.digest([encoding])<span><a class="mark" href="#all_hash_digest_encoding" id="all_hash_digest_encoding">#</a></span></h3>
|
||
<p>Calculates the digest of all of the passed data to be hashed.
|
||
The <code>encoding</code> can be <code>'hex'</code>, <code>'binary'</code> or <code>'base64'</code>.
|
||
Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<p>Note: <code>hash</code> object can not be used after <code>digest()</code> method been called.
|
||
|
||
|
||
</p>
|
||
<h2>crypto.createHmac(algorithm, key)<span><a class="mark" href="#all_crypto_createhmac_algorithm_key" id="all_crypto_createhmac_algorithm_key">#</a></span></h2>
|
||
<p>Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
|
||
|
||
</p>
|
||
<p><code>algorithm</code> is dependent on the available algorithms supported by OpenSSL - see createHash above.
|
||
<code>key</code> is the hmac key to be used.
|
||
|
||
</p>
|
||
<h2>Class: Hmac<span><a class="mark" href="#all_class_hmac" id="all_class_hmac">#</a></span></h2>
|
||
<p>Class for creating cryptographic hmac content.
|
||
|
||
</p>
|
||
<p>Returned by <code>crypto.createHmac</code>.
|
||
|
||
</p>
|
||
<h3>hmac.update(data)<span><a class="mark" href="#all_hmac_update_data" id="all_hmac_update_data">#</a></span></h3>
|
||
<p>Update the hmac content with the given <code>data</code>.
|
||
This can be called many times with new data as it is streamed.
|
||
|
||
</p>
|
||
<h3>hmac.digest([encoding])<span><a class="mark" href="#all_hmac_digest_encoding" id="all_hmac_digest_encoding">#</a></span></h3>
|
||
<p>Calculates the digest of all of the passed data to the hmac.
|
||
The <code>encoding</code> can be <code>'hex'</code>, <code>'binary'</code> or <code>'base64'</code>.
|
||
Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<p>Note: <code>hmac</code> object can not be used after <code>digest()</code> method been called.
|
||
|
||
|
||
</p>
|
||
<h2>crypto.createCipher(algorithm, password)<span><a class="mark" href="#all_crypto_createcipher_algorithm_password" id="all_crypto_createcipher_algorithm_password">#</a></span></h2>
|
||
<p>Creates and returns a cipher object, with the given algorithm and password.
|
||
|
||
</p>
|
||
<p><code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc.
|
||
On recent releases, <code>openssl list-cipher-algorithms</code> will display the
|
||
available cipher algorithms.
|
||
<code>password</code> is used to derive key and IV, which must be a <code>'binary'</code> encoded
|
||
string or a <a href="buffer.html">buffer</a>.
|
||
|
||
</p>
|
||
<h2>crypto.createCipheriv(algorithm, key, iv)<span><a class="mark" href="#all_crypto_createcipheriv_algorithm_key_iv" id="all_crypto_createcipheriv_algorithm_key_iv">#</a></span></h2>
|
||
<p>Creates and returns a cipher object, with the given algorithm, key and iv.
|
||
|
||
</p>
|
||
<p><code>algorithm</code> is the same as the argument to <code>createCipher()</code>.
|
||
<code>key</code> is the raw key used by the algorithm.
|
||
<code>iv</code> is an <a href="http://en.wikipedia.org/wiki/Initialization_vector">initialization
|
||
vector</a>.
|
||
|
||
</p>
|
||
<p><code>key</code> and <code>iv</code> must be <code>'binary'</code> encoded strings or <a href="buffer.html">buffers</a>.
|
||
|
||
</p>
|
||
<h2>Class: Cipher<span><a class="mark" href="#all_class_cipher" id="all_class_cipher">#</a></span></h2>
|
||
<p>Class for encrypting data.
|
||
|
||
</p>
|
||
<p>Returned by <code>crypto.createCipher</code> and <code>crypto.createCipheriv</code>.
|
||
|
||
</p>
|
||
<h3>cipher.update(data, [input_encoding], [output_encoding])<span><a class="mark" href="#all_cipher_update_data_input_encoding_output_encoding" id="all_cipher_update_data_input_encoding_output_encoding">#</a></span></h3>
|
||
<p>Updates the cipher with <code>data</code>, the encoding of which is given in
|
||
<code>input_encoding</code> and can be <code>'utf8'</code>, <code>'ascii'</code> or <code>'binary'</code>.
|
||
Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<p>The <code>output_encoding</code> specifies the output format of the enciphered data,
|
||
and can be <code>'binary'</code>, <code>'base64'</code> or <code>'hex'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<p>Returns the enciphered contents, and can be called many times with new data as it is streamed.
|
||
|
||
</p>
|
||
<h3>cipher.final([output_encoding])<span><a class="mark" href="#all_cipher_final_output_encoding" id="all_cipher_final_output_encoding">#</a></span></h3>
|
||
<p>Returns any remaining enciphered contents, with <code>output_encoding</code> being one of:
|
||
<code>'binary'</code>, <code>'base64'</code> or <code>'hex'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<p>Note: <code>cipher</code> object can not be used after <code>final()</code> method been called.
|
||
|
||
</p>
|
||
<h3>cipher.setAutoPadding(auto_padding=true)<span><a class="mark" href="#all_cipher_setautopadding_auto_padding_true" id="all_cipher_setautopadding_auto_padding_true">#</a></span></h3>
|
||
<p>You can disable automatic padding of the input data to block size. If <code>auto_padding</code> is false,
|
||
the length of the entire input data must be a multiple of the cipher's block size or <code>final</code> will fail.
|
||
Useful for non-standard padding, e.g. using <code>0x0</code> instead of PKCS padding. You must call this before <code>cipher.final</code>.
|
||
|
||
|
||
</p>
|
||
<h2>crypto.createDecipher(algorithm, password)<span><a class="mark" href="#all_crypto_createdecipher_algorithm_password" id="all_crypto_createdecipher_algorithm_password">#</a></span></h2>
|
||
<p>Creates and returns a decipher object, with the given algorithm and key.
|
||
This is the mirror of the <a href="#crypto_crypto_createcipher_algorithm_password">createCipher()</a> above.
|
||
|
||
</p>
|
||
<h2>crypto.createDecipheriv(algorithm, key, iv)<span><a class="mark" href="#all_crypto_createdecipheriv_algorithm_key_iv" id="all_crypto_createdecipheriv_algorithm_key_iv">#</a></span></h2>
|
||
<p>Creates and returns a decipher object, with the given algorithm, key and iv.
|
||
This is the mirror of the <a href="#crypto_crypto_createcipheriv_algorithm_key_iv">createCipheriv()</a> above.
|
||
|
||
</p>
|
||
<h2>Class: Decipher<span><a class="mark" href="#all_class_decipher" id="all_class_decipher">#</a></span></h2>
|
||
<p>Class for decrypting data.
|
||
|
||
</p>
|
||
<p>Returned by <code>crypto.createDecipher</code> and <code>crypto.createDecipheriv</code>.
|
||
|
||
</p>
|
||
<h3>decipher.update(data, [input_encoding], [output_encoding])<span><a class="mark" href="#all_decipher_update_data_input_encoding_output_encoding" id="all_decipher_update_data_input_encoding_output_encoding">#</a></span></h3>
|
||
<p>Updates the decipher with <code>data</code>, which is encoded in <code>'binary'</code>, <code>'base64'</code>
|
||
or <code>'hex'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<p>The <code>output_decoding</code> specifies in what format to return the deciphered
|
||
plaintext: <code>'binary'</code>, <code>'ascii'</code> or <code>'utf8'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<h3>decipher.final([output_encoding])<span><a class="mark" href="#all_decipher_final_output_encoding" id="all_decipher_final_output_encoding">#</a></span></h3>
|
||
<p>Returns any remaining plaintext which is deciphered,
|
||
with <code>output_encoding</code> being one of: <code>'binary'</code>, <code>'ascii'</code> or <code>'utf8'</code>.
|
||
Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<p>Note: <code>decipher</code> object can not be used after <code>final()</code> method been called.
|
||
|
||
</p>
|
||
<h3>decipher.setAutoPadding(auto_padding=true)<span><a class="mark" href="#all_decipher_setautopadding_auto_padding_true" id="all_decipher_setautopadding_auto_padding_true">#</a></span></h3>
|
||
<p>You can disable auto padding if the data has been encrypted without standard block padding to prevent
|
||
<code>decipher.final</code> from checking and removing it. Can only work if the input data's length is a multiple of the
|
||
ciphers block size. You must call this before streaming data to <code>decipher.update</code>.
|
||
|
||
</p>
|
||
<h2>crypto.createSign(algorithm)<span><a class="mark" href="#all_crypto_createsign_algorithm" id="all_crypto_createsign_algorithm">#</a></span></h2>
|
||
<p>Creates and returns a signing object, with the given algorithm.
|
||
On recent OpenSSL releases, <code>openssl list-public-key-algorithms</code> will display
|
||
the available signing algorithms. Examples are <code>'RSA-SHA256'</code>.
|
||
|
||
</p>
|
||
<h2>Class: Signer<span><a class="mark" href="#all_class_signer" id="all_class_signer">#</a></span></h2>
|
||
<p>Class for generating signatures.
|
||
|
||
</p>
|
||
<p>Returned by <code>crypto.createSign</code>.
|
||
|
||
</p>
|
||
<h3>signer.update(data)<span><a class="mark" href="#all_signer_update_data" id="all_signer_update_data">#</a></span></h3>
|
||
<p>Updates the signer object with data.
|
||
This can be called many times with new data as it is streamed.
|
||
|
||
</p>
|
||
<h3>signer.sign(private_key, [output_format])<span><a class="mark" href="#all_signer_sign_private_key_output_format" id="all_signer_sign_private_key_output_format">#</a></span></h3>
|
||
<p>Calculates the signature on all the updated data passed through the signer.
|
||
<code>private_key</code> is a string containing the PEM encoded private key for signing.
|
||
|
||
</p>
|
||
<p>Returns the signature in <code>output_format</code> which can be <code>'binary'</code>, <code>'hex'</code> or
|
||
<code>'base64'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<p>Note: <code>signer</code> object can not be used after <code>sign()</code> method been called.
|
||
|
||
</p>
|
||
<h2>crypto.createVerify(algorithm)<span><a class="mark" href="#all_crypto_createverify_algorithm" id="all_crypto_createverify_algorithm">#</a></span></h2>
|
||
<p>Creates and returns a verification object, with the given algorithm.
|
||
This is the mirror of the signing object above.
|
||
|
||
</p>
|
||
<h2>Class: Verify<span><a class="mark" href="#all_class_verify" id="all_class_verify">#</a></span></h2>
|
||
<p>Class for verifying signatures.
|
||
|
||
</p>
|
||
<p>Returned by <code>crypto.createVerify</code>.
|
||
|
||
</p>
|
||
<h3>verifier.update(data)<span><a class="mark" href="#all_verifier_update_data" id="all_verifier_update_data">#</a></span></h3>
|
||
<p>Updates the verifier object with data.
|
||
This can be called many times with new data as it is streamed.
|
||
|
||
</p>
|
||
<h3>verifier.verify(object, signature, [signature_format])<span><a class="mark" href="#all_verifier_verify_object_signature_signature_format" id="all_verifier_verify_object_signature_signature_format">#</a></span></h3>
|
||
<p>Verifies the signed data by using the <code>object</code> and <code>signature</code>. <code>object</code> is a
|
||
string containing a PEM encoded object, which can be one of RSA public key,
|
||
DSA public key, or X.509 certificate. <code>signature</code> is the previously calculated
|
||
signature for the data, in the <code>signature_format</code> which can be <code>'binary'</code>,
|
||
<code>'hex'</code> or <code>'base64'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<p>Returns true or false depending on the validity of the signature for the data and public key.
|
||
|
||
</p>
|
||
<p>Note: <code>verifier</code> object can not be used after <code>verify()</code> method been called.
|
||
|
||
</p>
|
||
<h2>crypto.createDiffieHellman(prime_length)<span><a class="mark" href="#all_crypto_creatediffiehellman_prime_length" id="all_crypto_creatediffiehellman_prime_length">#</a></span></h2>
|
||
<p>Creates a Diffie-Hellman key exchange object and generates a prime of the
|
||
given bit length. The generator used is <code>2</code>.
|
||
|
||
</p>
|
||
<h2>crypto.createDiffieHellman(prime, [encoding])<span><a class="mark" href="#all_crypto_creatediffiehellman_prime_encoding" id="all_crypto_creatediffiehellman_prime_encoding">#</a></span></h2>
|
||
<p>Creates a Diffie-Hellman key exchange object using the supplied prime. The
|
||
generator used is <code>2</code>. Encoding can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>.
|
||
Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<h2>Class: DiffieHellman<span><a class="mark" href="#all_class_diffiehellman" id="all_class_diffiehellman">#</a></span></h2>
|
||
<p>The class for creating Diffie-Hellman key exchanges.
|
||
|
||
</p>
|
||
<p>Returned by <code>crypto.createDiffieHellman</code>.
|
||
|
||
</p>
|
||
<h3>diffieHellman.generateKeys([encoding])<span><a class="mark" href="#all_diffiehellman_generatekeys_encoding" id="all_diffiehellman_generatekeys_encoding">#</a></span></h3>
|
||
<p>Generates private and public Diffie-Hellman key values, and returns the
|
||
public key in the specified encoding. This key should be transferred to the
|
||
other party. Encoding can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>.
|
||
Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<h3>diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])<span><a class="mark" href="#all_diffiehellman_computesecret_other_public_key_input_encoding_output_encoding" id="all_diffiehellman_computesecret_other_public_key_input_encoding_output_encoding">#</a></span></h3>
|
||
<p>Computes the shared secret using <code>other_public_key</code> as the other party's
|
||
public key and returns the computed shared secret. Supplied key is
|
||
interpreted using specified <code>input_encoding</code>, and secret is encoded using
|
||
specified <code>output_encoding</code>. Encodings can be <code>'binary'</code>, <code>'hex'</code>, or
|
||
<code>'base64'</code>. The input encoding defaults to <code>'binary'</code>.
|
||
If no output encoding is given, the input encoding is used as output encoding.
|
||
|
||
</p>
|
||
<h3>diffieHellman.getPrime([encoding])<span><a class="mark" href="#all_diffiehellman_getprime_encoding" id="all_diffiehellman_getprime_encoding">#</a></span></h3>
|
||
<p>Returns the Diffie-Hellman prime in the specified encoding, which can be
|
||
<code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<h3>diffieHellman.getGenerator([encoding])<span><a class="mark" href="#all_diffiehellman_getgenerator_encoding" id="all_diffiehellman_getgenerator_encoding">#</a></span></h3>
|
||
<p>Returns the Diffie-Hellman prime in the specified encoding, which can be
|
||
<code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<h3>diffieHellman.getPublicKey([encoding])<span><a class="mark" href="#all_diffiehellman_getpublickey_encoding" id="all_diffiehellman_getpublickey_encoding">#</a></span></h3>
|
||
<p>Returns the Diffie-Hellman public key in the specified encoding, which can
|
||
be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<h3>diffieHellman.getPrivateKey([encoding])<span><a class="mark" href="#all_diffiehellman_getprivatekey_encoding" id="all_diffiehellman_getprivatekey_encoding">#</a></span></h3>
|
||
<p>Returns the Diffie-Hellman private key in the specified encoding, which can
|
||
be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<h3>diffieHellman.setPublicKey(public_key, [encoding])<span><a class="mark" href="#all_diffiehellman_setpublickey_public_key_encoding" id="all_diffiehellman_setpublickey_public_key_encoding">#</a></span></h3>
|
||
<p>Sets the Diffie-Hellman public key. Key encoding can be <code>'binary'</code>, <code>'hex'</code>,
|
||
or <code>'base64'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<h3>diffieHellman.setPrivateKey(public_key, [encoding])<span><a class="mark" href="#all_diffiehellman_setprivatekey_public_key_encoding" id="all_diffiehellman_setprivatekey_public_key_encoding">#</a></span></h3>
|
||
<p>Sets the Diffie-Hellman private key. Key encoding can be <code>'binary'</code>, <code>'hex'</code>,
|
||
or <code>'base64'</code>. Defaults to <code>'binary'</code>.
|
||
|
||
</p>
|
||
<h2>crypto.getDiffieHellman(group_name)<span><a class="mark" href="#all_crypto_getdiffiehellman_group_name" id="all_crypto_getdiffiehellman_group_name">#</a></span></h2>
|
||
<p>Creates a predefined Diffie-Hellman key exchange object.
|
||
The supported groups are: <code>'modp1'</code>, <code>'modp2'</code>, <code>'modp5'</code>
|
||
(defined in <a href="http://www.rfc-editor.org/rfc/rfc2412.txt">RFC 2412</a>)
|
||
and <code>'modp14'</code>, <code>'modp15'</code>, <code>'modp16'</code>, <code>'modp17'</code>, <code>'modp18'</code>
|
||
(defined in <a href="http://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a>).
|
||
The returned object mimics the interface of objects created by
|
||
<a href="#crypto_crypto_creatediffiehellman_prime_encoding">crypto.createDiffieHellman()</a> above, but
|
||
will not allow to change the keys (with
|
||
<a href="#crypto_diffiehellman_setpublickey_public_key_encoding">diffieHellman.setPublicKey()</a> for example).
|
||
The advantage of using this routine is that the parties don't have to
|
||
generate nor exchange group modulus beforehand, saving both processor and
|
||
communication time.
|
||
|
||
</p>
|
||
<p>Example (obtaining a shared secret):
|
||
|
||
</p>
|
||
<pre><code>var crypto = require('crypto');
|
||
var alice = crypto.getDiffieHellman('modp5');
|
||
var bob = crypto.getDiffieHellman('modp5');
|
||
|
||
alice.generateKeys();
|
||
bob.generateKeys();
|
||
|
||
var alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex');
|
||
var bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex');
|
||
|
||
/* alice_secret and bob_secret should be the same */
|
||
console.log(alice_secret == bob_secret);</code></pre>
|
||
<h2>crypto.pbkdf2(password, salt, iterations, keylen, callback)<span><a class="mark" href="#all_crypto_pbkdf2_password_salt_iterations_keylen_callback" id="all_crypto_pbkdf2_password_salt_iterations_keylen_callback">#</a></span></h2>
|
||
<p>Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive
|
||
a key of given length from the given password, salt and iterations.
|
||
The callback gets two arguments <code>(err, derivedKey)</code>.
|
||
|
||
</p>
|
||
<h2>crypto.randomBytes(size, [callback])<span><a class="mark" href="#all_crypto_randombytes_size_callback" id="all_crypto_randombytes_size_callback">#</a></span></h2>
|
||
<p>Generates cryptographically strong pseudo-random data. Usage:
|
||
|
||
</p>
|
||
<pre><code>// async
|
||
crypto.randomBytes(256, function(ex, buf) {
|
||
if (ex) throw ex;
|
||
console.log('Have %d bytes of random data: %s', buf.length, buf);
|
||
});
|
||
|
||
// sync
|
||
try {
|
||
var buf = crypto.randomBytes(256);
|
||
console.log('Have %d bytes of random data: %s', buf.length, buf);
|
||
} catch (ex) {
|
||
// handle error
|
||
}</code></pre>
|
||
<h2>Proposed API Changes in Future Versions of Node<span><a class="mark" href="#all_proposed_api_changes_in_future_versions_of_node" id="all_proposed_api_changes_in_future_versions_of_node">#</a></span></h2>
|
||
<p>The Crypto module was added to Node before there was the concept of a
|
||
unified Stream API, and before there were Buffer objects for handling
|
||
binary data.
|
||
|
||
</p>
|
||
<p>As such, the streaming classes don't have the typical methods found on
|
||
other Node classes, and many methods accept and return Binary-encoded
|
||
strings by default rather than Buffers.
|
||
|
||
</p>
|
||
<p>A future version of node will make Buffers the default data type.
|
||
This will be a breaking change for some use cases, but not all.
|
||
|
||
</p>
|
||
<p>For example, if you currently use the default arguments to the Sign
|
||
class, and then pass the results to the Verify class, without ever
|
||
inspecting the data, then it will continue to work as before. Where
|
||
you now get a binary string and then present the binary string to the
|
||
Verify object, you'll get a Buffer, and present the Buffer to the
|
||
Verify object.
|
||
|
||
</p>
|
||
<p>However, if you are doing things with the string data that will not
|
||
work properly on Buffers (such as, concatenating them, storing in
|
||
databases, etc.), or you are passing binary strings to the crypto
|
||
functions without an encoding argument, then you will need to start
|
||
providing encoding arguments to specify which encoding you'd like to
|
||
use.
|
||
|
||
</p>
|
||
<p>Also, a Streaming API will be provided, but this will be done in such
|
||
a way as to preserve the legacy API surface.
|
||
|
||
|
||
</p>
|
||
<h1>TLS (SSL)<span><a class="mark" href="#all_tls_ssl" id="all_tls_ssl">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>Use <code>require('tls')</code> to access this module.
|
||
|
||
</p>
|
||
<p>The <code>tls</code> module uses OpenSSL to provide Transport Layer Security and/or
|
||
Secure Socket Layer: encrypted stream communication.
|
||
|
||
</p>
|
||
<p>TLS/SSL is a public/private key infrastructure. Each client and each
|
||
server must have a private key. A private key is created like this
|
||
|
||
</p>
|
||
<pre><code>openssl genrsa -out ryans-key.pem 1024</code></pre>
|
||
<p>All severs and some clients need to have a certificate. Certificates are public
|
||
keys signed by a Certificate Authority or self-signed. The first step to
|
||
getting a certificate is to create a "Certificate Signing Request" (CSR)
|
||
file. This is done with:
|
||
|
||
</p>
|
||
<pre><code>openssl req -new -key ryans-key.pem -out ryans-csr.pem</code></pre>
|
||
<p>To create a self-signed certificate with the CSR, do this:
|
||
|
||
</p>
|
||
<pre><code>openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem</code></pre>
|
||
<p>Alternatively you can send the CSR to a Certificate Authority for signing.
|
||
|
||
</p>
|
||
<p>(TODO: docs on creating a CA, for now interested users should just look at
|
||
<code>test/fixtures/keys/Makefile</code> in the Node source code)
|
||
|
||
</p>
|
||
<p>To create .pfx or .p12, do this:
|
||
|
||
</p>
|
||
<pre><code>openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
|
||
-certfile ca-cert.pem -out agent5.pfx</code></pre>
|
||
<ul>
|
||
<li><code>in</code>: certificate</li>
|
||
<li><code>inkey</code>: private key</li>
|
||
<li><code>certfile</code>: all CA certs concatenated in one file like
|
||
<code>cat ca1-cert.pem ca2-cert.pem > ca-cert.pem</code></li>
|
||
</ul>
|
||
<h2>Client-initiated renegotiation attack mitigation<span><a class="mark" href="#all_client_initiated_renegotiation_attack_mitigation" id="all_client_initiated_renegotiation_attack_mitigation">#</a></span></h2>
|
||
<!-- type=misc -->
|
||
|
||
<p>The TLS protocol lets the client renegotiate certain aspects of the TLS session.
|
||
Unfortunately, session renegotiation requires a disproportional amount of
|
||
server-side resources, which makes it a potential vector for denial-of-service
|
||
attacks.
|
||
|
||
</p>
|
||
<p>To mitigate this, renegotiations are limited to three times every 10 minutes. An
|
||
error is emitted on the <a href="#tls_class_tls_cleartextstream">CleartextStream</a> instance when the threshold is
|
||
exceeded. The limits are configurable:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>tls.CLIENT_RENEG_LIMIT</code>: renegotiation limit, default is 3.</p>
|
||
</li>
|
||
<li><p><code>tls.CLIENT_RENEG_WINDOW</code>: renegotiation window in seconds, default is</p>
|
||
<pre><code> 10 minutes.</code></pre>
|
||
</li>
|
||
</ul>
|
||
<p>Don't change the defaults unless you know what you are doing.
|
||
|
||
</p>
|
||
<p>To test your server, connect to it with <code>openssl s_client -connect address:port</code>
|
||
and tap <code>R<CR></code> (that's the letter <code>R</code> followed by a carriage return) a few
|
||
times.
|
||
|
||
|
||
</p>
|
||
<h2>NPN and SNI<span><a class="mark" href="#all_npn_and_sni" id="all_npn_and_sni">#</a></span></h2>
|
||
<!-- type=misc -->
|
||
|
||
<p>NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS
|
||
handshake extensions allowing you:
|
||
|
||
</p>
|
||
<ul>
|
||
<li>NPN - to use one TLS server for multiple protocols (HTTP, SPDY)</li>
|
||
<li>SNI - to use one TLS server for multiple hostnames with different SSL
|
||
certificates.</li>
|
||
</ul>
|
||
<h2>tls.createServer(options, [secureConnectionListener])<span><a class="mark" href="#all_tls_createserver_options_secureconnectionlistener" id="all_tls_createserver_options_secureconnectionlistener">#</a></span></h2>
|
||
<p>Creates a new <a href="#tls_class_tls_server">tls.Server</a>. The <code>connectionListener</code> argument is
|
||
automatically set as a listener for the <a href="#tls_event_secureconnection">secureConnection</a> event. The
|
||
<code>options</code> object has these possibilities:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>pfx</code>: A string or <code>Buffer</code> containing the private key, certificate and
|
||
CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with
|
||
the <code>key</code>, <code>cert</code> and <code>ca</code> options.)</p>
|
||
</li>
|
||
<li><p><code>key</code>: A string or <code>Buffer</code> containing the private key of the server in
|
||
PEM format. (Required)</p>
|
||
</li>
|
||
<li><p><code>passphrase</code>: A string of passphrase for the private key or pfx.</p>
|
||
</li>
|
||
<li><p><code>cert</code>: A string or <code>Buffer</code> containing the certificate key of the server in
|
||
PEM format. (Required)</p>
|
||
</li>
|
||
<li><p><code>ca</code>: An array of strings or <code>Buffer</code>s of trusted certificates. If this is
|
||
omitted several well known "root" CAs will be used, like VeriSign.
|
||
These are used to authorize connections.</p>
|
||
</li>
|
||
<li><p><code>crl</code> : Either a string or list of strings of PEM encoded CRLs (Certificate
|
||
Revocation List)</p>
|
||
</li>
|
||
<li><p><code>ciphers</code>: A string describing the ciphers to use or exclude.</p>
|
||
<p>To mitigate <a href="http://blog.ivanristic.com/2011/10/mitigating-the-beast-attack-on-tls.html">BEAST attacks</a> it is recommended that you use this option in
|
||
conjunction with the <code>honorCipherOrder</code> option described below to
|
||
prioritize the non-CBC cipher.</p>
|
||
<p>Defaults to
|
||
<code>ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH</code>.
|
||
Consult the <a href="http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">OpenSSL cipher list format documentation</a> for details on the
|
||
format.</p>
|
||
<p><code>ECDHE-RSA-AES128-SHA256</code> and <code>AES128-GCM-SHA256</code> are used when node.js is
|
||
linked against OpenSSL 1.0.1 or newer and the client speaks TLS 1.2, RC4 is
|
||
used as a secure fallback.</p>
|
||
<p><strong>NOTE</strong>: Previous revisions of this section suggested <code>AES256-SHA</code> as an
|
||
acceptable cipher. Unfortunately, <code>AES256-SHA</code> is a CBC cipher and therefore
|
||
susceptible to BEAST attacks. Do <em>not</em> use it.</p>
|
||
</li>
|
||
<li><p><code>honorCipherOrder</code> : When choosing a cipher, use the server's preferences
|
||
instead of the client preferences.</p>
|
||
<p>Note that if SSLv2 is used, the server will send its list of preferences
|
||
to the client, and the client chooses the cipher.</p>
|
||
<p>Although, this option is disabled by default, it is <em>recommended</em> that you
|
||
use this option in conjunction with the <code>ciphers</code> option to mitigate
|
||
BEAST attacks.</p>
|
||
</li>
|
||
<li><p><code>requestCert</code>: If <code>true</code> the server will request a certificate from
|
||
clients that connect and attempt to verify that certificate. Default:
|
||
<code>false</code>.</p>
|
||
</li>
|
||
<li><p><code>rejectUnauthorized</code>: If <code>true</code> the server will reject any connection
|
||
which is not authorized with the list of supplied CAs. This option only
|
||
has an effect if <code>requestCert</code> is <code>true</code>. Default: <code>false</code>.</p>
|
||
</li>
|
||
<li><p><code>NPNProtocols</code>: An array or <code>Buffer</code> of possible NPN protocols. (Protocols
|
||
should be ordered by their priority).</p>
|
||
</li>
|
||
<li><p><code>SNICallback</code>: A function that will be called if client supports SNI TLS
|
||
extension. Only one argument will be passed to it: <code>servername</code>. And
|
||
<code>SNICallback</code> should return SecureContext instance.
|
||
(You can use <code>crypto.createCredentials(...).context</code> to get proper
|
||
SecureContext). If <code>SNICallback</code> wasn't provided - default callback with
|
||
high-level API will be used (see below).</p>
|
||
</li>
|
||
<li><p><code>sessionIdContext</code>: A string containing a opaque identifier for session
|
||
resumption. If <code>requestCert</code> is <code>true</code>, the default is MD5 hash value
|
||
generated from command-line. Otherwise, the default is not provided.</p>
|
||
</li>
|
||
</ul>
|
||
<p>Here is a simple example echo server:
|
||
|
||
</p>
|
||
<pre><code>var tls = require('tls');
|
||
var fs = require('fs');
|
||
|
||
var options = {
|
||
key: fs.readFileSync('server-key.pem'),
|
||
cert: fs.readFileSync('server-cert.pem'),
|
||
|
||
// This is necessary only if using the client certificate authentication.
|
||
requestCert: true,
|
||
|
||
// This is necessary only if the client uses the self-signed certificate.
|
||
ca: [ fs.readFileSync('client-cert.pem') ]
|
||
};
|
||
|
||
var server = tls.createServer(options, function(cleartextStream) {
|
||
console.log('server connected',
|
||
cleartextStream.authorized ? 'authorized' : 'unauthorized');
|
||
cleartextStream.write("welcome!\n");
|
||
cleartextStream.setEncoding('utf8');
|
||
cleartextStream.pipe(cleartextStream);
|
||
});
|
||
server.listen(8000, function() {
|
||
console.log('server bound');
|
||
});</code></pre>
|
||
<p>Or
|
||
|
||
</p>
|
||
<pre><code>var tls = require('tls');
|
||
var fs = require('fs');
|
||
|
||
var options = {
|
||
pfx: fs.readFileSync('server.pfx'),
|
||
|
||
// This is necessary only if using the client certificate authentication.
|
||
requestCert: true,
|
||
|
||
};
|
||
|
||
var server = tls.createServer(options, function(cleartextStream) {
|
||
console.log('server connected',
|
||
cleartextStream.authorized ? 'authorized' : 'unauthorized');
|
||
cleartextStream.write("welcome!\n");
|
||
cleartextStream.setEncoding('utf8');
|
||
cleartextStream.pipe(cleartextStream);
|
||
});
|
||
server.listen(8000, function() {
|
||
console.log('server bound');
|
||
});</code></pre>
|
||
<p>You can test this server by connecting to it with <code>openssl s_client</code>:
|
||
|
||
|
||
</p>
|
||
<pre><code>openssl s_client -connect 127.0.0.1:8000</code></pre>
|
||
<h2>tls.connect(options, [callback])<span><a class="mark" href="#all_tls_connect_options_callback" id="all_tls_connect_options_callback">#</a></span></h2>
|
||
<h2>tls.connect(port, [host], [options], [callback])<span><a class="mark" href="#all_tls_connect_port_host_options_callback" id="all_tls_connect_port_host_options_callback">#</a></span></h2>
|
||
<p>Creates a new client connection to the given <code>port</code> and <code>host</code> (old API) or
|
||
<code>options.port</code> and <code>options.host</code>. (If <code>host</code> is omitted, it defaults to
|
||
<code>localhost</code>.) <code>options</code> should be an object which specifies:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>host</code>: Host the client should connect to</p>
|
||
</li>
|
||
<li><p><code>port</code>: Port the client should connect to</p>
|
||
</li>
|
||
<li><p><code>socket</code>: Establish secure connection on a given socket rather than
|
||
creating a new socket. If this option is specified, <code>host</code> and <code>port</code>
|
||
are ignored.</p>
|
||
</li>
|
||
<li><p><code>pfx</code>: A string or <code>Buffer</code> containing the private key, certificate and
|
||
CA certs of the server in PFX or PKCS12 format.</p>
|
||
</li>
|
||
<li><p><code>key</code>: A string or <code>Buffer</code> containing the private key of the client in
|
||
PEM format.</p>
|
||
</li>
|
||
<li><p><code>passphrase</code>: A string of passphrase for the private key or pfx.</p>
|
||
</li>
|
||
<li><p><code>cert</code>: A string or <code>Buffer</code> containing the certificate key of the client in
|
||
PEM format.</p>
|
||
</li>
|
||
<li><p><code>ca</code>: An array of strings or <code>Buffer</code>s of trusted certificates. If this is
|
||
omitted several well known "root" CAs will be used, like VeriSign.
|
||
These are used to authorize connections.</p>
|
||
</li>
|
||
<li><p><code>rejectUnauthorized</code>: If <code>true</code>, the server certificate is verified against
|
||
the list of supplied CAs. An <code>'error'</code> event is emitted if verification
|
||
fails. Default: <code>false</code>.</p>
|
||
</li>
|
||
<li><p><code>NPNProtocols</code>: An array of string or <code>Buffer</code> containing supported NPN
|
||
protocols. <code>Buffer</code> should have following format: <code>0x05hello0x05world</code>,
|
||
where first byte is next protocol name's length. (Passing array should
|
||
usually be much simpler: <code>['hello', 'world']</code>.)</p>
|
||
</li>
|
||
<li><p><code>servername</code>: Servername for SNI (Server Name Indication) TLS extension.</p>
|
||
</li>
|
||
</ul>
|
||
<p>The <code>callback</code> parameter will be added as a listener for the
|
||
<a href="#tls_event_secureconnect">'secureConnect'</a> event.
|
||
|
||
</p>
|
||
<p><code>tls.connect()</code> returns a <a href="#tls_class_tls_cleartextstream">CleartextStream</a> object.
|
||
|
||
</p>
|
||
<p>Here is an example of a client of echo server as described previously:
|
||
|
||
</p>
|
||
<pre><code>var tls = require('tls');
|
||
var fs = require('fs');
|
||
|
||
var options = {
|
||
// These are necessary only if using the client certificate authentication
|
||
key: fs.readFileSync('client-key.pem'),
|
||
cert: fs.readFileSync('client-cert.pem'),
|
||
|
||
// This is necessary only if the server uses the self-signed certificate
|
||
ca: [ fs.readFileSync('server-cert.pem') ]
|
||
};
|
||
|
||
var cleartextStream = tls.connect(8000, options, function() {
|
||
console.log('client connected',
|
||
cleartextStream.authorized ? 'authorized' : 'unauthorized');
|
||
process.stdin.pipe(cleartextStream);
|
||
process.stdin.resume();
|
||
});
|
||
cleartextStream.setEncoding('utf8');
|
||
cleartextStream.on('data', function(data) {
|
||
console.log(data);
|
||
});
|
||
cleartextStream.on('end', function() {
|
||
server.close();
|
||
});</code></pre>
|
||
<p>Or
|
||
|
||
</p>
|
||
<pre><code>var tls = require('tls');
|
||
var fs = require('fs');
|
||
|
||
var options = {
|
||
pfx: fs.readFileSync('client.pfx')
|
||
};
|
||
|
||
var cleartextStream = tls.connect(8000, options, function() {
|
||
console.log('client connected',
|
||
cleartextStream.authorized ? 'authorized' : 'unauthorized');
|
||
process.stdin.pipe(cleartextStream);
|
||
process.stdin.resume();
|
||
});
|
||
cleartextStream.setEncoding('utf8');
|
||
cleartextStream.on('data', function(data) {
|
||
console.log(data);
|
||
});
|
||
cleartextStream.on('end', function() {
|
||
server.close();
|
||
});</code></pre>
|
||
<h2>tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])<span><a class="mark" href="#all_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized" id="all_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized">#</a></span></h2>
|
||
<p>Creates a new secure pair object with two streams, one of which reads/writes
|
||
encrypted data, and one reads/writes cleartext data.
|
||
Generally the encrypted one is piped to/from an incoming encrypted data stream,
|
||
and the cleartext one is used as a replacement for the initial encrypted stream.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>credentials</code>: A credentials object from crypto.createCredentials( ... )</p>
|
||
</li>
|
||
<li><p><code>isServer</code>: A boolean indicating whether this tls connection should be
|
||
opened as a server or a client.</p>
|
||
</li>
|
||
<li><p><code>requestCert</code>: A boolean indicating whether a server should request a
|
||
certificate from a connecting client. Only applies to server connections.</p>
|
||
</li>
|
||
<li><p><code>rejectUnauthorized</code>: A boolean indicating whether a server should
|
||
automatically reject clients with invalid certificates. Only applies to
|
||
servers with <code>requestCert</code> enabled.</p>
|
||
</li>
|
||
</ul>
|
||
<p><code>tls.createSecurePair()</code> returns a SecurePair object with [cleartext][] and
|
||
<code>encrypted</code> stream properties.
|
||
|
||
</p>
|
||
<h2>Class: SecurePair<span><a class="mark" href="#all_class_securepair" id="all_class_securepair">#</a></span></h2>
|
||
<p>Returned by tls.createSecurePair.
|
||
|
||
</p>
|
||
<h3>Event: 'secure'<span><a class="mark" href="#all_event_secure" id="all_event_secure">#</a></span></h3>
|
||
<p>The event is emitted from the SecurePair once the pair has successfully
|
||
established a secure connection.
|
||
|
||
</p>
|
||
<p>Similarly to the checking for the server 'secureConnection' event,
|
||
pair.cleartext.authorized should be checked to confirm whether the certificate
|
||
used properly authorized.
|
||
|
||
</p>
|
||
<h2>Class: tls.Server<span><a class="mark" href="#all_class_tls_server" id="all_class_tls_server">#</a></span></h2>
|
||
<p>This class is a subclass of <code>net.Server</code> and has the same methods on it.
|
||
Instead of accepting just raw TCP connections, this accepts encrypted
|
||
connections using TLS or SSL.
|
||
|
||
</p>
|
||
<h3>Event: 'secureConnection'<span><a class="mark" href="#all_event_secureconnection" id="all_event_secureconnection">#</a></span></h3>
|
||
<p><code>function (cleartextStream) {}</code>
|
||
|
||
</p>
|
||
<p>This event is emitted after a new connection has been successfully
|
||
handshaked. The argument is a instance of <a href="#tls_class_tls_cleartextstream">CleartextStream</a>. It has all the
|
||
common stream methods and events.
|
||
|
||
</p>
|
||
<p><code>cleartextStream.authorized</code> is a boolean value which indicates if the
|
||
client has verified by one of the supplied certificate authorities for the
|
||
server. If <code>cleartextStream.authorized</code> is false, then
|
||
<code>cleartextStream.authorizationError</code> is set to describe how authorization
|
||
failed. Implied but worth mentioning: depending on the settings of the TLS
|
||
server, you unauthorized connections may be accepted.
|
||
<code>cleartextStream.npnProtocol</code> is a string containing selected NPN protocol.
|
||
<code>cleartextStream.servername</code> is a string containing servername requested with
|
||
SNI.
|
||
|
||
|
||
</p>
|
||
<h3>Event: 'clientError'<span><a class="mark" href="#all_event_clienterror" id="all_event_clienterror">#</a></span></h3>
|
||
<p><code>function (exception) { }</code>
|
||
|
||
</p>
|
||
<p>When a client connection emits an 'error' event before secure connection is
|
||
established - it will be forwarded here.
|
||
|
||
|
||
</p>
|
||
<h3>server.listen(port, [host], [callback])<span><a class="mark" href="#all_server_listen_port_host_callback" id="all_server_listen_port_host_callback">#</a></span></h3>
|
||
<p>Begin accepting connections on the specified <code>port</code> and <code>host</code>. If the
|
||
<code>host</code> is omitted, the server will accept connections directed to any
|
||
IPv4 address (<code>INADDR_ANY</code>).
|
||
|
||
</p>
|
||
<p>This function is asynchronous. The last parameter <code>callback</code> will be called
|
||
when the server has been bound.
|
||
|
||
</p>
|
||
<p>See <code>net.Server</code> for more information.
|
||
|
||
|
||
</p>
|
||
<h3>server.close()<span><a class="mark" href="#all_server_close" id="all_server_close">#</a></span></h3>
|
||
<p>Stops the server from accepting new connections. This function is
|
||
asynchronous, the server is finally closed when the server emits a <code>'close'</code>
|
||
event.
|
||
|
||
</p>
|
||
<h3>server.address()<span><a class="mark" href="#all_server_address" id="all_server_address">#</a></span></h3>
|
||
<p>Returns the bound address, the address family name and port of the
|
||
server as reported by the operating system. See <a href="net.html#net_server_address">net.Server.address()</a> for
|
||
more information.
|
||
|
||
</p>
|
||
<h3>server.addContext(hostname, credentials)<span><a class="mark" href="#all_server_addcontext_hostname_credentials" id="all_server_addcontext_hostname_credentials">#</a></span></h3>
|
||
<p>Add secure context that will be used if client request's SNI hostname is
|
||
matching passed <code>hostname</code> (wildcards can be used). <code>credentials</code> can contain
|
||
<code>key</code>, <code>cert</code> and <code>ca</code>.
|
||
|
||
</p>
|
||
<h3>server.maxConnections<span><a class="mark" href="#all_server_maxconnections" id="all_server_maxconnections">#</a></span></h3>
|
||
<p>Set this property to reject connections when the server's connection count
|
||
gets high.
|
||
|
||
</p>
|
||
<h3>server.connections<span><a class="mark" href="#all_server_connections" id="all_server_connections">#</a></span></h3>
|
||
<p>The number of concurrent connections on the server.
|
||
|
||
|
||
</p>
|
||
<h2>Class: tls.CleartextStream<span><a class="mark" href="#all_class_tls_cleartextstream" id="all_class_tls_cleartextstream">#</a></span></h2>
|
||
<p>This is a stream on top of the <em>Encrypted</em> stream that makes it possible to
|
||
read/write an encrypted data as a cleartext data.
|
||
|
||
</p>
|
||
<p>This instance implements a duplex <a href="stream.html#stream_stream">Stream</a> interfaces. It has all the
|
||
common stream methods and events.
|
||
|
||
</p>
|
||
<p>A ClearTextStream is the <code>clear</code> member of a SecurePair object.
|
||
|
||
</p>
|
||
<h3>Event: 'secureConnect'<span><a class="mark" href="#all_event_secureconnect" id="all_event_secureconnect">#</a></span></h3>
|
||
<p>This event is emitted after a new connection has been successfully handshaked.
|
||
The listener will be called no matter if the server's certificate was
|
||
authorized or not. It is up to the user to test <code>cleartextStream.authorized</code>
|
||
to see if the server certificate was signed by one of the specified CAs.
|
||
If <code>cleartextStream.authorized === false</code> then the error can be found in
|
||
<code>cleartextStream.authorizationError</code>. Also if NPN was used - you can check
|
||
<code>cleartextStream.npnProtocol</code> for negotiated protocol.
|
||
|
||
</p>
|
||
<h3>cleartextStream.authorized<span><a class="mark" href="#all_cleartextstream_authorized" id="all_cleartextstream_authorized">#</a></span></h3>
|
||
<p>A boolean that is <code>true</code> if the peer certificate was signed by one of the
|
||
specified CAs, otherwise <code>false</code>
|
||
|
||
</p>
|
||
<h3>cleartextStream.authorizationError<span><a class="mark" href="#all_cleartextstream_authorizationerror" id="all_cleartextstream_authorizationerror">#</a></span></h3>
|
||
<p>The reason why the peer's certificate has not been verified. This property
|
||
becomes available only when <code>cleartextStream.authorized === false</code>.
|
||
|
||
</p>
|
||
<h3>cleartextStream.getPeerCertificate()<span><a class="mark" href="#all_cleartextstream_getpeercertificate" id="all_cleartextstream_getpeercertificate">#</a></span></h3>
|
||
<p>Returns an object representing the peer's certificate. The returned object has
|
||
some properties corresponding to the field of the certificate.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>{ subject:
|
||
{ C: 'UK',
|
||
ST: 'Acknack Ltd',
|
||
L: 'Rhys Jones',
|
||
O: 'node.js',
|
||
OU: 'Test TLS Certificate',
|
||
CN: 'localhost' },
|
||
issuer:
|
||
{ C: 'UK',
|
||
ST: 'Acknack Ltd',
|
||
L: 'Rhys Jones',
|
||
O: 'node.js',
|
||
OU: 'Test TLS Certificate',
|
||
CN: 'localhost' },
|
||
valid_from: 'Nov 11 09:52:22 2009 GMT',
|
||
valid_to: 'Nov 6 09:52:22 2029 GMT',
|
||
fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }</code></pre>
|
||
<p>If the peer does not provide a certificate, it returns <code>null</code> or an empty
|
||
object.
|
||
|
||
</p>
|
||
<h3>cleartextStream.getCipher()<span><a class="mark" href="#all_cleartextstream_getcipher" id="all_cleartextstream_getcipher">#</a></span></h3>
|
||
<p>Returns an object representing the cipher name and the SSL/TLS
|
||
protocol version of the current connection.
|
||
|
||
</p>
|
||
<p>Example:
|
||
{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
|
||
|
||
</p>
|
||
<p>See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in
|
||
<a href="http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS">http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS</a> for more
|
||
information.
|
||
|
||
</p>
|
||
<h3>cleartextStream.address()<span><a class="mark" href="#all_cleartextstream_address" id="all_cleartextstream_address">#</a></span></h3>
|
||
<p>Returns the bound address, the address family name and port of the
|
||
underlying socket as reported by the operating system. Returns an
|
||
object with three properties, e.g.
|
||
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>
|
||
|
||
</p>
|
||
<h3>cleartextStream.remoteAddress<span><a class="mark" href="#all_cleartextstream_remoteaddress" id="all_cleartextstream_remoteaddress">#</a></span></h3>
|
||
<p>The string representation of the remote IP address. For example,
|
||
<code>'74.125.127.100'</code> or <code>'2001:4860:a005::68'</code>.
|
||
|
||
</p>
|
||
<h3>cleartextStream.remotePort<span><a class="mark" href="#all_cleartextstream_remoteport" id="all_cleartextstream_remoteport">#</a></span></h3>
|
||
<p>The numeric representation of the remote port. For example, <code>443</code>.
|
||
|
||
</p>
|
||
<h1>StringDecoder<span><a class="mark" href="#all_stringdecoder" id="all_stringdecoder">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>To use this module, do <code>require('string_decoder')</code>. StringDecoder decodes a
|
||
buffer to a string. It is a simple interface to <code>buffer.toString()</code> but provides
|
||
additional support for utf8.
|
||
|
||
</p>
|
||
<pre><code>var StringDecoder = require('string_decoder').StringDecoder;
|
||
var decoder = new StringDecoder('utf8');
|
||
|
||
var cent = new Buffer([0xC2, 0xA2]);
|
||
console.log(decoder.write(cent));
|
||
|
||
var euro = new Buffer([0xE2, 0x82, 0xAC]);
|
||
console.log(decoder.write(euro));</code></pre>
|
||
<h2>Class: StringDecoder<span><a class="mark" href="#all_class_stringdecoder" id="all_class_stringdecoder">#</a></span></h2>
|
||
<p>Accepts a single argument, <code>encoding</code> which defaults to <code>utf8</code>.
|
||
|
||
</p>
|
||
<h3>StringDecoder.write(buffer)<span><a class="mark" href="#all_stringdecoder_write_buffer" id="all_stringdecoder_write_buffer">#</a></span></h3>
|
||
<p>Returns a decoded string.
|
||
</p>
|
||
<h1>File System<span><a class="mark" href="#all_file_system" id="all_file_system">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<!--name=fs-->
|
||
|
||
<p>File I/O is provided by simple wrappers around standard POSIX functions. To
|
||
use this module do <code>require('fs')</code>. All the methods have asynchronous and
|
||
synchronous forms.
|
||
|
||
</p>
|
||
<p>The asynchronous form always take a completion callback as its last argument.
|
||
The arguments passed to the completion callback depend on the method, but the
|
||
first argument is always reserved for an exception. If the operation was
|
||
completed successfully, then the first argument will be <code>null</code> or <code>undefined</code>.
|
||
|
||
</p>
|
||
<p>When using the synchronous form any exceptions are immediately thrown.
|
||
You can use try/catch to handle exceptions or allow them to bubble up.
|
||
|
||
</p>
|
||
<p>Here is an example of the asynchronous version:
|
||
|
||
</p>
|
||
<pre><code>var fs = require('fs');
|
||
|
||
fs.unlink('/tmp/hello', function (err) {
|
||
if (err) throw err;
|
||
console.log('successfully deleted /tmp/hello');
|
||
});</code></pre>
|
||
<p>Here is the synchronous version:
|
||
|
||
</p>
|
||
<pre><code>var fs = require('fs');
|
||
|
||
fs.unlinkSync('/tmp/hello')
|
||
console.log('successfully deleted /tmp/hello');</code></pre>
|
||
<p>With the asynchronous methods there is no guaranteed ordering. So the
|
||
following is prone to error:
|
||
|
||
</p>
|
||
<pre><code>fs.rename('/tmp/hello', '/tmp/world', function (err) {
|
||
if (err) throw err;
|
||
console.log('renamed complete');
|
||
});
|
||
fs.stat('/tmp/world', function (err, stats) {
|
||
if (err) throw err;
|
||
console.log('stats: ' + JSON.stringify(stats));
|
||
});</code></pre>
|
||
<p>It could be that <code>fs.stat</code> is executed before <code>fs.rename</code>.
|
||
The correct way to do this is to chain the callbacks.
|
||
|
||
</p>
|
||
<pre><code>fs.rename('/tmp/hello', '/tmp/world', function (err) {
|
||
if (err) throw err;
|
||
fs.stat('/tmp/world', function (err, stats) {
|
||
if (err) throw err;
|
||
console.log('stats: ' + JSON.stringify(stats));
|
||
});
|
||
});</code></pre>
|
||
<p>In busy processes, the programmer is <em>strongly encouraged</em> to use the
|
||
asynchronous versions of these calls. The synchronous versions will block
|
||
the entire process until they complete--halting all connections.
|
||
|
||
</p>
|
||
<p>Relative path to filename can be used, remember however that this path will be relative
|
||
to <code>process.cwd()</code>.
|
||
|
||
</p>
|
||
<h2>fs.rename(oldPath, newPath, [callback])<span><a class="mark" href="#all_fs_rename_oldpath_newpath_callback" id="all_fs_rename_oldpath_newpath_callback">#</a></span></h2>
|
||
<p>Asynchronous rename(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.renameSync(oldPath, newPath)<span><a class="mark" href="#all_fs_renamesync_oldpath_newpath" id="all_fs_renamesync_oldpath_newpath">#</a></span></h2>
|
||
<p>Synchronous rename(2).
|
||
|
||
</p>
|
||
<h2>fs.truncate(fd, len, [callback])<span><a class="mark" href="#all_fs_truncate_fd_len_callback" id="all_fs_truncate_fd_len_callback">#</a></span></h2>
|
||
<p>Asynchronous ftruncate(2). No arguments other than a possible exception are
|
||
given to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.truncateSync(fd, len)<span><a class="mark" href="#all_fs_truncatesync_fd_len" id="all_fs_truncatesync_fd_len">#</a></span></h2>
|
||
<p>Synchronous ftruncate(2).
|
||
|
||
</p>
|
||
<h2>fs.chown(path, uid, gid, [callback])<span><a class="mark" href="#all_fs_chown_path_uid_gid_callback" id="all_fs_chown_path_uid_gid_callback">#</a></span></h2>
|
||
<p>Asynchronous chown(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.chownSync(path, uid, gid)<span><a class="mark" href="#all_fs_chownsync_path_uid_gid" id="all_fs_chownsync_path_uid_gid">#</a></span></h2>
|
||
<p>Synchronous chown(2).
|
||
|
||
</p>
|
||
<h2>fs.fchown(fd, uid, gid, [callback])<span><a class="mark" href="#all_fs_fchown_fd_uid_gid_callback" id="all_fs_fchown_fd_uid_gid_callback">#</a></span></h2>
|
||
<p>Asynchronous fchown(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.fchownSync(fd, uid, gid)<span><a class="mark" href="#all_fs_fchownsync_fd_uid_gid" id="all_fs_fchownsync_fd_uid_gid">#</a></span></h2>
|
||
<p>Synchronous fchown(2).
|
||
|
||
</p>
|
||
<h2>fs.lchown(path, uid, gid, [callback])<span><a class="mark" href="#all_fs_lchown_path_uid_gid_callback" id="all_fs_lchown_path_uid_gid_callback">#</a></span></h2>
|
||
<p>Asynchronous lchown(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.lchownSync(path, uid, gid)<span><a class="mark" href="#all_fs_lchownsync_path_uid_gid" id="all_fs_lchownsync_path_uid_gid">#</a></span></h2>
|
||
<p>Synchronous lchown(2).
|
||
|
||
</p>
|
||
<h2>fs.chmod(path, mode, [callback])<span><a class="mark" href="#all_fs_chmod_path_mode_callback" id="all_fs_chmod_path_mode_callback">#</a></span></h2>
|
||
<p>Asynchronous chmod(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.chmodSync(path, mode)<span><a class="mark" href="#all_fs_chmodsync_path_mode" id="all_fs_chmodsync_path_mode">#</a></span></h2>
|
||
<p>Synchronous chmod(2).
|
||
|
||
</p>
|
||
<h2>fs.fchmod(fd, mode, [callback])<span><a class="mark" href="#all_fs_fchmod_fd_mode_callback" id="all_fs_fchmod_fd_mode_callback">#</a></span></h2>
|
||
<p>Asynchronous fchmod(2). No arguments other than a possible exception
|
||
are given to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.fchmodSync(fd, mode)<span><a class="mark" href="#all_fs_fchmodsync_fd_mode" id="all_fs_fchmodsync_fd_mode">#</a></span></h2>
|
||
<p>Synchronous fchmod(2).
|
||
|
||
</p>
|
||
<h2>fs.lchmod(path, mode, [callback])<span><a class="mark" href="#all_fs_lchmod_path_mode_callback" id="all_fs_lchmod_path_mode_callback">#</a></span></h2>
|
||
<p>Asynchronous lchmod(2). No arguments other than a possible exception
|
||
are given to the completion callback.
|
||
|
||
</p>
|
||
<p>Only available on Mac OS X.
|
||
|
||
</p>
|
||
<h2>fs.lchmodSync(path, mode)<span><a class="mark" href="#all_fs_lchmodsync_path_mode" id="all_fs_lchmodsync_path_mode">#</a></span></h2>
|
||
<p>Synchronous lchmod(2).
|
||
|
||
</p>
|
||
<h2>fs.stat(path, [callback])<span><a class="mark" href="#all_fs_stat_path_callback" id="all_fs_stat_path_callback">#</a></span></h2>
|
||
<p>Asynchronous stat(2). The callback gets two arguments <code>(err, stats)</code> where
|
||
<code>stats</code> is a <a href="#fs_class_fs_stats">fs.Stats</a> object. See the <a href="#fs_class_fs_stats">fs.Stats</a>
|
||
section below for more information.
|
||
|
||
</p>
|
||
<h2>fs.lstat(path, [callback])<span><a class="mark" href="#all_fs_lstat_path_callback" id="all_fs_lstat_path_callback">#</a></span></h2>
|
||
<p>Asynchronous lstat(2). The callback gets two arguments <code>(err, stats)</code> where
|
||
<code>stats</code> is a <code>fs.Stats</code> object. <code>lstat()</code> is identical to <code>stat()</code>, except that if
|
||
<code>path</code> is a symbolic link, then the link itself is stat-ed, not the file that it
|
||
refers to.
|
||
|
||
</p>
|
||
<h2>fs.fstat(fd, [callback])<span><a class="mark" href="#all_fs_fstat_fd_callback" id="all_fs_fstat_fd_callback">#</a></span></h2>
|
||
<p>Asynchronous fstat(2). The callback gets two arguments <code>(err, stats)</code> where
|
||
<code>stats</code> is a <code>fs.Stats</code> object. <code>fstat()</code> is identical to <code>stat()</code>, except that
|
||
the file to be stat-ed is specified by the file descriptor <code>fd</code>.
|
||
|
||
</p>
|
||
<h2>fs.statSync(path)<span><a class="mark" href="#all_fs_statsync_path" id="all_fs_statsync_path">#</a></span></h2>
|
||
<p>Synchronous stat(2). Returns an instance of <code>fs.Stats</code>.
|
||
|
||
</p>
|
||
<h2>fs.lstatSync(path)<span><a class="mark" href="#all_fs_lstatsync_path" id="all_fs_lstatsync_path">#</a></span></h2>
|
||
<p>Synchronous lstat(2). Returns an instance of <code>fs.Stats</code>.
|
||
|
||
</p>
|
||
<h2>fs.fstatSync(fd)<span><a class="mark" href="#all_fs_fstatsync_fd" id="all_fs_fstatsync_fd">#</a></span></h2>
|
||
<p>Synchronous fstat(2). Returns an instance of <code>fs.Stats</code>.
|
||
|
||
</p>
|
||
<h2>fs.link(srcpath, dstpath, [callback])<span><a class="mark" href="#all_fs_link_srcpath_dstpath_callback" id="all_fs_link_srcpath_dstpath_callback">#</a></span></h2>
|
||
<p>Asynchronous link(2). No arguments other than a possible exception are given to
|
||
the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.linkSync(srcpath, dstpath)<span><a class="mark" href="#all_fs_linksync_srcpath_dstpath" id="all_fs_linksync_srcpath_dstpath">#</a></span></h2>
|
||
<p>Synchronous link(2).
|
||
|
||
</p>
|
||
<h2>fs.symlink(srcpath, dstpath, [type], [callback])<span><a class="mark" href="#all_fs_symlink_srcpath_dstpath_type_callback" id="all_fs_symlink_srcpath_dstpath_type_callback">#</a></span></h2>
|
||
<p>Asynchronous symlink(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
<code>type</code> argument can be either <code>'dir'</code>, <code>'file'</code>, or <code>'junction'</code> (default is <code>'file'</code>). It is only
|
||
used on Windows (ignored on other platforms).
|
||
Note that Windows junction points require the destination path to be absolute. When using
|
||
<code>'junction'</code>, the <code>destination</code> argument will automatically be normalized to absolute path.
|
||
|
||
</p>
|
||
<h2>fs.symlinkSync(srcpath, dstpath, [type])<span><a class="mark" href="#all_fs_symlinksync_srcpath_dstpath_type" id="all_fs_symlinksync_srcpath_dstpath_type">#</a></span></h2>
|
||
<p>Synchronous symlink(2).
|
||
|
||
</p>
|
||
<h2>fs.readlink(path, [callback])<span><a class="mark" href="#all_fs_readlink_path_callback" id="all_fs_readlink_path_callback">#</a></span></h2>
|
||
<p>Asynchronous readlink(2). The callback gets two arguments <code>(err,
|
||
linkString)</code>.
|
||
|
||
</p>
|
||
<h2>fs.readlinkSync(path)<span><a class="mark" href="#all_fs_readlinksync_path" id="all_fs_readlinksync_path">#</a></span></h2>
|
||
<p>Synchronous readlink(2). Returns the symbolic link's string value.
|
||
|
||
</p>
|
||
<h2>fs.realpath(path, [cache], callback)<span><a class="mark" href="#all_fs_realpath_path_cache_callback" id="all_fs_realpath_path_cache_callback">#</a></span></h2>
|
||
<p>Asynchronous realpath(2). The <code>callback</code> gets two arguments <code>(err,
|
||
resolvedPath)</code>. May use <code>process.cwd</code> to resolve relative paths. <code>cache</code> is an
|
||
object literal of mapped paths that can be used to force a specific path
|
||
resolution or avoid additional <code>fs.stat</code> calls for known real paths.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var cache = {'/etc':'/private/etc'};
|
||
fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
|
||
if (err) throw err;
|
||
console.log(resolvedPath);
|
||
});</code></pre>
|
||
<h2>fs.realpathSync(path, [cache])<span><a class="mark" href="#all_fs_realpathsync_path_cache" id="all_fs_realpathsync_path_cache">#</a></span></h2>
|
||
<p>Synchronous realpath(2). Returns the resolved path.
|
||
|
||
</p>
|
||
<h2>fs.unlink(path, [callback])<span><a class="mark" href="#all_fs_unlink_path_callback" id="all_fs_unlink_path_callback">#</a></span></h2>
|
||
<p>Asynchronous unlink(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.unlinkSync(path)<span><a class="mark" href="#all_fs_unlinksync_path" id="all_fs_unlinksync_path">#</a></span></h2>
|
||
<p>Synchronous unlink(2).
|
||
|
||
</p>
|
||
<h2>fs.rmdir(path, [callback])<span><a class="mark" href="#all_fs_rmdir_path_callback" id="all_fs_rmdir_path_callback">#</a></span></h2>
|
||
<p>Asynchronous rmdir(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.rmdirSync(path)<span><a class="mark" href="#all_fs_rmdirsync_path" id="all_fs_rmdirsync_path">#</a></span></h2>
|
||
<p>Synchronous rmdir(2).
|
||
|
||
</p>
|
||
<h2>fs.mkdir(path, [mode], [callback])<span><a class="mark" href="#all_fs_mkdir_path_mode_callback" id="all_fs_mkdir_path_mode_callback">#</a></span></h2>
|
||
<p>Asynchronous mkdir(2). No arguments other than a possible exception are given
|
||
to the completion callback. <code>mode</code> defaults to <code>0777</code>.
|
||
|
||
</p>
|
||
<h2>fs.mkdirSync(path, [mode])<span><a class="mark" href="#all_fs_mkdirsync_path_mode" id="all_fs_mkdirsync_path_mode">#</a></span></h2>
|
||
<p>Synchronous mkdir(2).
|
||
|
||
</p>
|
||
<h2>fs.readdir(path, [callback])<span><a class="mark" href="#all_fs_readdir_path_callback" id="all_fs_readdir_path_callback">#</a></span></h2>
|
||
<p>Asynchronous readdir(3). Reads the contents of a directory.
|
||
The callback gets two arguments <code>(err, files)</code> where <code>files</code> is an array of
|
||
the names of the files in the directory excluding <code>'.'</code> and <code>'..'</code>.
|
||
|
||
</p>
|
||
<h2>fs.readdirSync(path)<span><a class="mark" href="#all_fs_readdirsync_path" id="all_fs_readdirsync_path">#</a></span></h2>
|
||
<p>Synchronous readdir(3). Returns an array of filenames excluding <code>'.'</code> and
|
||
<code>'..'</code>.
|
||
|
||
</p>
|
||
<h2>fs.close(fd, [callback])<span><a class="mark" href="#all_fs_close_fd_callback" id="all_fs_close_fd_callback">#</a></span></h2>
|
||
<p>Asynchronous close(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.closeSync(fd)<span><a class="mark" href="#all_fs_closesync_fd" id="all_fs_closesync_fd">#</a></span></h2>
|
||
<p>Synchronous close(2).
|
||
|
||
</p>
|
||
<h2>fs.open(path, flags, [mode], [callback])<span><a class="mark" href="#all_fs_open_path_flags_mode_callback" id="all_fs_open_path_flags_mode_callback">#</a></span></h2>
|
||
<p>Asynchronous file open. See open(2). <code>flags</code> can be:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>'r'</code> - Open file for reading.
|
||
An exception occurs if the file does not exist.</p>
|
||
</li>
|
||
<li><p><code>'r+'</code> - Open file for reading and writing.
|
||
An exception occurs if the file does not exist.</p>
|
||
</li>
|
||
<li><p><code>'rs'</code> - Open file for reading in synchronous mode. Instructs the operating
|
||
system to bypass the local file system cache.</p>
|
||
<p>This is primarily useful for opening files on NFS mounts as it allows you to
|
||
skip the potentially stale local cache. It has a very real impact on I/O
|
||
performance so don't use this mode unless you need it.</p>
|
||
<p>Note that this doesn't turn <code>fs.open()</code> into a synchronous blocking call.
|
||
If that's what you want then you should be using <code>fs.openSync()</code></p>
|
||
</li>
|
||
<li><p><code>'rs+'</code> - Open file for reading and writing, telling the OS to open it
|
||
synchronously. See notes for <code>'rs'</code> about using this with caution.</p>
|
||
</li>
|
||
<li><p><code>'w'</code> - Open file for writing.
|
||
The file is created (if it does not exist) or truncated (if it exists).</p>
|
||
</li>
|
||
<li><p><code>'wx'</code> - Like <code>'w'</code> but opens the file in exclusive mode.</p>
|
||
</li>
|
||
<li><p><code>'w+'</code> - Open file for reading and writing.
|
||
The file is created (if it does not exist) or truncated (if it exists).</p>
|
||
</li>
|
||
<li><p><code>'wx+'</code> - Like <code>'w+'</code> but opens the file in exclusive mode.</p>
|
||
</li>
|
||
<li><p><code>'a'</code> - Open file for appending.
|
||
The file is created if it does not exist.</p>
|
||
</li>
|
||
<li><p><code>'ax'</code> - Like <code>'a'</code> but opens the file in exclusive mode.</p>
|
||
</li>
|
||
<li><p><code>'a+'</code> - Open file for reading and appending.
|
||
The file is created if it does not exist.</p>
|
||
</li>
|
||
<li><p><code>'ax+'</code> - Like <code>'a+'</code> but opens the file in exclusive mode.</p>
|
||
</li>
|
||
</ul>
|
||
<p><code>mode</code> defaults to <code>0666</code>. The callback gets two arguments <code>(err, fd)</code>.
|
||
|
||
</p>
|
||
<p>Exclusive mode (<code>O_EXCL</code>) ensures that <code>path</code> is newly created. <code>fs.open()</code>
|
||
fails if a file by that name already exists. On POSIX systems, symlinks are
|
||
not followed. Exclusive mode may or may not work with network file systems.
|
||
|
||
</p>
|
||
<h2>fs.openSync(path, flags, [mode])<span><a class="mark" href="#all_fs_opensync_path_flags_mode" id="all_fs_opensync_path_flags_mode">#</a></span></h2>
|
||
<p>Synchronous open(2).
|
||
|
||
</p>
|
||
<h2>fs.utimes(path, atime, mtime, [callback])<span><a class="mark" href="#all_fs_utimes_path_atime_mtime_callback" id="all_fs_utimes_path_atime_mtime_callback">#</a></span></h2>
|
||
<h2>fs.utimesSync(path, atime, mtime)<span><a class="mark" href="#all_fs_utimessync_path_atime_mtime" id="all_fs_utimessync_path_atime_mtime">#</a></span></h2>
|
||
<p>Change file timestamps of the file referenced by the supplied path.
|
||
|
||
</p>
|
||
<h2>fs.futimes(fd, atime, mtime, [callback])<span><a class="mark" href="#all_fs_futimes_fd_atime_mtime_callback" id="all_fs_futimes_fd_atime_mtime_callback">#</a></span></h2>
|
||
<h2>fs.futimesSync(fd, atime, mtime)<span><a class="mark" href="#all_fs_futimessync_fd_atime_mtime" id="all_fs_futimessync_fd_atime_mtime">#</a></span></h2>
|
||
<p>Change the file timestamps of a file referenced by the supplied file
|
||
descriptor.
|
||
|
||
</p>
|
||
<h2>fs.fsync(fd, [callback])<span><a class="mark" href="#all_fs_fsync_fd_callback" id="all_fs_fsync_fd_callback">#</a></span></h2>
|
||
<p>Asynchronous fsync(2). No arguments other than a possible exception are given
|
||
to the completion callback.
|
||
|
||
</p>
|
||
<h2>fs.fsyncSync(fd)<span><a class="mark" href="#all_fs_fsyncsync_fd" id="all_fs_fsyncsync_fd">#</a></span></h2>
|
||
<p>Synchronous fsync(2).
|
||
|
||
</p>
|
||
<h2>fs.write(fd, buffer, offset, length, position, [callback])<span><a class="mark" href="#all_fs_write_fd_buffer_offset_length_position_callback" id="all_fs_write_fd_buffer_offset_length_position_callback">#</a></span></h2>
|
||
<p>Write <code>buffer</code> to the file specified by <code>fd</code>.
|
||
|
||
</p>
|
||
<p><code>offset</code> and <code>length</code> determine the part of the buffer to be written.
|
||
|
||
</p>
|
||
<p><code>position</code> refers to the offset from the beginning of the file where this data
|
||
should be written. If <code>position</code> is <code>null</code>, the data will be written at the
|
||
current position.
|
||
See pwrite(2).
|
||
|
||
</p>
|
||
<p>The callback will be given three arguments <code>(err, written, buffer)</code> where <code>written</code>
|
||
specifies how many <em>bytes</em> were written from <code>buffer</code>.
|
||
|
||
</p>
|
||
<p>Note that it is unsafe to use <code>fs.write</code> multiple times on the same file
|
||
without waiting for the callback. For this scenario,
|
||
<code>fs.createWriteStream</code> is strongly recommended.
|
||
|
||
</p>
|
||
<h2>fs.writeSync(fd, buffer, offset, length, position)<span><a class="mark" href="#all_fs_writesync_fd_buffer_offset_length_position" id="all_fs_writesync_fd_buffer_offset_length_position">#</a></span></h2>
|
||
<p>Synchronous version of <code>fs.write()</code>. Returns the number of bytes written.
|
||
|
||
</p>
|
||
<h2>fs.read(fd, buffer, offset, length, position, [callback])<span><a class="mark" href="#all_fs_read_fd_buffer_offset_length_position_callback" id="all_fs_read_fd_buffer_offset_length_position_callback">#</a></span></h2>
|
||
<p>Read data from the file specified by <code>fd</code>.
|
||
|
||
</p>
|
||
<p><code>buffer</code> is the buffer that the data will be written to.
|
||
|
||
</p>
|
||
<p><code>offset</code> is offset within the buffer where reading will start.
|
||
|
||
</p>
|
||
<p><code>length</code> is an integer specifying the number of bytes to read.
|
||
|
||
</p>
|
||
<p><code>position</code> is an integer specifying where to begin reading from in the file.
|
||
If <code>position</code> is <code>null</code>, data will be read from the current file position.
|
||
|
||
</p>
|
||
<p>The callback is given the three arguments, <code>(err, bytesRead, buffer)</code>.
|
||
|
||
</p>
|
||
<h2>fs.readSync(fd, buffer, offset, length, position)<span><a class="mark" href="#all_fs_readsync_fd_buffer_offset_length_position" id="all_fs_readsync_fd_buffer_offset_length_position">#</a></span></h2>
|
||
<p>Synchronous version of <code>fs.read</code>. Returns the number of <code>bytesRead</code>.
|
||
|
||
</p>
|
||
<h2>fs.readFile(filename, [encoding], [callback])<span><a class="mark" href="#all_fs_readfile_filename_encoding_callback" id="all_fs_readfile_filename_encoding_callback">#</a></span></h2>
|
||
<p>Asynchronously reads the entire contents of a file. Example:
|
||
|
||
</p>
|
||
<pre><code>fs.readFile('/etc/passwd', function (err, data) {
|
||
if (err) throw err;
|
||
console.log(data);
|
||
});</code></pre>
|
||
<p>The callback is passed two arguments <code>(err, data)</code>, where <code>data</code> is the
|
||
contents of the file.
|
||
|
||
</p>
|
||
<p>If no encoding is specified, then the raw buffer is returned.
|
||
|
||
|
||
</p>
|
||
<h2>fs.readFileSync(filename, [encoding])<span><a class="mark" href="#all_fs_readfilesync_filename_encoding" id="all_fs_readfilesync_filename_encoding">#</a></span></h2>
|
||
<p>Synchronous version of <code>fs.readFile</code>. Returns the contents of the <code>filename</code>.
|
||
|
||
</p>
|
||
<p>If <code>encoding</code> is specified then this function returns a string. Otherwise it
|
||
returns a buffer.
|
||
|
||
|
||
</p>
|
||
<h2>fs.writeFile(filename, data, [encoding], [callback])<span><a class="mark" href="#all_fs_writefile_filename_data_encoding_callback" id="all_fs_writefile_filename_data_encoding_callback">#</a></span></h2>
|
||
<p>Asynchronously writes data to a file, replacing the file if it already exists.
|
||
<code>data</code> can be a string or a buffer. The <code>encoding</code> argument is ignored if
|
||
<code>data</code> is a buffer. It defaults to <code>'utf8'</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>fs.writeFile('message.txt', 'Hello Node', function (err) {
|
||
if (err) throw err;
|
||
console.log('It\'s saved!');
|
||
});</code></pre>
|
||
<h2>fs.writeFileSync(filename, data, [encoding])<span><a class="mark" href="#all_fs_writefilesync_filename_data_encoding" id="all_fs_writefilesync_filename_data_encoding">#</a></span></h2>
|
||
<p>The synchronous version of <code>fs.writeFile</code>.
|
||
|
||
</p>
|
||
<h2>fs.appendFile(filename, data, encoding='utf8', [callback])<span><a class="mark" href="#all_fs_appendfile_filename_data_encoding_utf8_callback" id="all_fs_appendfile_filename_data_encoding_utf8_callback">#</a></span></h2>
|
||
<p>Asynchronously append data to a file, creating the file if it not yet exists.
|
||
<code>data</code> can be a string or a buffer. The <code>encoding</code> argument is ignored if
|
||
<code>data</code> is a buffer.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>fs.appendFile('message.txt', 'data to append', function (err) {
|
||
if (err) throw err;
|
||
console.log('The "data to append" was appended to file!');
|
||
});</code></pre>
|
||
<h2>fs.appendFileSync(filename, data, encoding='utf8')<span><a class="mark" href="#all_fs_appendfilesync_filename_data_encoding_utf8" id="all_fs_appendfilesync_filename_data_encoding_utf8">#</a></span></h2>
|
||
<p>The synchronous version of <code>fs.appendFile</code>.
|
||
|
||
</p>
|
||
<h2>fs.watchFile(filename, [options], listener)<span><a class="mark" href="#all_fs_watchfile_filename_options_listener" id="all_fs_watchfile_filename_options_listener">#</a></span></h2>
|
||
<pre><code>Stability: 2 - Unstable. Use fs.watch instead, if possible.</code></pre>
|
||
<p>Watch for changes on <code>filename</code>. The callback <code>listener</code> will be called each
|
||
time the file is accessed.
|
||
|
||
</p>
|
||
<p>The second argument is optional. The <code>options</code> if provided should be an object
|
||
containing two members a boolean, <code>persistent</code>, and <code>interval</code>. <code>persistent</code>
|
||
indicates whether the process should continue to run as long as files are
|
||
being watched. <code>interval</code> indicates how often the target should be polled,
|
||
in milliseconds. The default is <code>{ persistent: true, interval: 5007 }</code>.
|
||
|
||
</p>
|
||
<p>The <code>listener</code> gets two arguments the current stat object and the previous
|
||
stat object:
|
||
|
||
</p>
|
||
<pre><code>fs.watchFile('message.text', function (curr, prev) {
|
||
console.log('the current mtime is: ' + curr.mtime);
|
||
console.log('the previous mtime was: ' + prev.mtime);
|
||
});</code></pre>
|
||
<p>These stat objects are instances of <code>fs.Stat</code>.
|
||
|
||
</p>
|
||
<p>If you want to be notified when the file was modified, not just accessed
|
||
you need to compare <code>curr.mtime</code> and <code>prev.mtime</code>.
|
||
|
||
</p>
|
||
<h2>fs.unwatchFile(filename, [listener])<span><a class="mark" href="#all_fs_unwatchfile_filename_listener" id="all_fs_unwatchfile_filename_listener">#</a></span></h2>
|
||
<pre><code>Stability: 2 - Unstable. Use fs.watch instead, if available.</code></pre>
|
||
<p>Stop watching for changes on <code>filename</code>. If <code>listener</code> is specified, only that
|
||
particular listener is removed. Otherwise, <em>all</em> listeners are removed and you
|
||
have effectively stopped watching <code>filename</code>.
|
||
|
||
</p>
|
||
<p>Calling <code>fs.unwatchFile()</code> with a filename that is not being watched is a
|
||
no-op, not an error.
|
||
|
||
</p>
|
||
<h2>fs.watch(filename, [options], [listener])<span><a class="mark" href="#all_fs_watch_filename_options_listener" id="all_fs_watch_filename_options_listener">#</a></span></h2>
|
||
<pre><code>Stability: 2 - Unstable.</code></pre>
|
||
<p>Watch for changes on <code>filename</code>, where <code>filename</code> is either a file or a
|
||
directory. The returned object is a <a href="#fs_class_fs_fswatcher">fs.FSWatcher</a>.
|
||
|
||
</p>
|
||
<p>The second argument is optional. The <code>options</code> if provided should be an object
|
||
containing a boolean member <code>persistent</code>, which indicates whether the process
|
||
should continue to run as long as files are being watched. The default is
|
||
<code>{ persistent: true }</code>.
|
||
|
||
</p>
|
||
<p>The listener callback gets two arguments <code>(event, filename)</code>. <code>event</code> is either
|
||
'rename' or 'change', and <code>filename</code> is the name of the file which triggered
|
||
the event.
|
||
|
||
</p>
|
||
<h3>Caveats<span><a class="mark" href="#all_caveats" id="all_caveats">#</a></span></h3>
|
||
<!--type=misc-->
|
||
|
||
<p>The <code>fs.watch</code> API is not 100% consistent across platforms, and is
|
||
unavailable in some situations.
|
||
|
||
</p>
|
||
<h4>Availability<span><a class="mark" href="#all_availability" id="all_availability">#</a></span></h4>
|
||
<!--type=misc-->
|
||
|
||
<p>This feature depends on the underlying operating system providing a way
|
||
to be notified of filesystem changes.
|
||
|
||
</p>
|
||
<ul>
|
||
<li>On Linux systems, this uses <code>inotify</code>.</li>
|
||
<li>On BSD systems (including OS X), this uses <code>kqueue</code>.</li>
|
||
<li>On SunOS systems (including Solaris and SmartOS), this uses <code>event ports</code>.</li>
|
||
<li>On Windows systems, this feature depends on <code>ReadDirectoryChangesW</code>.</li>
|
||
</ul>
|
||
<p>If the underlying functionality is not available for some reason, then
|
||
<code>fs.watch</code> will not be able to function. For example, watching files or
|
||
directories on network file systems (NFS, SMB, etc.) often doesn't work
|
||
reliably or at all.
|
||
|
||
</p>
|
||
<p>You can still use <code>fs.watchFile</code>, which uses stat polling, but it is slower and
|
||
less reliable.
|
||
|
||
</p>
|
||
<h4>Filename Argument<span><a class="mark" href="#all_filename_argument" id="all_filename_argument">#</a></span></h4>
|
||
<!--type=misc-->
|
||
|
||
<p>Providing <code>filename</code> argument in the callback is not supported
|
||
on every platform (currently it's only supported on Linux and Windows). Even
|
||
on supported platforms <code>filename</code> is not always guaranteed to be provided.
|
||
Therefore, don't assume that <code>filename</code> argument is always provided in the
|
||
callback, and have some fallback logic if it is null.
|
||
|
||
</p>
|
||
<pre><code>fs.watch('somedir', function (event, filename) {
|
||
console.log('event is: ' + event);
|
||
if (filename) {
|
||
console.log('filename provided: ' + filename);
|
||
} else {
|
||
console.log('filename not provided');
|
||
}
|
||
});</code></pre>
|
||
<h2>fs.exists(path, [callback])<span><a class="mark" href="#all_fs_exists_path_callback" id="all_fs_exists_path_callback">#</a></span></h2>
|
||
<p>Test whether or not the given path exists by checking with the file system.
|
||
Then call the <code>callback</code> argument with either true or false. Example:
|
||
|
||
</p>
|
||
<pre><code>fs.exists('/etc/passwd', function (exists) {
|
||
util.debug(exists ? "it's there" : "no passwd!");
|
||
});</code></pre>
|
||
<h2>fs.existsSync(path)<span><a class="mark" href="#all_fs_existssync_path" id="all_fs_existssync_path">#</a></span></h2>
|
||
<p>Synchronous version of <code>fs.exists</code>.
|
||
|
||
</p>
|
||
<h2>Class: fs.Stats<span><a class="mark" href="#all_class_fs_stats" id="all_class_fs_stats">#</a></span></h2>
|
||
<p>Objects returned from <code>fs.stat()</code>, <code>fs.lstat()</code> and <code>fs.fstat()</code> and their
|
||
synchronous counterparts are of this type.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>stats.isFile()</code></li>
|
||
<li><code>stats.isDirectory()</code></li>
|
||
<li><code>stats.isBlockDevice()</code></li>
|
||
<li><code>stats.isCharacterDevice()</code></li>
|
||
<li><code>stats.isSymbolicLink()</code> (only valid with <code>fs.lstat()</code>)</li>
|
||
<li><code>stats.isFIFO()</code></li>
|
||
<li><code>stats.isSocket()</code></li>
|
||
</ul>
|
||
<p>For a regular file <code>util.inspect(stats)</code> would return a string very
|
||
similar to this:
|
||
|
||
</p>
|
||
<pre><code>{ dev: 2114,
|
||
ino: 48064969,
|
||
mode: 33188,
|
||
nlink: 1,
|
||
uid: 85,
|
||
gid: 100,
|
||
rdev: 0,
|
||
size: 527,
|
||
blksize: 4096,
|
||
blocks: 8,
|
||
atime: Mon, 10 Oct 2011 23:24:11 GMT,
|
||
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
|
||
ctime: Mon, 10 Oct 2011 23:24:11 GMT }</code></pre>
|
||
<p>Please note that <code>atime</code>, <code>mtime</code> and <code>ctime</code> are instances
|
||
of <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date">Date</a> object and to compare the values of
|
||
these objects you should use appropriate methods. For most
|
||
general uses <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime">getTime()</a> will return
|
||
the number of milliseconds elapsed since <em>1 January 1970
|
||
00:00:00 UTC</em> and this integer should be sufficient for
|
||
any comparison, however there additional methods which can
|
||
be used for displaying fuzzy information. More details can
|
||
be found in the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date">MDN JavaScript Reference</a> page.
|
||
|
||
</p>
|
||
<h2>fs.createReadStream(path, [options])<span><a class="mark" href="#all_fs_createreadstream_path_options" id="all_fs_createreadstream_path_options">#</a></span></h2>
|
||
<p>Returns a new ReadStream object (See <code>Readable Stream</code>).
|
||
|
||
</p>
|
||
<p><code>options</code> is an object with the following defaults:
|
||
|
||
</p>
|
||
<pre><code>{ flags: 'r',
|
||
encoding: null,
|
||
fd: null,
|
||
mode: 0666,
|
||
bufferSize: 64 * 1024
|
||
}</code></pre>
|
||
<p><code>options</code> can include <code>start</code> and <code>end</code> values to read a range of bytes from
|
||
the file instead of the entire file. Both <code>start</code> and <code>end</code> are inclusive and
|
||
start at 0. The <code>encoding</code> can be <code>'utf8'</code>, <code>'ascii'</code>, or <code>'base64'</code>.
|
||
|
||
</p>
|
||
<p>An example to read the last 10 bytes of a file which is 100 bytes long:
|
||
|
||
</p>
|
||
<pre><code>fs.createReadStream('sample.txt', {start: 90, end: 99});</code></pre>
|
||
<h2>Class: fs.ReadStream<span><a class="mark" href="#all_class_fs_readstream" id="all_class_fs_readstream">#</a></span></h2>
|
||
<p><code>ReadStream</code> is a <a href="stream.html#stream_readable_stream">Readable Stream</a>.
|
||
|
||
</p>
|
||
<h3>Event: 'open'<span><a class="mark" href="#all_event_open" id="all_event_open">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>fd</code> <span class="type">Integer</span> file descriptor used by the ReadStream.</li>
|
||
</div></ul>
|
||
<p>Emitted when the ReadStream's file is opened.
|
||
|
||
|
||
</p>
|
||
<h2>fs.createWriteStream(path, [options])<span><a class="mark" href="#all_fs_createwritestream_path_options" id="all_fs_createwritestream_path_options">#</a></span></h2>
|
||
<p>Returns a new WriteStream object (See <code>Writable Stream</code>).
|
||
|
||
</p>
|
||
<p><code>options</code> is an object with the following defaults:
|
||
|
||
</p>
|
||
<pre><code>{ flags: 'w',
|
||
encoding: null,
|
||
mode: 0666 }</code></pre>
|
||
<p><code>options</code> may also include a <code>start</code> option to allow writing data at
|
||
some position past the beginning of the file. Modifying a file rather
|
||
than replacing it may require a <code>flags</code> mode of <code>r+</code> rather than the
|
||
default mode <code>w</code>.
|
||
|
||
</p>
|
||
<h2>fs.WriteStream<span><a class="mark" href="#all_fs_writestream" id="all_fs_writestream">#</a></span></h2>
|
||
<p><code>WriteStream</code> is a <a href="stream.html#stream_writable_stream">Writable Stream</a>.
|
||
|
||
</p>
|
||
<h3>Event: 'open'<span><a class="mark" href="#all_event_open_1" id="all_event_open_1">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>fd</code> <span class="type">Integer</span> file descriptor used by the WriteStream.</li>
|
||
</div></ul>
|
||
<p>Emitted when the WriteStream's file is opened.
|
||
|
||
</p>
|
||
<h3>file.bytesWritten<span><a class="mark" href="#all_file_byteswritten" id="all_file_byteswritten">#</a></span></h3>
|
||
<p>The number of bytes written so far. Does not include data that is still queued
|
||
for writing.
|
||
|
||
</p>
|
||
<h2>Class: fs.FSWatcher<span><a class="mark" href="#all_class_fs_fswatcher" id="all_class_fs_fswatcher">#</a></span></h2>
|
||
<p>Objects returned from <code>fs.watch()</code> are of this type.
|
||
|
||
</p>
|
||
<h3>watcher.close()<span><a class="mark" href="#all_watcher_close" id="all_watcher_close">#</a></span></h3>
|
||
<p>Stop watching for changes on the given <code>fs.FSWatcher</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'change'<span><a class="mark" href="#all_event_change" id="all_event_change">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>event</code> <span class="type">String</span> The type of fs change</li>
|
||
<li><code>filename</code> <span class="type">String</span> The filename that changed (if relevant/available)</li>
|
||
</div></ul>
|
||
<p>Emitted when something changes in a watched directory or file.
|
||
See more details in <a href="#fs_fs_watch_filename_options_listener">fs.watch</a>.
|
||
|
||
</p>
|
||
<h3>Event: 'error'<span><a class="mark" href="#all_event_error_2" id="all_event_error_2">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>error</code> <span class="type">Error object</span></li>
|
||
</div></ul>
|
||
<p>Emitted when an error occurs.
|
||
|
||
</p>
|
||
<h1>Path<span><a class="mark" href="#all_path" id="all_path">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>This module contains utilities for handling and transforming file
|
||
paths. Almost all these methods perform only string transformations.
|
||
The file system is not consulted to check whether paths are valid.
|
||
|
||
</p>
|
||
<p>Use <code>require('path')</code> to use this module. The following methods are provided:
|
||
|
||
</p>
|
||
<h2>path.normalize(p)<span><a class="mark" href="#all_path_normalize_p" id="all_path_normalize_p">#</a></span></h2>
|
||
<p>Normalize a string path, taking care of <code>'..'</code> and <code>'.'</code> parts.
|
||
|
||
</p>
|
||
<p>When multiple slashes are found, they're replaced by a single one;
|
||
when the path contains a trailing slash, it is preserved.
|
||
On windows backslashes are used.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>path.normalize('/foo/bar//baz/asdf/quux/..')
|
||
// returns
|
||
'/foo/bar/baz/asdf'</code></pre>
|
||
<h2>path.join([path1], [path2], [...])<span><a class="mark" href="#all_path_join_path1_path2" id="all_path_join_path1_path2">#</a></span></h2>
|
||
<p>Join all arguments together and normalize the resulting path.
|
||
Non-string arguments are ignored.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
|
||
// returns
|
||
'/foo/bar/baz/asdf'
|
||
|
||
path.join('foo', {}, 'bar')
|
||
// returns
|
||
'foo/bar'</code></pre>
|
||
<h2>path.resolve([from ...], to)<span><a class="mark" href="#all_path_resolve_from_to" id="all_path_resolve_from_to">#</a></span></h2>
|
||
<p>Resolves <code>to</code> to an absolute path.
|
||
|
||
</p>
|
||
<p>If <code>to</code> isn't already absolute <code>from</code> arguments are prepended in right to left
|
||
order, until an absolute path is found. If after using all <code>from</code> paths still
|
||
no absolute path is found, the current working directory is used as well. The
|
||
resulting path is normalized, and trailing slashes are removed unless the path
|
||
gets resolved to the root directory. Non-string arguments are ignored.
|
||
|
||
</p>
|
||
<p>Another way to think of it is as a sequence of <code>cd</code> commands in a shell.
|
||
|
||
</p>
|
||
<pre><code>path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')</code></pre>
|
||
<p>Is similar to:
|
||
|
||
</p>
|
||
<pre><code>cd foo/bar
|
||
cd /tmp/file/
|
||
cd ..
|
||
cd a/../subfile
|
||
pwd</code></pre>
|
||
<p>The difference is that the different paths don't need to exist and may also be
|
||
files.
|
||
|
||
</p>
|
||
<p>Examples:
|
||
|
||
</p>
|
||
<pre><code>path.resolve('/foo/bar', './baz')
|
||
// returns
|
||
'/foo/bar/baz'
|
||
|
||
path.resolve('/foo/bar', '/tmp/file/')
|
||
// returns
|
||
'/tmp/file'
|
||
|
||
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
|
||
// if currently in /home/myself/node, it returns
|
||
'/home/myself/node/wwwroot/static_files/gif/image.gif'</code></pre>
|
||
<h2>path.relative(from, to)<span><a class="mark" href="#all_path_relative_from_to" id="all_path_relative_from_to">#</a></span></h2>
|
||
<p>Solve the relative path from <code>from</code> to <code>to</code>.
|
||
|
||
</p>
|
||
<p>At times we have two absolute paths, and we need to derive the relative
|
||
path from one to the other. This is actually the reverse transform of
|
||
<code>path.resolve</code>, which means we see that:
|
||
|
||
</p>
|
||
<pre><code>path.resolve(from, path.relative(from, to)) == path.resolve(to)</code></pre>
|
||
<p>Examples:
|
||
|
||
</p>
|
||
<pre><code>path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
|
||
// returns
|
||
'..\\..\\impl\\bbb'
|
||
|
||
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
|
||
// returns
|
||
'../../impl/bbb'</code></pre>
|
||
<h2>path.dirname(p)<span><a class="mark" href="#all_path_dirname_p" id="all_path_dirname_p">#</a></span></h2>
|
||
<p>Return the directory name of a path. Similar to the Unix <code>dirname</code> command.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>path.dirname('/foo/bar/baz/asdf/quux')
|
||
// returns
|
||
'/foo/bar/baz/asdf'</code></pre>
|
||
<h2>path.basename(p, [ext])<span><a class="mark" href="#all_path_basename_p_ext" id="all_path_basename_p_ext">#</a></span></h2>
|
||
<p>Return the last portion of a path. Similar to the Unix <code>basename</code> command.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>path.basename('/foo/bar/baz/asdf/quux.html')
|
||
// returns
|
||
'quux.html'
|
||
|
||
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
|
||
// returns
|
||
'quux'</code></pre>
|
||
<h2>path.extname(p)<span><a class="mark" href="#all_path_extname_p" id="all_path_extname_p">#</a></span></h2>
|
||
<p>Return the extension of the path, from the last '.' to end of string
|
||
in the last portion of the path. If there is no '.' in the last portion
|
||
of the path or the first character of it is '.', then it returns
|
||
an empty string. Examples:
|
||
|
||
</p>
|
||
<pre><code>path.extname('index.html')
|
||
// returns
|
||
'.html'
|
||
|
||
path.extname('index.')
|
||
// returns
|
||
'.'
|
||
|
||
path.extname('index')
|
||
// returns
|
||
''</code></pre>
|
||
<h2>path.sep<span><a class="mark" href="#all_path_sep" id="all_path_sep">#</a></span></h2>
|
||
<p>The platform-specific file separator. <code>'\\'</code> or <code>'/'</code>.
|
||
|
||
</p>
|
||
<p>An example on linux:
|
||
|
||
</p>
|
||
<pre><code>'foo/bar/baz'.split(path.sep)
|
||
// returns
|
||
['foo', 'bar', 'baz']</code></pre>
|
||
<p>An example on windows:
|
||
|
||
</p>
|
||
<pre><code>'foo\\bar\\baz'.split(path.sep)
|
||
// returns
|
||
['foo', 'bar', 'baz']</code></pre>
|
||
<h1>net<span><a class="mark" href="#all_net" id="all_net">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>The <code>net</code> module provides you with an asynchronous network wrapper. It contains
|
||
methods for creating both servers and clients (called streams). You can include
|
||
this module with <code>require('net');</code>
|
||
|
||
</p>
|
||
<h2>net.createServer([options], [connectionListener])<span><a class="mark" href="#all_net_createserver_options_connectionlistener" id="all_net_createserver_options_connectionlistener">#</a></span></h2>
|
||
<p>Creates a new TCP server. The <code>connectionListener</code> argument is
|
||
automatically set as a listener for the <a href="#net_event_connection">'connection'</a> event.
|
||
|
||
</p>
|
||
<p><code>options</code> is an object with the following defaults:
|
||
|
||
</p>
|
||
<pre><code>{ allowHalfOpen: false
|
||
}</code></pre>
|
||
<p>If <code>allowHalfOpen</code> is <code>true</code>, then the socket won't automatically send a FIN
|
||
packet when the other end of the socket sends a FIN packet. The socket becomes
|
||
non-readable, but still writable. You should call the <code>end()</code> method explicitly.
|
||
See <a href="#net_event_end">'end'</a> event for more information.
|
||
|
||
</p>
|
||
<p>Here is an example of an echo server which listens for connections
|
||
on port 8124:
|
||
|
||
</p>
|
||
<pre><code>var net = require('net');
|
||
var server = net.createServer(function(c) { //'connection' listener
|
||
console.log('server connected');
|
||
c.on('end', function() {
|
||
console.log('server disconnected');
|
||
});
|
||
c.write('hello\r\n');
|
||
c.pipe(c);
|
||
});
|
||
server.listen(8124, function() { //'listening' listener
|
||
console.log('server bound');
|
||
});</code></pre>
|
||
<p>Test this by using <code>telnet</code>:
|
||
|
||
</p>
|
||
<pre><code>telnet localhost 8124</code></pre>
|
||
<p>To listen on the socket <code>/tmp/echo.sock</code> the third line from the last would
|
||
just be changed to
|
||
|
||
</p>
|
||
<pre><code>server.listen('/tmp/echo.sock', function() { //'listening' listener</code></pre>
|
||
<p>Use <code>nc</code> to connect to a UNIX domain socket server:
|
||
|
||
</p>
|
||
<pre><code>nc -U /tmp/echo.sock</code></pre>
|
||
<h2>net.connect(options, [connectionListener])<span><a class="mark" href="#all_net_connect_options_connectionlistener" id="all_net_connect_options_connectionlistener">#</a></span></h2>
|
||
<h2>net.createConnection(options, [connectionListener])<span><a class="mark" href="#all_net_createconnection_options_connectionlistener" id="all_net_createconnection_options_connectionlistener">#</a></span></h2>
|
||
<p>Constructs a new socket object and opens the socket to the given location.
|
||
When the socket is established, the <a href="#net_event_connect">'connect'</a> event will be emitted.
|
||
|
||
</p>
|
||
<p>For TCP sockets, <code>options</code> argument should be an object which specifies:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>port</code>: Port the client should connect to (Required).</p>
|
||
</li>
|
||
<li><p><code>host</code>: Host the client should connect to. Defaults to <code>'localhost'</code>.</p>
|
||
</li>
|
||
<li><p><code>localAddress</code>: Local interface to bind to for network connections.</p>
|
||
</li>
|
||
</ul>
|
||
<p>For UNIX domain sockets, <code>options</code> argument should be an object which specifies:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>path</code>: Path the client should connect to (Required).</li>
|
||
</ul>
|
||
<p>Common options are:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>allowHalfOpen</code>: if <code>true</code>, the socket won't automatically send
|
||
a FIN packet when the other end of the socket sends a FIN packet.
|
||
Defaults to <code>false</code>. See <a href="#net_event_end">'end'</a> event for more information.</li>
|
||
</ul>
|
||
<p>The <code>connectListener</code> parameter will be added as an listener for the
|
||
<a href="#net_event_connect">'connect'</a> event.
|
||
|
||
</p>
|
||
<p>Here is an example of a client of echo server as described previously:
|
||
|
||
</p>
|
||
<pre><code>var net = require('net');
|
||
var client = net.connect({port: 8124},
|
||
function() { //'connect' listener
|
||
console.log('client connected');
|
||
client.write('world!\r\n');
|
||
});
|
||
client.on('data', function(data) {
|
||
console.log(data.toString());
|
||
client.end();
|
||
});
|
||
client.on('end', function() {
|
||
console.log('client disconnected');
|
||
});</code></pre>
|
||
<p>To connect on the socket <code>/tmp/echo.sock</code> the second line would just be
|
||
changed to
|
||
|
||
</p>
|
||
<pre><code>var client = net.connect({path: '/tmp/echo.sock'},</code></pre>
|
||
<h2>net.connect(port, [host], [connectListener])<span><a class="mark" href="#all_net_connect_port_host_connectlistener" id="all_net_connect_port_host_connectlistener">#</a></span></h2>
|
||
<h2>net.createConnection(port, [host], [connectListener])<span><a class="mark" href="#all_net_createconnection_port_host_connectlistener" id="all_net_createconnection_port_host_connectlistener">#</a></span></h2>
|
||
<p>Creates a TCP connection to <code>port</code> on <code>host</code>. If <code>host</code> is omitted,
|
||
<code>'localhost'</code> will be assumed.
|
||
The <code>connectListener</code> parameter will be added as an listener for the
|
||
<a href="#net_event_connect">'connect'</a> event.
|
||
|
||
</p>
|
||
<h2>net.connect(path, [connectListener])<span><a class="mark" href="#all_net_connect_path_connectlistener" id="all_net_connect_path_connectlistener">#</a></span></h2>
|
||
<h2>net.createConnection(path, [connectListener])<span><a class="mark" href="#all_net_createconnection_path_connectlistener" id="all_net_createconnection_path_connectlistener">#</a></span></h2>
|
||
<p>Creates unix socket connection to <code>path</code>.
|
||
The <code>connectListener</code> parameter will be added as an listener for the
|
||
<a href="#net_event_connect">'connect'</a> event.
|
||
|
||
</p>
|
||
<h2>Class: net.Server<span><a class="mark" href="#all_class_net_server" id="all_class_net_server">#</a></span></h2>
|
||
<p>This class is used to create a TCP or UNIX server.
|
||
A server is a <code>net.Socket</code> that can listen for new incoming connections.
|
||
|
||
</p>
|
||
<h3>server.listen(port, [host], [backlog], [callback])<span><a class="mark" href="#all_server_listen_port_host_backlog_callback" id="all_server_listen_port_host_backlog_callback">#</a></span></h3>
|
||
<p>Begin accepting connections on the specified <code>port</code> and <code>host</code>. If the
|
||
<code>host</code> is omitted, the server will accept connections directed to any
|
||
IPv4 address (<code>INADDR_ANY</code>). A port value of zero will assign a random port.
|
||
|
||
</p>
|
||
<p>Backlog is the maximum length of the queue of pending connections.
|
||
The actual length will be determined by your OS through sysctl settings such as
|
||
<code>tcp_max_syn_backlog</code> and <code>somaxconn</code> on linux. The default value of this
|
||
parameter is 511 (not 512).
|
||
|
||
</p>
|
||
<p>This function is asynchronous. When the server has been bound,
|
||
<a href="net.html#net_event_listening">'listening'</a> event will be emitted. The last parameter <code>callback</code>
|
||
will be added as an listener for the <a href="net.html#net_event_listening">'listening'</a> event.
|
||
|
||
</p>
|
||
<p>One issue some users run into is getting <code>EADDRINUSE</code> errors. This means that
|
||
another server is already running on the requested port. One way of handling this
|
||
would be to wait a second and then try again. This can be done with
|
||
|
||
</p>
|
||
<pre><code>server.on('error', function (e) {
|
||
if (e.code == 'EADDRINUSE') {
|
||
console.log('Address in use, retrying...');
|
||
setTimeout(function () {
|
||
server.close();
|
||
server.listen(PORT, HOST);
|
||
}, 1000);
|
||
}
|
||
});</code></pre>
|
||
<p>(Note: All sockets in Node set <code>SO_REUSEADDR</code> already)
|
||
|
||
|
||
</p>
|
||
<h3>server.listen(path, [callback])<span><a class="mark" href="#all_server_listen_path_callback" id="all_server_listen_path_callback">#</a></span></h3>
|
||
<p>Start a UNIX socket server listening for connections on the given <code>path</code>.
|
||
|
||
</p>
|
||
<p>This function is asynchronous. When the server has been bound,
|
||
<a href="net.html#net_event_listening">'listening'</a> event will be emitted. The last parameter <code>callback</code>
|
||
will be added as an listener for the <a href="net.html#net_event_listening">'listening'</a> event.
|
||
|
||
</p>
|
||
<h3>server.listen(handle, [callback])<span><a class="mark" href="#all_server_listen_handle_callback" id="all_server_listen_handle_callback">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>handle</code> <span class="type">Object</span></li>
|
||
<li><code>callback</code> <span class="type">Function</span></li>
|
||
</div></ul>
|
||
<p>The <code>handle</code> object can be set to either a server or socket (anything
|
||
with an underlying <code>_handle</code> member), or a <code>{fd: <n>}</code> object.
|
||
|
||
</p>
|
||
<p>This will cause the server to accept connections on the specified
|
||
handle, but it is presumed that the file descriptor or handle has
|
||
already been bound to a port or domain socket.
|
||
|
||
</p>
|
||
<p>Listening on a file descriptor is not supported on Windows.
|
||
|
||
</p>
|
||
<p>This function is asynchronous. When the server has been bound,
|
||
<a href="#event_listening_">'listening'</a> event will be emitted.
|
||
the last parameter <code>callback</code> will be added as an listener for the
|
||
<a href="#event_listening_">'listening'</a> event.
|
||
|
||
</p>
|
||
<h3>server.close([callback])<span><a class="mark" href="#all_server_close_callback" id="all_server_close_callback">#</a></span></h3>
|
||
<p>Stops the server from accepting new connections and keeps existing
|
||
connections. This function is asynchronous, the server is finally
|
||
closed when all connections are ended and the server emits a <code>'close'</code>
|
||
event. Optionally, you can pass a callback to listen for the <code>'close'</code>
|
||
event.
|
||
|
||
</p>
|
||
<h3>server.address()<span><a class="mark" href="#all_server_address_1" id="all_server_address_1">#</a></span></h3>
|
||
<p>Returns the bound address, the address family name and port of the server
|
||
as reported by the operating system.
|
||
Useful to find which port was assigned when giving getting an OS-assigned address.
|
||
Returns an object with three properties, e.g.
|
||
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var server = net.createServer(function (socket) {
|
||
socket.end("goodbye\n");
|
||
});
|
||
|
||
// grab a random port.
|
||
server.listen(function() {
|
||
address = server.address();
|
||
console.log("opened server on %j", address);
|
||
});</code></pre>
|
||
<p>Don't call <code>server.address()</code> until the <code>'listening'</code> event has been emitted.
|
||
|
||
</p>
|
||
<h3>server.maxConnections<span><a class="mark" href="#all_server_maxconnections_1" id="all_server_maxconnections_1">#</a></span></h3>
|
||
<p>Set this property to reject connections when the server's connection count gets
|
||
high.
|
||
|
||
</p>
|
||
<p>It is not recommended to use this option once a socket has been sent to a child
|
||
with <code>child_process.fork()</code>.
|
||
|
||
</p>
|
||
<h3>server.connections<span><a class="mark" href="#all_server_connections_1" id="all_server_connections_1">#</a></span></h3>
|
||
<p>The number of concurrent connections on the server.
|
||
|
||
</p>
|
||
<p>This becomes <code>null</code> when sending a socket to a child with <code>child_process.fork()</code>.
|
||
|
||
</p>
|
||
<p><code>net.Server</code> is an <a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
|
||
|
||
</p>
|
||
<h3>Event: 'listening'<span><a class="mark" href="#all_event_listening" id="all_event_listening">#</a></span></h3>
|
||
<p>Emitted when the server has been bound after calling <code>server.listen</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'connection'<span><a class="mark" href="#all_event_connection" id="all_event_connection">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Socket object</span> The connection object</li>
|
||
</div></ul>
|
||
<p>Emitted when a new connection is made. <code>socket</code> is an instance of
|
||
<code>net.Socket</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_2" id="all_event_close_2">#</a></span></h3>
|
||
<p>Emitted when the server closes. Note that if connections exist, this
|
||
event is not emitted until all connections are ended.
|
||
|
||
</p>
|
||
<h3>Event: 'error'<span><a class="mark" href="#all_event_error_3" id="all_event_error_3">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Error Object</span></li>
|
||
</div></ul>
|
||
<p>Emitted when an error occurs. The <code>'close'</code> event will be called directly
|
||
following this event. See example in discussion of <code>server.listen</code>.
|
||
|
||
</p>
|
||
<h2>Class: net.Socket<span><a class="mark" href="#all_class_net_socket" id="all_class_net_socket">#</a></span></h2>
|
||
<p>This object is an abstraction of a TCP or UNIX socket. <code>net.Socket</code>
|
||
instances implement a duplex Stream interface. They can be created by the
|
||
user and used as a client (with <code>connect()</code>) or they can be created by Node
|
||
and passed to the user through the <code>'connection'</code> event of a server.
|
||
|
||
</p>
|
||
<h3>new net.Socket([options])<span><a class="mark" href="#all_new_net_socket_options" id="all_new_net_socket_options">#</a></span></h3>
|
||
<p>Construct a new socket object.
|
||
|
||
</p>
|
||
<p><code>options</code> is an object with the following defaults:
|
||
|
||
</p>
|
||
<pre><code>{ fd: null
|
||
type: null
|
||
allowHalfOpen: false
|
||
}</code></pre>
|
||
<p><code>fd</code> allows you to specify the existing file descriptor of socket. <code>type</code>
|
||
specified underlying protocol. It can be <code>'tcp4'</code>, <code>'tcp6'</code>, or <code>'unix'</code>.
|
||
About <code>allowHalfOpen</code>, refer to <code>createServer()</code> and <code>'end'</code> event.
|
||
|
||
</p>
|
||
<h3>socket.connect(port, [host], [connectListener])<span><a class="mark" href="#all_socket_connect_port_host_connectlistener" id="all_socket_connect_port_host_connectlistener">#</a></span></h3>
|
||
<h3>socket.connect(path, [connectListener])<span><a class="mark" href="#all_socket_connect_path_connectlistener" id="all_socket_connect_path_connectlistener">#</a></span></h3>
|
||
<p>Opens the connection for a given socket. If <code>port</code> and <code>host</code> are given,
|
||
then the socket will be opened as a TCP socket, if <code>host</code> is omitted,
|
||
<code>localhost</code> will be assumed. If a <code>path</code> is given, the socket will be
|
||
opened as a unix socket to that path.
|
||
|
||
</p>
|
||
<p>Normally this method is not needed, as <code>net.createConnection</code> opens the
|
||
socket. Use this only if you are implementing a custom Socket or if a
|
||
Socket is closed and you want to reuse it to connect to another server.
|
||
|
||
</p>
|
||
<p>This function is asynchronous. When the <a href="#net_event_connect">'connect'</a> event is emitted the
|
||
socket is established. If there is a problem connecting, the <code>'connect'</code> event
|
||
will not be emitted, the <code>'error'</code> event will be emitted with the exception.
|
||
|
||
</p>
|
||
<p>The <code>connectListener</code> parameter will be added as an listener for the
|
||
<a href="#net_event_connect">'connect'</a> event.
|
||
|
||
|
||
</p>
|
||
<h3>socket.bufferSize<span><a class="mark" href="#all_socket_buffersize" id="all_socket_buffersize">#</a></span></h3>
|
||
<p><code>net.Socket</code> has the property that <code>socket.write()</code> always works. This is to
|
||
help users get up and running quickly. The computer cannot always keep up
|
||
with the amount of data that is written to a socket - the network connection
|
||
simply might be too slow. Node will internally queue up the data written to a
|
||
socket and send it out over the wire when it is possible. (Internally it is
|
||
polling on the socket's file descriptor for being writable).
|
||
|
||
</p>
|
||
<p>The consequence of this internal buffering is that memory may grow. This
|
||
property shows the number of characters currently buffered to be written.
|
||
(Number of characters is approximately equal to the number of bytes to be
|
||
written, but the buffer may contain strings, and the strings are lazily
|
||
encoded, so the exact number of bytes is not known.)
|
||
|
||
</p>
|
||
<p>Users who experience large or growing <code>bufferSize</code> should attempt to
|
||
"throttle" the data flows in their program with <code>pause()</code> and <code>resume()</code>.
|
||
|
||
|
||
</p>
|
||
<h3>socket.setEncoding([encoding])<span><a class="mark" href="#all_socket_setencoding_encoding" id="all_socket_setencoding_encoding">#</a></span></h3>
|
||
<p>Set the encoding for the socket as a Readable Stream. See
|
||
<a href="stream.html#stream_stream_setencoding_encoding">stream.setEncoding()</a> for more information.
|
||
|
||
</p>
|
||
<h3>socket.write(data, [encoding], [callback])<span><a class="mark" href="#all_socket_write_data_encoding_callback" id="all_socket_write_data_encoding_callback">#</a></span></h3>
|
||
<p>Sends data on the socket. The second parameter specifies the encoding in the
|
||
case of a string--it defaults to UTF8 encoding.
|
||
|
||
</p>
|
||
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
|
||
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
|
||
<code>'drain'</code> will be emitted when the buffer is again free.
|
||
|
||
</p>
|
||
<p>The optional <code>callback</code> parameter will be executed when the data is finally
|
||
written out - this may not be immediately.
|
||
|
||
</p>
|
||
<h3>socket.end([data], [encoding])<span><a class="mark" href="#all_socket_end_data_encoding" id="all_socket_end_data_encoding">#</a></span></h3>
|
||
<p>Half-closes the socket. i.e., it sends a FIN packet. It is possible the
|
||
server will still send some data.
|
||
|
||
</p>
|
||
<p>If <code>data</code> is specified, it is equivalent to calling
|
||
<code>socket.write(data, encoding)</code> followed by <code>socket.end()</code>.
|
||
|
||
</p>
|
||
<h3>socket.destroy()<span><a class="mark" href="#all_socket_destroy" id="all_socket_destroy">#</a></span></h3>
|
||
<p>Ensures that no more I/O activity happens on this socket. Only necessary in
|
||
case of errors (parse error or so).
|
||
|
||
</p>
|
||
<h3>socket.pause()<span><a class="mark" href="#all_socket_pause" id="all_socket_pause">#</a></span></h3>
|
||
<p>Pauses the reading of data. That is, <code>'data'</code> events will not be emitted.
|
||
Useful to throttle back an upload.
|
||
|
||
</p>
|
||
<h3>socket.resume()<span><a class="mark" href="#all_socket_resume" id="all_socket_resume">#</a></span></h3>
|
||
<p>Resumes reading after a call to <code>pause()</code>.
|
||
|
||
</p>
|
||
<h3>socket.setTimeout(timeout, [callback])<span><a class="mark" href="#all_socket_settimeout_timeout_callback" id="all_socket_settimeout_timeout_callback">#</a></span></h3>
|
||
<p>Sets the socket to timeout after <code>timeout</code> milliseconds of inactivity on
|
||
the socket. By default <code>net.Socket</code> do not have a timeout.
|
||
|
||
</p>
|
||
<p>When an idle timeout is triggered the socket will receive a <code>'timeout'</code>
|
||
event but the connection will not be severed. The user must manually <code>end()</code>
|
||
or <code>destroy()</code> the socket.
|
||
|
||
</p>
|
||
<p>If <code>timeout</code> is 0, then the existing idle timeout is disabled.
|
||
|
||
</p>
|
||
<p>The optional <code>callback</code> parameter will be added as a one time listener for the
|
||
<code>'timeout'</code> event.
|
||
|
||
</p>
|
||
<h3>socket.setNoDelay([noDelay])<span><a class="mark" href="#all_socket_setnodelay_nodelay" id="all_socket_setnodelay_nodelay">#</a></span></h3>
|
||
<p>Disables the Nagle algorithm. By default TCP connections use the Nagle
|
||
algorithm, they buffer data before sending it off. Setting <code>true</code> for
|
||
<code>noDelay</code> will immediately fire off data each time <code>socket.write()</code> is called.
|
||
<code>noDelay</code> defaults to <code>true</code>.
|
||
|
||
</p>
|
||
<h3>socket.setKeepAlive([enable], [initialDelay])<span><a class="mark" href="#all_socket_setkeepalive_enable_initialdelay" id="all_socket_setkeepalive_enable_initialdelay">#</a></span></h3>
|
||
<p>Enable/disable keep-alive functionality, and optionally set the initial
|
||
delay before the first keepalive probe is sent on an idle socket.
|
||
<code>enable</code> defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Set <code>initialDelay</code> (in milliseconds) to set the delay between the last
|
||
data packet received and the first keepalive probe. Setting 0 for
|
||
initialDelay will leave the value unchanged from the default
|
||
(or previous) setting. Defaults to <code>0</code>.
|
||
|
||
</p>
|
||
<h3>socket.address()<span><a class="mark" href="#all_socket_address" id="all_socket_address">#</a></span></h3>
|
||
<p>Returns the bound address, the address family name and port of the
|
||
socket as reported by the operating system. Returns an object with
|
||
three properties, e.g.
|
||
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>
|
||
|
||
</p>
|
||
<h3>socket.remoteAddress<span><a class="mark" href="#all_socket_remoteaddress" id="all_socket_remoteaddress">#</a></span></h3>
|
||
<p>The string representation of the remote IP address. For example,
|
||
<code>'74.125.127.100'</code> or <code>'2001:4860:a005::68'</code>.
|
||
|
||
</p>
|
||
<h3>socket.remotePort<span><a class="mark" href="#all_socket_remoteport" id="all_socket_remoteport">#</a></span></h3>
|
||
<p>The numeric representation of the remote port. For example,
|
||
<code>80</code> or <code>21</code>.
|
||
|
||
</p>
|
||
<h3>socket.bytesRead<span><a class="mark" href="#all_socket_bytesread" id="all_socket_bytesread">#</a></span></h3>
|
||
<p>The amount of received bytes.
|
||
|
||
</p>
|
||
<h3>socket.bytesWritten<span><a class="mark" href="#all_socket_byteswritten" id="all_socket_byteswritten">#</a></span></h3>
|
||
<p>The amount of bytes sent.
|
||
|
||
|
||
</p>
|
||
<p><code>net.Socket</code> instances are <a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
|
||
|
||
</p>
|
||
<h3>Event: 'connect'<span><a class="mark" href="#all_event_connect" id="all_event_connect">#</a></span></h3>
|
||
<p>Emitted when a socket connection is successfully established.
|
||
See <code>connect()</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'data'<span><a class="mark" href="#all_event_data_1" id="all_event_data_1">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Buffer object</span></li>
|
||
</div></ul>
|
||
<p>Emitted when data is received. The argument <code>data</code> will be a <code>Buffer</code> or
|
||
<code>String</code>. Encoding of data is set by <code>socket.setEncoding()</code>.
|
||
(See the <a href="stream.html#stream_readable_stream">Readable Stream</a> section for more information.)
|
||
|
||
</p>
|
||
<p>Note that the <strong>data will be lost</strong> if there is no listener when a <code>Socket</code>
|
||
emits a <code>'data'</code> event.
|
||
|
||
</p>
|
||
<h3>Event: 'end'<span><a class="mark" href="#all_event_end_1" id="all_event_end_1">#</a></span></h3>
|
||
<p>Emitted when the other end of the socket sends a FIN packet.
|
||
|
||
</p>
|
||
<p>By default (<code>allowHalfOpen == false</code>) the socket will destroy its file
|
||
descriptor once it has written out its pending write queue. However, by
|
||
setting <code>allowHalfOpen == true</code> the socket will not automatically <code>end()</code>
|
||
its side allowing the user to write arbitrary amounts of data, with the
|
||
caveat that the user is required to <code>end()</code> their side now.
|
||
|
||
|
||
</p>
|
||
<h3>Event: 'timeout'<span><a class="mark" href="#all_event_timeout" id="all_event_timeout">#</a></span></h3>
|
||
<p>Emitted if the socket times out from inactivity. This is only to notify that
|
||
the socket has been idle. The user must manually close the connection.
|
||
|
||
</p>
|
||
<p>See also: <code>socket.setTimeout()</code>
|
||
|
||
|
||
</p>
|
||
<h3>Event: 'drain'<span><a class="mark" href="#all_event_drain_1" id="all_event_drain_1">#</a></span></h3>
|
||
<p>Emitted when the write buffer becomes empty. Can be used to throttle uploads.
|
||
|
||
</p>
|
||
<p>See also: the return values of <code>socket.write()</code>
|
||
|
||
</p>
|
||
<h3>Event: 'error'<span><a class="mark" href="#all_event_error_4" id="all_event_error_4">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Error object</span></li>
|
||
</div></ul>
|
||
<p>Emitted when an error occurs. The <code>'close'</code> event will be called directly
|
||
following this event.
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_3" id="all_event_close_3">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>had_error</code> <span class="type">Boolean</span> true if the socket had a transmission error</li>
|
||
</div></ul>
|
||
<p>Emitted once the socket is fully closed. The argument <code>had_error</code> is a boolean
|
||
which says if the socket was closed due to a transmission error.
|
||
|
||
</p>
|
||
<h2>net.isIP(input)<span><a class="mark" href="#all_net_isip_input" id="all_net_isip_input">#</a></span></h2>
|
||
<p>Tests if input is an IP address. Returns 0 for invalid strings,
|
||
returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.
|
||
|
||
|
||
</p>
|
||
<h2>net.isIPv4(input)<span><a class="mark" href="#all_net_isipv4_input" id="all_net_isipv4_input">#</a></span></h2>
|
||
<p>Returns true if input is a version 4 IP address, otherwise returns false.
|
||
|
||
|
||
</p>
|
||
<h2>net.isIPv6(input)<span><a class="mark" href="#all_net_isipv6_input" id="all_net_isipv6_input">#</a></span></h2>
|
||
<p>Returns true if input is a version 6 IP address, otherwise returns false.
|
||
|
||
</p>
|
||
<h1>UDP / Datagram Sockets<span><a class="mark" href="#all_udp_datagram_sockets" id="all_udp_datagram_sockets">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<!-- name=dgram -->
|
||
|
||
<p>Datagram sockets are available through <code>require('dgram')</code>.
|
||
|
||
</p>
|
||
<h2>dgram.createSocket(type, [callback])<span><a class="mark" href="#all_dgram_createsocket_type_callback" id="all_dgram_createsocket_type_callback">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>type</code> String. Either 'udp4' or 'udp6'</li>
|
||
<li><code>callback</code> Function. Attached as a listener to <code>message</code> events.
|
||
Optional</li>
|
||
<li>Returns: Socket object</li>
|
||
</div></ul>
|
||
<p>Creates a datagram Socket of the specified types. Valid types are <code>udp4</code>
|
||
and <code>udp6</code>.
|
||
|
||
</p>
|
||
<p>Takes an optional callback which is added as a listener for <code>message</code> events.
|
||
|
||
</p>
|
||
<p>Call <code>socket.bind</code> if you want to receive datagrams. <code>socket.bind()</code> will bind
|
||
to the "all interfaces" address on a random port (it does the right thing for
|
||
both <code>udp4</code> and <code>udp6</code> sockets). You can then retrieve the address and port
|
||
with <code>socket.address().address</code> and <code>socket.address().port</code>.
|
||
|
||
</p>
|
||
<h2>Class: Socket<span><a class="mark" href="#all_class_socket" id="all_class_socket">#</a></span></h2>
|
||
<p>The dgram Socket class encapsulates the datagram functionality. It
|
||
should be created via <code>dgram.createSocket(type, [callback])</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'message'<span><a class="mark" href="#all_event_message" id="all_event_message">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>msg</code> Buffer object. The message</li>
|
||
<li><code>rinfo</code> Object. Remote address information</li>
|
||
</div></ul>
|
||
<p>Emitted when a new datagram is available on a socket. <code>msg</code> is a <code>Buffer</code> and <code>rinfo</code> is
|
||
an object with the sender's address information and the number of bytes in the datagram.
|
||
|
||
</p>
|
||
<h3>Event: 'listening'<span><a class="mark" href="#all_event_listening_1" id="all_event_listening_1">#</a></span></h3>
|
||
<p>Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
|
||
are created.
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_4" id="all_event_close_4">#</a></span></h3>
|
||
<p>Emitted when a socket is closed with <code>close()</code>. No new <code>message</code> events will be emitted
|
||
on this socket.
|
||
|
||
</p>
|
||
<h3>Event: 'error'<span><a class="mark" href="#all_event_error_5" id="all_event_error_5">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>exception</code> Error object</li>
|
||
</div></ul>
|
||
<p>Emitted when an error occurs.
|
||
|
||
</p>
|
||
<h3>dgram.send(buf, offset, length, port, address, [callback])<span><a class="mark" href="#all_dgram_send_buf_offset_length_port_address_callback" id="all_dgram_send_buf_offset_length_port_address_callback">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>buf</code> Buffer object. Message to be sent</li>
|
||
<li><code>offset</code> Integer. Offset in the buffer where the message starts.</li>
|
||
<li><code>length</code> Integer. Number of bytes in the message.</li>
|
||
<li><code>port</code> Integer. destination port</li>
|
||
<li><code>address</code> String. destination IP</li>
|
||
<li><code>callback</code> Function. Callback when message is done being delivered.
|
||
Optional.</li>
|
||
</div></ul>
|
||
<p>For UDP sockets, the destination port and IP address must be specified. A string
|
||
may be supplied for the <code>address</code> parameter, and it will be resolved with DNS. An
|
||
optional callback may be specified to detect any DNS errors and when <code>buf</code> may be
|
||
re-used. Note that DNS lookups will delay the time that a send takes place, at
|
||
least until the next tick. The only way to know for sure that a send has taken place
|
||
is to use the callback.
|
||
|
||
</p>
|
||
<p>If the socket has not been previously bound with a call to <code>bind</code>, it's
|
||
assigned a random port number and bound to the "all interfaces" address
|
||
(0.0.0.0 for <code>udp4</code> sockets, ::0 for <code>udp6</code> sockets).
|
||
|
||
</p>
|
||
<p>Example of sending a UDP packet to a random port on <code>localhost</code>;
|
||
|
||
</p>
|
||
<pre><code>var dgram = require('dgram');
|
||
var message = new Buffer("Some bytes");
|
||
var client = dgram.createSocket("udp4");
|
||
client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {
|
||
client.close();
|
||
});</code></pre>
|
||
<p><strong>A Note about UDP datagram size</strong>
|
||
|
||
</p>
|
||
<p>The maximum size of an <code>IPv4/v6</code> datagram depends on the <code>MTU</code> (<em>Maximum Transmission Unit</em>)
|
||
and on the <code>Payload Length</code> field size.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p>The <code>Payload Length</code> field is <code>16 bits</code> wide, which means that a normal payload
|
||
cannot be larger than 64K octets including internet header and data
|
||
(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
|
||
this is generally true for loopback interfaces, but such long datagrams
|
||
are impractical for most hosts and networks.</p>
|
||
</li>
|
||
<li><p>The <code>MTU</code> is the largest size a given link layer technology can support for datagrams.
|
||
For any link, <code>IPv4</code> mandates a minimum <code>MTU</code> of <code>68</code> octets, while the recommended <code>MTU</code>
|
||
for IPv4 is <code>576</code> (typically recommended as the <code>MTU</code> for dial-up type applications),
|
||
whether they arrive whole or in fragments.</p>
|
||
<p>For <code>IPv6</code>, the minimum <code>MTU</code> is <code>1280</code> octets, however, the mandatory minimum
|
||
fragment reassembly buffer size is <code>1500</code> octets.
|
||
The value of <code>68</code> octets is very small, since most current link layer technologies have
|
||
a minimum <code>MTU</code> of <code>1500</code> (like Ethernet).</p>
|
||
</li>
|
||
</ul>
|
||
<p>Note that it's impossible to know in advance the MTU of each link through which
|
||
a packet might travel, and that generally sending a datagram greater than
|
||
the (receiver) <code>MTU</code> won't work (the packet gets silently dropped, without
|
||
informing the source that the data did not reach its intended recipient).
|
||
|
||
</p>
|
||
<h3>dgram.bind(port, [address])<span><a class="mark" href="#all_dgram_bind_port_address" id="all_dgram_bind_port_address">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>port</code> Integer</li>
|
||
<li><code>address</code> String, Optional</li>
|
||
</div></ul>
|
||
<p>For UDP sockets, listen for datagrams on a named <code>port</code> and optional <code>address</code>. If
|
||
<code>address</code> is not specified, the OS will try to listen on all addresses.
|
||
|
||
</p>
|
||
<p>Example of a UDP server listening on port 41234:
|
||
|
||
</p>
|
||
<pre><code>var dgram = require("dgram");
|
||
|
||
var server = dgram.createSocket("udp4");
|
||
|
||
server.on("message", function (msg, rinfo) {
|
||
console.log("server got: " + msg + " from " +
|
||
rinfo.address + ":" + rinfo.port);
|
||
});
|
||
|
||
server.on("listening", function () {
|
||
var address = server.address();
|
||
console.log("server listening " +
|
||
address.address + ":" + address.port);
|
||
});
|
||
|
||
server.bind(41234);
|
||
// server listening 0.0.0.0:41234</code></pre>
|
||
<h3>dgram.close()<span><a class="mark" href="#all_dgram_close" id="all_dgram_close">#</a></span></h3>
|
||
<p>Close the underlying socket and stop listening for data on it.
|
||
|
||
</p>
|
||
<h3>dgram.address()<span><a class="mark" href="#all_dgram_address" id="all_dgram_address">#</a></span></h3>
|
||
<p>Returns an object containing the address information for a socket. For UDP sockets,
|
||
this object will contain <code>address</code> , <code>family</code> and <code>port</code>.
|
||
|
||
</p>
|
||
<h3>dgram.setBroadcast(flag)<span><a class="mark" href="#all_dgram_setbroadcast_flag" id="all_dgram_setbroadcast_flag">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>flag</code> Boolean</li>
|
||
</div></ul>
|
||
<p>Sets or clears the <code>SO_BROADCAST</code> socket option. When this option is set, UDP packets
|
||
may be sent to a local interface's broadcast address.
|
||
|
||
</p>
|
||
<h3>dgram.setTTL(ttl)<span><a class="mark" href="#all_dgram_setttl_ttl" id="all_dgram_setttl_ttl">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>ttl</code> Integer</li>
|
||
</div></ul>
|
||
<p>Sets the <code>IP_TTL</code> socket option. TTL stands for "Time to Live," but in this context it
|
||
specifies the number of IP hops that a packet is allowed to go through. Each router or
|
||
gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a
|
||
router, it will not be forwarded. Changing TTL values is typically done for network
|
||
probes or when multicasting.
|
||
|
||
</p>
|
||
<p>The argument to <code>setTTL()</code> is a number of hops between 1 and 255. The default on most
|
||
systems is 64.
|
||
|
||
</p>
|
||
<h3>dgram.setMulticastTTL(ttl)<span><a class="mark" href="#all_dgram_setmulticastttl_ttl" id="all_dgram_setmulticastttl_ttl">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>ttl</code> Integer</li>
|
||
</div></ul>
|
||
<p>Sets the <code>IP_MULTICAST_TTL</code> socket option. TTL stands for "Time to Live," but in this
|
||
context it specifies the number of IP hops that a packet is allowed to go through,
|
||
specifically for multicast traffic. Each router or gateway that forwards a packet
|
||
decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
|
||
|
||
</p>
|
||
<p>The argument to <code>setMulticastTTL()</code> is a number of hops between 0 and 255. The default on most
|
||
systems is 1.
|
||
|
||
</p>
|
||
<h3>dgram.setMulticastLoopback(flag)<span><a class="mark" href="#all_dgram_setmulticastloopback_flag" id="all_dgram_setmulticastloopback_flag">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>flag</code> Boolean</li>
|
||
</div></ul>
|
||
<p>Sets or clears the <code>IP_MULTICAST_LOOP</code> socket option. When this option is set, multicast
|
||
packets will also be received on the local interface.
|
||
|
||
</p>
|
||
<h3>dgram.addMembership(multicastAddress, [multicastInterface])<span><a class="mark" href="#all_dgram_addmembership_multicastaddress_multicastinterface" id="all_dgram_addmembership_multicastaddress_multicastinterface">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>multicastAddress</code> String</li>
|
||
<li><code>multicastInterface</code> String, Optional</li>
|
||
</div></ul>
|
||
<p>Tells the kernel to join a multicast group with <code>IP_ADD_MEMBERSHIP</code> socket option.
|
||
|
||
</p>
|
||
<p>If <code>multicastInterface</code> is not specified, the OS will try to add membership to all valid
|
||
interfaces.
|
||
|
||
</p>
|
||
<h3>dgram.dropMembership(multicastAddress, [multicastInterface])<span><a class="mark" href="#all_dgram_dropmembership_multicastaddress_multicastinterface" id="all_dgram_dropmembership_multicastaddress_multicastinterface">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>multicastAddress</code> String</li>
|
||
<li><code>multicastInterface</code> String, Optional</li>
|
||
</div></ul>
|
||
<p>Opposite of <code>addMembership</code> - tells the kernel to leave a multicast group with
|
||
<code>IP_DROP_MEMBERSHIP</code> socket option. This is automatically called by the kernel
|
||
when the socket is closed or process terminates, so most apps will never need to call
|
||
this.
|
||
|
||
</p>
|
||
<p>If <code>multicastInterface</code> is not specified, the OS will try to drop membership to all valid
|
||
interfaces.
|
||
|
||
</p>
|
||
<h1>DNS<span><a class="mark" href="#all_dns" id="all_dns">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>Use <code>require('dns')</code> to access this module. All methods in the dns module
|
||
use C-Ares except for <code>dns.lookup</code> which uses <code>getaddrinfo(3)</code> in a thread
|
||
pool. C-Ares is much faster than <code>getaddrinfo</code> but the system resolver is
|
||
more constant with how other programs operate. When a user does
|
||
<code>net.connect(80, 'google.com')</code> or <code>http.get({ host: 'google.com' })</code> the
|
||
<code>dns.lookup</code> method is used. Users who need to do a large number of look ups
|
||
quickly should use the methods that go through C-Ares.
|
||
|
||
</p>
|
||
<p>Here is an example which resolves <code>'www.google.com'</code> then reverse
|
||
resolves the IP addresses which are returned.
|
||
|
||
</p>
|
||
<pre><code>var dns = require('dns');
|
||
|
||
dns.resolve4('www.google.com', function (err, addresses) {
|
||
if (err) throw err;
|
||
|
||
console.log('addresses: ' + JSON.stringify(addresses));
|
||
|
||
addresses.forEach(function (a) {
|
||
dns.reverse(a, function (err, domains) {
|
||
if (err) {
|
||
throw err;
|
||
}
|
||
|
||
console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
|
||
});
|
||
});
|
||
});</code></pre>
|
||
<h2>dns.lookup(domain, [family], callback)<span><a class="mark" href="#all_dns_lookup_domain_family_callback" id="all_dns_lookup_domain_family_callback">#</a></span></h2>
|
||
<p>Resolves a domain (e.g. <code>'google.com'</code>) into the first found A (IPv4) or
|
||
AAAA (IPv6) record.
|
||
The <code>family</code> can be the integer <code>4</code> or <code>6</code>. Defaults to <code>null</code> that indicates
|
||
both Ip v4 and v6 address family.
|
||
|
||
</p>
|
||
<p>The callback has arguments <code>(err, address, family)</code>. The <code>address</code> argument
|
||
is a string representation of a IP v4 or v6 address. The <code>family</code> argument
|
||
is either the integer 4 or 6 and denotes the family of <code>address</code> (not
|
||
necessarily the value initially passed to <code>lookup</code>).
|
||
|
||
</p>
|
||
<p>On error, <code>err</code> is an <code>Error</code> object, where <code>err.code</code> is the error code.
|
||
Keep in mind that <code>err.code</code> will be set to <code>'ENOENT'</code> not only when
|
||
the domain does not exist but also when the lookup fails in other ways
|
||
such as no available file descriptors.
|
||
|
||
|
||
</p>
|
||
<h2>dns.resolve(domain, [rrtype], callback)<span><a class="mark" href="#all_dns_resolve_domain_rrtype_callback" id="all_dns_resolve_domain_rrtype_callback">#</a></span></h2>
|
||
<p>Resolves a domain (e.g. <code>'google.com'</code>) into an array of the record types
|
||
specified by rrtype. Valid rrtypes are <code>'A'</code> (IPV4 addresses, default),
|
||
<code>'AAAA'</code> (IPV6 addresses), <code>'MX'</code> (mail exchange records), <code>'TXT'</code> (text
|
||
records), <code>'SRV'</code> (SRV records), <code>'PTR'</code> (used for reverse IP lookups),
|
||
<code>'NS'</code> (name server records) and <code>'CNAME'</code> (canonical name records).
|
||
|
||
</p>
|
||
<p>The callback has arguments <code>(err, addresses)</code>. The type of each item
|
||
in <code>addresses</code> is determined by the record type, and described in the
|
||
documentation for the corresponding lookup methods below.
|
||
|
||
</p>
|
||
<p>On error, <code>err</code> is an <code>Error</code> object, where <code>err.code</code> is
|
||
one of the error codes listed below.
|
||
|
||
|
||
</p>
|
||
<h2>dns.resolve4(domain, callback)<span><a class="mark" href="#all_dns_resolve4_domain_callback" id="all_dns_resolve4_domain_callback">#</a></span></h2>
|
||
<p>The same as <code>dns.resolve()</code>, but only for IPv4 queries (<code>A</code> records).
|
||
<code>addresses</code> is an array of IPv4 addresses (e.g.
|
||
<code>['74.125.79.104', '74.125.79.105', '74.125.79.106']</code>).
|
||
|
||
</p>
|
||
<h2>dns.resolve6(domain, callback)<span><a class="mark" href="#all_dns_resolve6_domain_callback" id="all_dns_resolve6_domain_callback">#</a></span></h2>
|
||
<p>The same as <code>dns.resolve4()</code> except for IPv6 queries (an <code>AAAA</code> query).
|
||
|
||
|
||
</p>
|
||
<h2>dns.resolveMx(domain, callback)<span><a class="mark" href="#all_dns_resolvemx_domain_callback" id="all_dns_resolvemx_domain_callback">#</a></span></h2>
|
||
<p>The same as <code>dns.resolve()</code>, but only for mail exchange queries (<code>MX</code> records).
|
||
|
||
</p>
|
||
<p><code>addresses</code> is an array of MX records, each with a priority and an exchange
|
||
attribute (e.g. <code>[{'priority': 10, 'exchange': 'mx.example.com'},...]</code>).
|
||
|
||
</p>
|
||
<h2>dns.resolveTxt(domain, callback)<span><a class="mark" href="#all_dns_resolvetxt_domain_callback" id="all_dns_resolvetxt_domain_callback">#</a></span></h2>
|
||
<p>The same as <code>dns.resolve()</code>, but only for text queries (<code>TXT</code> records).
|
||
<code>addresses</code> is an array of the text records available for <code>domain</code> (e.g.,
|
||
<code>['v=spf1 ip4:0.0.0.0 ~all']</code>).
|
||
|
||
</p>
|
||
<h2>dns.resolveSrv(domain, callback)<span><a class="mark" href="#all_dns_resolvesrv_domain_callback" id="all_dns_resolvesrv_domain_callback">#</a></span></h2>
|
||
<p>The same as <code>dns.resolve()</code>, but only for service records (<code>SRV</code> records).
|
||
<code>addresses</code> is an array of the SRV records available for <code>domain</code>. Properties
|
||
of SRV records are priority, weight, port, and name (e.g.,
|
||
<code>[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]</code>).
|
||
|
||
</p>
|
||
<h2>dns.resolveNs(domain, callback)<span><a class="mark" href="#all_dns_resolvens_domain_callback" id="all_dns_resolvens_domain_callback">#</a></span></h2>
|
||
<p>The same as <code>dns.resolve()</code>, but only for name server records (<code>NS</code> records).
|
||
<code>addresses</code> is an array of the name server records available for <code>domain</code>
|
||
(e.g., <code>['ns1.example.com', 'ns2.example.com']</code>).
|
||
|
||
</p>
|
||
<h2>dns.resolveCname(domain, callback)<span><a class="mark" href="#all_dns_resolvecname_domain_callback" id="all_dns_resolvecname_domain_callback">#</a></span></h2>
|
||
<p>The same as <code>dns.resolve()</code>, but only for canonical name records (<code>CNAME</code>
|
||
records). <code>addresses</code> is an array of the canonical name records available for
|
||
<code>domain</code> (e.g., <code>['bar.example.com']</code>).
|
||
|
||
</p>
|
||
<h2>dns.reverse(ip, callback)<span><a class="mark" href="#all_dns_reverse_ip_callback" id="all_dns_reverse_ip_callback">#</a></span></h2>
|
||
<p>Reverse resolves an ip address to an array of domain names.
|
||
|
||
</p>
|
||
<p>The callback has arguments <code>(err, domains)</code>.
|
||
|
||
</p>
|
||
<p>On error, <code>err</code> is an <code>Error</code> object, where <code>err.code</code> is
|
||
one of the error codes listed below.
|
||
|
||
</p>
|
||
<h2>Error codes<span><a class="mark" href="#all_error_codes" id="all_error_codes">#</a></span></h2>
|
||
<p>Each DNS query can return one of the following error codes:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>dns.NODATA</code>: DNS server returned answer with no data.</li>
|
||
<li><code>dns.FORMERR</code>: DNS server claims query was misformatted.</li>
|
||
<li><code>dns.SERVFAIL</code>: DNS server returned general failure.</li>
|
||
<li><code>dns.NOTFOUND</code>: Domain name not found.</li>
|
||
<li><code>dns.NOTIMP</code>: DNS server does not implement requested operation.</li>
|
||
<li><code>dns.REFUSED</code>: DNS server refused query.</li>
|
||
<li><code>dns.BADQUERY</code>: Misformatted DNS query.</li>
|
||
<li><code>dns.BADNAME</code>: Misformatted domain name.</li>
|
||
<li><code>dns.BADFAMILY</code>: Unsupported address family.</li>
|
||
<li><code>dns.BADRESP</code>: Misformatted DNS reply.</li>
|
||
<li><code>dns.CONNREFUSED</code>: Could not contact DNS servers.</li>
|
||
<li><code>dns.TIMEOUT</code>: Timeout while contacting DNS servers.</li>
|
||
<li><code>dns.EOF</code>: End of file.</li>
|
||
<li><code>dns.FILE</code>: Error reading file.</li>
|
||
<li><code>dns.NOMEM</code>: Out of memory.</li>
|
||
<li><code>dns.DESTRUCTION</code>: Channel is being destroyed.</li>
|
||
<li><code>dns.BADSTR</code>: Misformatted string.</li>
|
||
<li><code>dns.BADFLAGS</code>: Illegal flags specified.</li>
|
||
<li><code>dns.NONAME</code>: Given hostname is not numeric.</li>
|
||
<li><code>dns.BADHINTS</code>: Illegal hints flags specified.</li>
|
||
<li><code>dns.NOTINITIALIZED</code>: c-ares library initialization not yet performed.</li>
|
||
<li><code>dns.LOADIPHLPAPI</code>: Error loading iphlpapi.dll.</li>
|
||
<li><code>dns.ADDRGETNETWORKPARAMS</code>: Could not find GetNetworkParams function.</li>
|
||
<li><code>dns.CANCELLED</code>: DNS query cancelled.</li>
|
||
</ul>
|
||
<h1>HTTP<span><a class="mark" href="#all_http" id="all_http">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>To use the HTTP server and client one must <code>require('http')</code>.
|
||
|
||
</p>
|
||
<p>The HTTP interfaces in Node are designed to support many features
|
||
of the protocol which have been traditionally difficult to use.
|
||
In particular, large, possibly chunk-encoded, messages. The interface is
|
||
careful to never buffer entire requests or responses--the
|
||
user is able to stream data.
|
||
|
||
</p>
|
||
<p>HTTP message headers are represented by an object like this:
|
||
|
||
</p>
|
||
<pre><code>{ 'content-length': '123',
|
||
'content-type': 'text/plain',
|
||
'connection': 'keep-alive',
|
||
'accept': '*/*' }</code></pre>
|
||
<p>Keys are lowercased. Values are not modified.
|
||
|
||
</p>
|
||
<p>In order to support the full spectrum of possible HTTP applications, Node's
|
||
HTTP API is very low-level. It deals with stream handling and message
|
||
parsing only. It parses a message into headers and body but it does not
|
||
parse the actual headers or the body.
|
||
|
||
|
||
</p>
|
||
<h2>http.STATUS_CODES<span><a class="mark" href="#all_http_status_codes" id="all_http_status_codes">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Object</span></li>
|
||
</div></ul>
|
||
<p>A collection of all the standard HTTP response status codes, and the
|
||
short description of each. For example, <code>http.STATUS_CODES[404] === 'Not
|
||
Found'</code>.
|
||
|
||
</p>
|
||
<h2>http.createServer([requestListener])<span><a class="mark" href="#all_http_createserver_requestlistener" id="all_http_createserver_requestlistener">#</a></span></h2>
|
||
<p>Returns a new web server object.
|
||
|
||
</p>
|
||
<p>The <code>requestListener</code> is a function which is automatically
|
||
added to the <code>'request'</code> event.
|
||
|
||
</p>
|
||
<h2>http.createClient([port], [host])<span><a class="mark" href="#all_http_createclient_port_host" id="all_http_createclient_port_host">#</a></span></h2>
|
||
<p>This function is <strong>deprecated</strong>; please use <a href="http.html#http_http_request_options_callback">http.request()</a> instead.
|
||
Constructs a new HTTP client. <code>port</code> and <code>host</code> refer to the server to be
|
||
connected to.
|
||
|
||
</p>
|
||
<h2>Class: http.Server<span><a class="mark" href="#all_class_http_server" id="all_class_http_server">#</a></span></h2>
|
||
<p>This is an <a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
|
||
|
||
</p>
|
||
<h3>Event: 'request'<span><a class="mark" href="#all_event_request" id="all_event_request">#</a></span></h3>
|
||
<p><code>function (request, response) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted each time there is a request. Note that there may be multiple requests
|
||
per connection (in the case of keep-alive connections).
|
||
<code>request</code> is an instance of <code>http.ServerRequest</code> and <code>response</code> is
|
||
an instance of <code>http.ServerResponse</code>
|
||
|
||
</p>
|
||
<h3>Event: 'connection'<span><a class="mark" href="#all_event_connection_1" id="all_event_connection_1">#</a></span></h3>
|
||
<p><code>function (socket) { }</code>
|
||
|
||
</p>
|
||
<p> When a new TCP stream is established. <code>socket</code> is an object of type
|
||
<code>net.Socket</code>. Usually users will not want to access this event. The
|
||
<code>socket</code> can also be accessed at <code>request.connection</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_5" id="all_event_close_5">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p> Emitted when the server closes.
|
||
|
||
</p>
|
||
<h3>Event: 'checkContinue'<span><a class="mark" href="#all_event_checkcontinue" id="all_event_checkcontinue">#</a></span></h3>
|
||
<p><code>function (request, response) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted each time a request with an http Expect: 100-continue is received.
|
||
If this event isn't listened for, the server will automatically respond
|
||
with a 100 Continue as appropriate.
|
||
|
||
</p>
|
||
<p>Handling this event involves calling <code>response.writeContinue</code> if the client
|
||
should continue to send the request body, or generating an appropriate HTTP
|
||
response (e.g., 400 Bad Request) if the client should not continue to send the
|
||
request body.
|
||
|
||
</p>
|
||
<p>Note that when this event is emitted and handled, the <code>request</code> event will
|
||
not be emitted.
|
||
|
||
</p>
|
||
<h3>Event: 'connect'<span><a class="mark" href="#all_event_connect_1" id="all_event_connect_1">#</a></span></h3>
|
||
<p><code>function (request, socket, head) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted each time a client requests a http CONNECT method. If this event isn't
|
||
listened for, then clients requesting a CONNECT method will have their
|
||
connections closed.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>request</code> is the arguments for the http request, as it is in the request
|
||
event.</li>
|
||
<li><code>socket</code> is the network socket between the server and client.</li>
|
||
<li><code>head</code> is an instance of Buffer, the first packet of the tunneling stream,
|
||
this may be empty.</li>
|
||
</ul>
|
||
<p>After this event is emitted, the request's socket will not have a <code>data</code>
|
||
event listener, meaning you will need to bind to it in order to handle data
|
||
sent to the server on that socket.
|
||
|
||
</p>
|
||
<h3>Event: 'upgrade'<span><a class="mark" href="#all_event_upgrade" id="all_event_upgrade">#</a></span></h3>
|
||
<p><code>function (request, socket, head) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted each time a client requests a http upgrade. If this event isn't
|
||
listened for, then clients requesting an upgrade will have their connections
|
||
closed.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>request</code> is the arguments for the http request, as it is in the request
|
||
event.</li>
|
||
<li><code>socket</code> is the network socket between the server and client.</li>
|
||
<li><code>head</code> is an instance of Buffer, the first packet of the upgraded stream,
|
||
this may be empty.</li>
|
||
</ul>
|
||
<p>After this event is emitted, the request's socket will not have a <code>data</code>
|
||
event listener, meaning you will need to bind to it in order to handle data
|
||
sent to the server on that socket.
|
||
|
||
</p>
|
||
<h3>Event: 'clientError'<span><a class="mark" href="#all_event_clienterror_1" id="all_event_clienterror_1">#</a></span></h3>
|
||
<p><code>function (exception) { }</code>
|
||
|
||
</p>
|
||
<p>If a client connection emits an 'error' event - it will forwarded here.
|
||
|
||
</p>
|
||
<h3>server.listen(port, [hostname], [backlog], [callback])<span><a class="mark" href="#all_server_listen_port_hostname_backlog_callback" id="all_server_listen_port_hostname_backlog_callback">#</a></span></h3>
|
||
<p>Begin accepting connections on the specified port and hostname. If the
|
||
hostname is omitted, the server will accept connections directed to any
|
||
IPv4 address (<code>INADDR_ANY</code>).
|
||
|
||
</p>
|
||
<p>To listen to a unix socket, supply a filename instead of port and hostname.
|
||
|
||
</p>
|
||
<p>Backlog is the maximum length of the queue of pending connections.
|
||
The actual length will be determined by your OS through sysctl settings such as
|
||
<code>tcp_max_syn_backlog</code> and <code>somaxconn</code> on linux. The default value of this
|
||
parameter is 511 (not 512).
|
||
|
||
</p>
|
||
<p>This function is asynchronous. The last parameter <code>callback</code> will be added as
|
||
a listener for the <a href="net.html#net_event_listening">'listening'</a> event. See also <a href="net.html#net_server_listen_port_host_backlog_callback">net.Server.listen(port)</a>.
|
||
|
||
|
||
</p>
|
||
<h3>server.listen(path, [callback])<span><a class="mark" href="#all_server_listen_path_callback_1" id="all_server_listen_path_callback_1">#</a></span></h3>
|
||
<p>Start a UNIX socket server listening for connections on the given <code>path</code>.
|
||
|
||
</p>
|
||
<p>This function is asynchronous. The last parameter <code>callback</code> will be added as
|
||
a listener for the <a href="net.html#net_event_listening">'listening'</a> event. See also <a href="net.html#net_server_listen_path_callback">net.Server.listen(path)</a>.
|
||
|
||
|
||
</p>
|
||
<h3>server.listen(handle, [callback])<span><a class="mark" href="#all_server_listen_handle_callback_1" id="all_server_listen_handle_callback_1">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>handle</code> <span class="type">Object</span></li>
|
||
<li><code>callback</code> <span class="type">Function</span></li>
|
||
</div></ul>
|
||
<p>The <code>handle</code> object can be set to either a server or socket (anything
|
||
with an underlying <code>_handle</code> member), or a <code>{fd: <n>}</code> object.
|
||
|
||
</p>
|
||
<p>This will cause the server to accept connections on the specified
|
||
handle, but it is presumed that the file descriptor or handle has
|
||
already been bound to a port or domain socket.
|
||
|
||
</p>
|
||
<p>Listening on a file descriptor is not supported on Windows.
|
||
|
||
</p>
|
||
<p>This function is asynchronous. The last parameter <code>callback</code> will be added as
|
||
a listener for the <a href="net.html#event_listening_">'listening'</a> event.
|
||
See also <a href="net.html#net_server_listen_handle_callback">net.Server.listen()</a>.
|
||
|
||
</p>
|
||
<h3>server.close([callback])<span><a class="mark" href="#all_server_close_callback_1" id="all_server_close_callback_1">#</a></span></h3>
|
||
<p>Stops the server from accepting new connections. See <a href="net.html#net_server_close_callback">net.Server.close()</a>.
|
||
|
||
|
||
</p>
|
||
<h3>server.maxHeadersCount<span><a class="mark" href="#all_server_maxheaderscount" id="all_server_maxheaderscount">#</a></span></h3>
|
||
<p>Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
|
||
no limit will be applied.
|
||
|
||
|
||
</p>
|
||
<h2>Class: http.ServerRequest<span><a class="mark" href="#all_class_http_serverrequest" id="all_class_http_serverrequest">#</a></span></h2>
|
||
<p>This object is created internally by a HTTP server -- not by
|
||
the user -- and passed as the first argument to a <code>'request'</code> listener.
|
||
|
||
</p>
|
||
<p>The request implements the <a href="stream.html#stream_readable_stream">Readable Stream</a> interface. This is an
|
||
<a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
|
||
|
||
</p>
|
||
<h3>Event: 'data'<span><a class="mark" href="#all_event_data_2" id="all_event_data_2">#</a></span></h3>
|
||
<p><code>function (chunk) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted when a piece of the message body is received. The chunk is a string if
|
||
an encoding has been set with <code>request.setEncoding()</code>, otherwise it's a
|
||
<a href="buffer.html#buffer_buffer">Buffer</a>.
|
||
|
||
</p>
|
||
<p>Note that the <strong>data will be lost</strong> if there is no listener when a
|
||
<code>ServerRequest</code> emits a <code>'data'</code> event.
|
||
|
||
</p>
|
||
<h3>Event: 'end'<span><a class="mark" href="#all_event_end_2" id="all_event_end_2">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Emitted exactly once for each request. After that, no more <code>'data'</code> events
|
||
will be emitted on the request.
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_6" id="all_event_close_6">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Indicates that the underlaying connection was terminated before
|
||
<code>response.end()</code> was called or able to flush.
|
||
|
||
</p>
|
||
<p>Just like <code>'end'</code>, this event occurs only once per request, and no more <code>'data'</code>
|
||
events will fire afterwards.
|
||
|
||
</p>
|
||
<p>Note: <code>'close'</code> can fire after <code>'end'</code>, but not vice versa.
|
||
|
||
</p>
|
||
<h3>request.method<span><a class="mark" href="#all_request_method" id="all_request_method">#</a></span></h3>
|
||
<p>The request method as a string. Read only. Example:
|
||
<code>'GET'</code>, <code>'DELETE'</code>.
|
||
|
||
|
||
</p>
|
||
<h3>request.url<span><a class="mark" href="#all_request_url" id="all_request_url">#</a></span></h3>
|
||
<p>Request URL string. This contains only the URL that is
|
||
present in the actual HTTP request. If the request is:
|
||
|
||
</p>
|
||
<pre><code>GET /status?name=ryan HTTP/1.1\r\n
|
||
Accept: text/plain\r\n
|
||
\r\n</code></pre>
|
||
<p>Then <code>request.url</code> will be:
|
||
|
||
</p>
|
||
<pre><code>'/status?name=ryan'</code></pre>
|
||
<p>If you would like to parse the URL into its parts, you can use
|
||
<code>require('url').parse(request.url)</code>. Example:
|
||
|
||
</p>
|
||
<pre><code>node> require('url').parse('/status?name=ryan')
|
||
{ href: '/status?name=ryan',
|
||
search: '?name=ryan',
|
||
query: 'name=ryan',
|
||
pathname: '/status' }</code></pre>
|
||
<p>If you would like to extract the params from the query string,
|
||
you can use the <code>require('querystring').parse</code> function, or pass
|
||
<code>true</code> as the second argument to <code>require('url').parse</code>. Example:
|
||
|
||
</p>
|
||
<pre><code>node> require('url').parse('/status?name=ryan', true)
|
||
{ href: '/status?name=ryan',
|
||
search: '?name=ryan',
|
||
query: { name: 'ryan' },
|
||
pathname: '/status' }</code></pre>
|
||
<h3>request.headers<span><a class="mark" href="#all_request_headers" id="all_request_headers">#</a></span></h3>
|
||
<p>Read only map of header names and values. Header names are lower-cased.
|
||
Example:
|
||
|
||
</p>
|
||
<pre><code>// Prints something like:
|
||
//
|
||
// { 'user-agent': 'curl/7.22.0',
|
||
// host: '127.0.0.1:8000',
|
||
// accept: '*/*' }
|
||
console.log(request.headers);</code></pre>
|
||
<h3>request.trailers<span><a class="mark" href="#all_request_trailers" id="all_request_trailers">#</a></span></h3>
|
||
<p>Read only; HTTP trailers (if present). Only populated after the 'end' event.
|
||
|
||
</p>
|
||
<h3>request.httpVersion<span><a class="mark" href="#all_request_httpversion" id="all_request_httpversion">#</a></span></h3>
|
||
<p>The HTTP protocol version as a string. Read only. Examples:
|
||
<code>'1.1'</code>, <code>'1.0'</code>.
|
||
Also <code>request.httpVersionMajor</code> is the first integer and
|
||
<code>request.httpVersionMinor</code> is the second.
|
||
|
||
|
||
</p>
|
||
<h3>request.setEncoding([encoding])<span><a class="mark" href="#all_request_setencoding_encoding" id="all_request_setencoding_encoding">#</a></span></h3>
|
||
<p>Set the encoding for the request body. See <a href="stream.html#stream_stream_setencoding_encoding">stream.setEncoding()</a> for more
|
||
information.
|
||
|
||
</p>
|
||
<h3>request.pause()<span><a class="mark" href="#all_request_pause" id="all_request_pause">#</a></span></h3>
|
||
<p>Pauses request from emitting events. Useful to throttle back an upload.
|
||
|
||
|
||
</p>
|
||
<h3>request.resume()<span><a class="mark" href="#all_request_resume" id="all_request_resume">#</a></span></h3>
|
||
<p>Resumes a paused request.
|
||
|
||
</p>
|
||
<h3>request.connection<span><a class="mark" href="#all_request_connection" id="all_request_connection">#</a></span></h3>
|
||
<p>The <code>net.Socket</code> object associated with the connection.
|
||
|
||
|
||
</p>
|
||
<p>With HTTPS support, use request.connection.verifyPeer() and
|
||
request.connection.getPeerCertificate() to obtain the client's
|
||
authentication details.
|
||
|
||
|
||
|
||
</p>
|
||
<h2>Class: http.ServerResponse<span><a class="mark" href="#all_class_http_serverresponse" id="all_class_http_serverresponse">#</a></span></h2>
|
||
<p>This object is created internally by a HTTP server--not by the user. It is
|
||
passed as the second parameter to the <code>'request'</code> event.
|
||
|
||
</p>
|
||
<p>The response implements the <a href="stream.html#stream_writable_stream">Writable Stream</a> interface. This is an
|
||
<a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_7" id="all_event_close_7">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Indicates that the underlaying connection was terminated before
|
||
<code>response.end()</code> was called or able to flush.
|
||
|
||
</p>
|
||
<h3>response.writeContinue()<span><a class="mark" href="#all_response_writecontinue" id="all_response_writecontinue">#</a></span></h3>
|
||
<p>Sends a HTTP/1.1 100 Continue message to the client, indicating that
|
||
the request body should be sent. See the <a href="#http_event_checkcontinue">'checkContinue'</a> event on <code>Server</code>.
|
||
|
||
</p>
|
||
<h3>response.writeHead(statusCode, [reasonPhrase], [headers])<span><a class="mark" href="#all_response_writehead_statuscode_reasonphrase_headers" id="all_response_writehead_statuscode_reasonphrase_headers">#</a></span></h3>
|
||
<p>Sends a response header to the request. The status code is a 3-digit HTTP
|
||
status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.
|
||
Optionally one can give a human-readable <code>reasonPhrase</code> as the second
|
||
argument.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var body = 'hello world';
|
||
response.writeHead(200, {
|
||
'Content-Length': body.length,
|
||
'Content-Type': 'text/plain' });</code></pre>
|
||
<p>This method must only be called once on a message and it must
|
||
be called before <code>response.end()</code> is called.
|
||
|
||
</p>
|
||
<p>If you call <code>response.write()</code> or <code>response.end()</code> before calling this, the
|
||
implicit/mutable headers will be calculated and call this function for you.
|
||
|
||
</p>
|
||
<p>Note: that Content-Length is given in bytes not characters. The above example
|
||
works because the string <code>'hello world'</code> contains only single byte characters.
|
||
If the body contains higher coded characters then <code>Buffer.byteLength()</code>
|
||
should be used to determine the number of bytes in a given encoding.
|
||
And Node does not check whether Content-Length and the length of the body
|
||
which has been transmitted are equal or not.
|
||
|
||
</p>
|
||
<h3>response.statusCode<span><a class="mark" href="#all_response_statuscode" id="all_response_statuscode">#</a></span></h3>
|
||
<p>When using implicit headers (not calling <code>response.writeHead()</code> explicitly), this property
|
||
controls the status code that will be sent to the client when the headers get
|
||
flushed.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>response.statusCode = 404;</code></pre>
|
||
<p>After response header was sent to the client, this property indicates the
|
||
status code which was sent out.
|
||
|
||
</p>
|
||
<h3>response.setHeader(name, value)<span><a class="mark" href="#all_response_setheader_name_value" id="all_response_setheader_name_value">#</a></span></h3>
|
||
<p>Sets a single header value for implicit headers. If this header already exists
|
||
in the to-be-sent headers, its value will be replaced. Use an array of strings
|
||
here if you need to send multiple headers with the same name.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>response.setHeader("Content-Type", "text/html");</code></pre>
|
||
<p>or
|
||
|
||
</p>
|
||
<pre><code>response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);</code></pre>
|
||
<h3>response.sendDate<span><a class="mark" href="#all_response_senddate" id="all_response_senddate">#</a></span></h3>
|
||
<p>When true, the Date header will be automatically generated and sent in
|
||
the response if it is not already present in the headers. Defaults to true.
|
||
|
||
</p>
|
||
<p>This should only be disabled for testing; HTTP requires the Date header
|
||
in responses.
|
||
|
||
</p>
|
||
<h3>response.getHeader(name)<span><a class="mark" href="#all_response_getheader_name" id="all_response_getheader_name">#</a></span></h3>
|
||
<p>Reads out a header that's already been queued but not sent to the client. Note
|
||
that the name is case insensitive. This can only be called before headers get
|
||
implicitly flushed.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var contentType = response.getHeader('content-type');</code></pre>
|
||
<h3>response.removeHeader(name)<span><a class="mark" href="#all_response_removeheader_name" id="all_response_removeheader_name">#</a></span></h3>
|
||
<p>Removes a header that's queued for implicit sending.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>response.removeHeader("Content-Encoding");</code></pre>
|
||
<h3>response.write(chunk, [encoding])<span><a class="mark" href="#all_response_write_chunk_encoding" id="all_response_write_chunk_encoding">#</a></span></h3>
|
||
<p>If this method is called and <code>response.writeHead()</code> has not been called, it will
|
||
switch to implicit header mode and flush the implicit headers.
|
||
|
||
</p>
|
||
<p>This sends a chunk of the response body. This method may
|
||
be called multiple times to provide successive parts of the body.
|
||
|
||
</p>
|
||
<p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string,
|
||
the second parameter specifies how to encode it into a byte stream.
|
||
By default the <code>encoding</code> is <code>'utf8'</code>.
|
||
|
||
</p>
|
||
<p><strong>Note</strong>: This is the raw HTTP body and has nothing to do with
|
||
higher-level multi-part body encodings that may be used.
|
||
|
||
</p>
|
||
<p>The first time <code>response.write()</code> is called, it will send the buffered
|
||
header information and the first body to the client. The second time
|
||
<code>response.write()</code> is called, Node assumes you're going to be streaming
|
||
data, and sends that separately. That is, the response is buffered up to the
|
||
first chunk of body.
|
||
|
||
</p>
|
||
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
|
||
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
|
||
<code>'drain'</code> will be emitted when the buffer is again free.
|
||
|
||
</p>
|
||
<h3>response.addTrailers(headers)<span><a class="mark" href="#all_response_addtrailers_headers" id="all_response_addtrailers_headers">#</a></span></h3>
|
||
<p>This method adds HTTP trailing headers (a header but at the end of the
|
||
message) to the response.
|
||
|
||
</p>
|
||
<p>Trailers will <strong>only</strong> be emitted if chunked encoding is used for the
|
||
response; if it is not (e.g., if the request was HTTP/1.0), they will
|
||
be silently discarded.
|
||
|
||
</p>
|
||
<p>Note that HTTP requires the <code>Trailer</code> header to be sent if you intend to
|
||
emit trailers, with a list of the header fields in its value. E.g.,
|
||
|
||
</p>
|
||
<pre><code>response.writeHead(200, { 'Content-Type': 'text/plain',
|
||
'Trailer': 'Content-MD5' });
|
||
response.write(fileData);
|
||
response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
|
||
response.end();</code></pre>
|
||
<h3>response.end([data], [encoding])<span><a class="mark" href="#all_response_end_data_encoding" id="all_response_end_data_encoding">#</a></span></h3>
|
||
<p>This method signals to the server that all of the response headers and body
|
||
have been sent; that server should consider this message complete.
|
||
The method, <code>response.end()</code>, MUST be called on each
|
||
response.
|
||
|
||
</p>
|
||
<p>If <code>data</code> is specified, it is equivalent to calling <code>response.write(data, encoding)</code>
|
||
followed by <code>response.end()</code>.
|
||
|
||
|
||
</p>
|
||
<h2>http.request(options, callback)<span><a class="mark" href="#all_http_request_options_callback" id="all_http_request_options_callback">#</a></span></h2>
|
||
<p>Node maintains several connections per server to make HTTP requests.
|
||
This function allows one to transparently issue requests.
|
||
|
||
</p>
|
||
<p><code>options</code> can be an object or a string. If <code>options</code> is a string, it is
|
||
automatically parsed with <a href="url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost">url.parse()</a>.
|
||
|
||
</p>
|
||
<p>Options:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>host</code>: A domain name or IP address of the server to issue the request to.
|
||
Defaults to <code>'localhost'</code>.</li>
|
||
<li><code>hostname</code>: To support <code>url.parse()</code> <code>hostname</code> is preferred over <code>host</code></li>
|
||
<li><code>port</code>: Port of remote server. Defaults to 80.</li>
|
||
<li><code>localAddress</code>: Local interface to bind for network connections.</li>
|
||
<li><code>socketPath</code>: Unix Domain Socket (use one of host:port or socketPath)</li>
|
||
<li><code>method</code>: A string specifying the HTTP request method. Defaults to <code>'GET'</code>.</li>
|
||
<li><code>path</code>: Request path. Defaults to <code>'/'</code>. Should include query string if any.
|
||
E.G. <code>'/index.html?page=12'</code></li>
|
||
<li><code>headers</code>: An object containing request headers.</li>
|
||
<li><code>auth</code>: Basic authentication i.e. <code>'user:password'</code> to compute an
|
||
Authorization header.</li>
|
||
<li><code>agent</code>: Controls <a href="#https_class_https_agent">Agent</a> behavior. When an Agent is used request will
|
||
default to <code>Connection: keep-alive</code>. Possible values:<ul>
|
||
<li><code>undefined</code> (default): use <a href="#http_http_globalagent">global Agent</a> for this host and port.</li>
|
||
<li><code>Agent</code> object: explicitly use the passed in <code>Agent</code>.</li>
|
||
<li><code>false</code>: opts out of connection pooling with an Agent, defaults request to
|
||
<code>Connection: close</code>.</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
<p><code>http.request()</code> returns an instance of the <code>http.ClientRequest</code>
|
||
class. The <code>ClientRequest</code> instance is a writable stream. If one needs to
|
||
upload a file with a POST request, then write to the <code>ClientRequest</code> object.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var options = {
|
||
host: 'www.google.com',
|
||
port: 80,
|
||
path: '/upload',
|
||
method: 'POST'
|
||
};
|
||
|
||
var req = http.request(options, function(res) {
|
||
console.log('STATUS: ' + res.statusCode);
|
||
console.log('HEADERS: ' + JSON.stringify(res.headers));
|
||
res.setEncoding('utf8');
|
||
res.on('data', function (chunk) {
|
||
console.log('BODY: ' + chunk);
|
||
});
|
||
});
|
||
|
||
req.on('error', function(e) {
|
||
console.log('problem with request: ' + e.message);
|
||
});
|
||
|
||
// write data to request body
|
||
req.write('data\n');
|
||
req.write('data\n');
|
||
req.end();</code></pre>
|
||
<p>Note that in the example <code>req.end()</code> was called. With <code>http.request()</code> one
|
||
must always call <code>req.end()</code> to signify that you're done with the request -
|
||
even if there is no data being written to the request body.
|
||
|
||
</p>
|
||
<p>If any error is encountered during the request (be that with DNS resolution,
|
||
TCP level errors, or actual HTTP parse errors) an <code>'error'</code> event is emitted
|
||
on the returned request object.
|
||
|
||
</p>
|
||
<p>There are a few special headers that should be noted.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p>Sending a 'Connection: keep-alive' will notify Node that the connection to
|
||
the server should be persisted until the next request.</p>
|
||
</li>
|
||
<li><p>Sending a 'Content-length' header will disable the default chunked encoding.</p>
|
||
</li>
|
||
<li><p>Sending an 'Expect' header will immediately send the request headers.
|
||
Usually, when sending 'Expect: 100-continue', you should both set a timeout
|
||
and listen for the <code>continue</code> event. See RFC2616 Section 8.2.3 for more
|
||
information.</p>
|
||
</li>
|
||
<li><p>Sending an Authorization header will override using the <code>auth</code> option
|
||
to compute basic authentication.</p>
|
||
</li>
|
||
</ul>
|
||
<h2>http.get(options, callback)<span><a class="mark" href="#all_http_get_options_callback" id="all_http_get_options_callback">#</a></span></h2>
|
||
<p>Since most requests are GET requests without bodies, Node provides this
|
||
convenience method. The only difference between this method and <code>http.request()</code>
|
||
is that it sets the method to GET and calls <code>req.end()</code> automatically.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>http.get("http://www.google.com/index.html", function(res) {
|
||
console.log("Got response: " + res.statusCode);
|
||
}).on('error', function(e) {
|
||
console.log("Got error: " + e.message);
|
||
});</code></pre>
|
||
<h2>Class: http.Agent<span><a class="mark" href="#all_class_http_agent" id="all_class_http_agent">#</a></span></h2>
|
||
<p>In node 0.5.3+ there is a new implementation of the HTTP Agent which is used
|
||
for pooling sockets used in HTTP client requests.
|
||
|
||
</p>
|
||
<p>Previously, a single agent instance helped pool for a single host+port. The
|
||
current implementation now holds sockets for any number of hosts.
|
||
|
||
</p>
|
||
<p>The current HTTP Agent also defaults client requests to using
|
||
Connection:keep-alive. If no pending HTTP requests are waiting on a socket
|
||
to become free the socket is closed. This means that node's pool has the
|
||
benefit of keep-alive when under load but still does not require developers
|
||
to manually close the HTTP clients using keep-alive.
|
||
|
||
</p>
|
||
<p>Sockets are removed from the agent's pool when the socket emits either a
|
||
"close" event or a special "agentRemove" event. This means that if you intend
|
||
to keep one HTTP request open for a long time and don't want it to stay in the
|
||
pool you can do something along the lines of:
|
||
|
||
</p>
|
||
<pre><code>http.get(options, function(res) {
|
||
// Do stuff
|
||
}).on("socket", function (socket) {
|
||
socket.emit("agentRemove");
|
||
});</code></pre>
|
||
<p>Alternatively, you could just opt out of pooling entirely using <code>agent:false</code>:
|
||
|
||
</p>
|
||
<pre><code>http.get({host:'localhost', port:80, path:'/', agent:false}, function (res) {
|
||
// Do stuff
|
||
})</code></pre>
|
||
<h3>agent.maxSockets<span><a class="mark" href="#all_agent_maxsockets" id="all_agent_maxsockets">#</a></span></h3>
|
||
<p>By default set to 5. Determines how many concurrent sockets the agent can have
|
||
open per host.
|
||
|
||
</p>
|
||
<h3>agent.sockets<span><a class="mark" href="#all_agent_sockets" id="all_agent_sockets">#</a></span></h3>
|
||
<p>An object which contains arrays of sockets currently in use by the Agent. Do not
|
||
modify.
|
||
|
||
</p>
|
||
<h3>agent.requests<span><a class="mark" href="#all_agent_requests" id="all_agent_requests">#</a></span></h3>
|
||
<p>An object which contains queues of requests that have not yet been assigned to
|
||
sockets. Do not modify.
|
||
|
||
</p>
|
||
<h2>http.globalAgent<span><a class="mark" href="#all_http_globalagent" id="all_http_globalagent">#</a></span></h2>
|
||
<p>Global instance of Agent which is used as the default for all http client
|
||
requests.
|
||
|
||
|
||
</p>
|
||
<h2>Class: http.ClientRequest<span><a class="mark" href="#all_class_http_clientrequest" id="all_class_http_clientrequest">#</a></span></h2>
|
||
<p>This object is created internally and returned from <code>http.request()</code>. It
|
||
represents an <em>in-progress</em> request whose header has already been queued. The
|
||
header is still mutable using the <code>setHeader(name, value)</code>, <code>getHeader(name)</code>,
|
||
<code>removeHeader(name)</code> API. The actual header will be sent along with the first
|
||
data chunk or when closing the connection.
|
||
|
||
</p>
|
||
<p>To get the response, add a listener for <code>'response'</code> to the request object.
|
||
<code>'response'</code> will be emitted from the request object when the response
|
||
headers have been received. The <code>'response'</code> event is executed with one
|
||
argument which is an instance of <code>http.ClientResponse</code>.
|
||
|
||
</p>
|
||
<p>During the <code>'response'</code> event, one can add listeners to the
|
||
response object; particularly to listen for the <code>'data'</code> event. Note that
|
||
the <code>'response'</code> event is called before any part of the response body is received,
|
||
so there is no need to worry about racing to catch the first part of the
|
||
body. As long as a listener for <code>'data'</code> is added during the <code>'response'</code>
|
||
event, the entire body will be caught.
|
||
|
||
|
||
</p>
|
||
<pre><code>// Good
|
||
request.on('response', function (response) {
|
||
response.on('data', function (chunk) {
|
||
console.log('BODY: ' + chunk);
|
||
});
|
||
});
|
||
|
||
// Bad - misses all or part of the body
|
||
request.on('response', function (response) {
|
||
setTimeout(function () {
|
||
response.on('data', function (chunk) {
|
||
console.log('BODY: ' + chunk);
|
||
});
|
||
}, 10);
|
||
});</code></pre>
|
||
<p>Note: Node does not check whether Content-Length and the length of the body
|
||
which has been transmitted are equal or not.
|
||
|
||
</p>
|
||
<p>The request implements the <a href="stream.html#stream_writable_stream">Writable Stream</a> interface. This is an
|
||
<a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
|
||
|
||
</p>
|
||
<h3>Event 'response'<span><a class="mark" href="#all_event_response" id="all_event_response">#</a></span></h3>
|
||
<p><code>function (response) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted when a response is received to this request. This event is emitted only
|
||
once. The <code>response</code> argument will be an instance of <code>http.ClientResponse</code>.
|
||
|
||
</p>
|
||
<p>Options:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>host</code>: A domain name or IP address of the server to issue the request to.</li>
|
||
<li><code>port</code>: Port of remote server.</li>
|
||
<li><code>socketPath</code>: Unix Domain Socket (use one of host:port or socketPath)</li>
|
||
</ul>
|
||
<h3>Event: 'socket'<span><a class="mark" href="#all_event_socket" id="all_event_socket">#</a></span></h3>
|
||
<p><code>function (socket) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted after a socket is assigned to this request.
|
||
|
||
</p>
|
||
<h3>Event: 'connect'<span><a class="mark" href="#all_event_connect_2" id="all_event_connect_2">#</a></span></h3>
|
||
<p><code>function (response, socket, head) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted each time a server responds to a request with a CONNECT method. If this
|
||
event isn't being listened for, clients receiving a CONNECT method will have
|
||
their connections closed.
|
||
|
||
</p>
|
||
<p>A client server pair that show you how to listen for the <code>connect</code> event.
|
||
|
||
</p>
|
||
<pre><code>var http = require('http');
|
||
var net = require('net');
|
||
var url = require('url');
|
||
|
||
// Create an HTTP tunneling proxy
|
||
var proxy = http.createServer(function (req, res) {
|
||
res.writeHead(200, {'Content-Type': 'text/plain'});
|
||
res.end('okay');
|
||
});
|
||
proxy.on('connect', function(req, cltSocket, head) {
|
||
// connect to an origin server
|
||
var srvUrl = url.parse('http://' + req.url);
|
||
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {
|
||
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
|
||
'Proxy-agent: Node-Proxy\r\n' +
|
||
'\r\n');
|
||
srvSocket.write(head);
|
||
srvSocket.pipe(cltSocket);
|
||
cltSocket.pipe(srvSocket);
|
||
});
|
||
});
|
||
|
||
// now that proxy is running
|
||
proxy.listen(1337, '127.0.0.1', function() {
|
||
|
||
// make a request to a tunneling proxy
|
||
var options = {
|
||
port: 1337,
|
||
host: '127.0.0.1',
|
||
method: 'CONNECT',
|
||
path: 'www.google.com:80'
|
||
};
|
||
|
||
var req = http.request(options);
|
||
req.end();
|
||
|
||
req.on('connect', function(res, socket, head) {
|
||
console.log('got connected!');
|
||
|
||
// make a request over an HTTP tunnel
|
||
socket.write('GET / HTTP/1.1\r\n' +
|
||
'Host: www.google.com:80\r\n' +
|
||
'Connection: close\r\n' +
|
||
'\r\n');
|
||
socket.on('data', function(chunk) {
|
||
console.log(chunk.toString());
|
||
});
|
||
socket.on('end', function() {
|
||
proxy.close();
|
||
});
|
||
});
|
||
});</code></pre>
|
||
<h3>Event: 'upgrade'<span><a class="mark" href="#all_event_upgrade_1" id="all_event_upgrade_1">#</a></span></h3>
|
||
<p><code>function (response, socket, head) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted each time a server responds to a request with an upgrade. If this
|
||
event isn't being listened for, clients receiving an upgrade header will have
|
||
their connections closed.
|
||
|
||
</p>
|
||
<p>A client server pair that show you how to listen for the <code>upgrade</code> event.
|
||
|
||
</p>
|
||
<pre><code>var http = require('http');
|
||
|
||
// Create an HTTP server
|
||
var srv = http.createServer(function (req, res) {
|
||
res.writeHead(200, {'Content-Type': 'text/plain'});
|
||
res.end('okay');
|
||
});
|
||
srv.on('upgrade', function(req, socket, head) {
|
||
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
|
||
'Upgrade: WebSocket\r\n' +
|
||
'Connection: Upgrade\r\n' +
|
||
'\r\n');
|
||
|
||
socket.pipe(socket); // echo back
|
||
});
|
||
|
||
// now that server is running
|
||
srv.listen(1337, '127.0.0.1', function() {
|
||
|
||
// make a request
|
||
var options = {
|
||
port: 1337,
|
||
host: '127.0.0.1',
|
||
headers: {
|
||
'Connection': 'Upgrade',
|
||
'Upgrade': 'websocket'
|
||
}
|
||
};
|
||
|
||
var req = http.request(options);
|
||
req.end();
|
||
|
||
req.on('upgrade', function(res, socket, upgradeHead) {
|
||
console.log('got upgraded!');
|
||
socket.end();
|
||
process.exit(0);
|
||
});
|
||
});</code></pre>
|
||
<h3>Event: 'continue'<span><a class="mark" href="#all_event_continue" id="all_event_continue">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Emitted when the server sends a '100 Continue' HTTP response, usually because
|
||
the request contained 'Expect: 100-continue'. This is an instruction that
|
||
the client should send the request body.
|
||
|
||
</p>
|
||
<h3>request.write(chunk, [encoding])<span><a class="mark" href="#all_request_write_chunk_encoding" id="all_request_write_chunk_encoding">#</a></span></h3>
|
||
<p>Sends a chunk of the body. By calling this method
|
||
many times, the user can stream a request body to a
|
||
server--in that case it is suggested to use the
|
||
<code>['Transfer-Encoding', 'chunked']</code> header line when
|
||
creating the request.
|
||
|
||
</p>
|
||
<p>The <code>chunk</code> argument should be a <a href="buffer.html#buffer_buffer">Buffer</a> or a string.
|
||
|
||
</p>
|
||
<p>The <code>encoding</code> argument is optional and only applies when <code>chunk</code> is a string.
|
||
Defaults to <code>'utf8'</code>.
|
||
|
||
|
||
</p>
|
||
<h3>request.end([data], [encoding])<span><a class="mark" href="#all_request_end_data_encoding" id="all_request_end_data_encoding">#</a></span></h3>
|
||
<p>Finishes sending the request. If any parts of the body are
|
||
unsent, it will flush them to the stream. If the request is
|
||
chunked, this will send the terminating <code>'0\r\n\r\n'</code>.
|
||
|
||
</p>
|
||
<p>If <code>data</code> is specified, it is equivalent to calling
|
||
<code>request.write(data, encoding)</code> followed by <code>request.end()</code>.
|
||
|
||
</p>
|
||
<h3>request.abort()<span><a class="mark" href="#all_request_abort" id="all_request_abort">#</a></span></h3>
|
||
<p>Aborts a request. (New since v0.3.8.)
|
||
|
||
</p>
|
||
<h3>request.setTimeout(timeout, [callback])<span><a class="mark" href="#all_request_settimeout_timeout_callback" id="all_request_settimeout_timeout_callback">#</a></span></h3>
|
||
<p>Once a socket is assigned to this request and is connected
|
||
<a href="net.html#net_socket_settimeout_timeout_callback">socket.setTimeout()</a> will be called.
|
||
|
||
</p>
|
||
<h3>request.setNoDelay([noDelay])<span><a class="mark" href="#all_request_setnodelay_nodelay" id="all_request_setnodelay_nodelay">#</a></span></h3>
|
||
<p>Once a socket is assigned to this request and is connected
|
||
<a href="net.html#net_socket_setnodelay_nodelay">socket.setNoDelay()</a> will be called.
|
||
|
||
</p>
|
||
<h3>request.setSocketKeepAlive([enable], [initialDelay])<span><a class="mark" href="#all_request_setsocketkeepalive_enable_initialdelay" id="all_request_setsocketkeepalive_enable_initialdelay">#</a></span></h3>
|
||
<p>Once a socket is assigned to this request and is connected
|
||
<a href="net.html#net_socket_setkeepalive_enable_initialdelay">socket.setKeepAlive()</a> will be called.
|
||
|
||
</p>
|
||
<h2>http.ClientResponse<span><a class="mark" href="#all_http_clientresponse" id="all_http_clientresponse">#</a></span></h2>
|
||
<p>This object is created when making a request with <code>http.request()</code>. It is
|
||
passed to the <code>'response'</code> event of the request object.
|
||
|
||
</p>
|
||
<p>The response implements the <a href="stream.html#stream_readable_stream">Readable Stream</a> interface. This is an
|
||
<a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
|
||
|
||
|
||
</p>
|
||
<h3>Event: 'data'<span><a class="mark" href="#all_event_data_3" id="all_event_data_3">#</a></span></h3>
|
||
<p><code>function (chunk) { }</code>
|
||
|
||
</p>
|
||
<p>Emitted when a piece of the message body is received.
|
||
|
||
</p>
|
||
<p>Note that the <strong>data will be lost</strong> if there is no listener when a
|
||
<code>ClientResponse</code> emits a <code>'data'</code> event.
|
||
|
||
|
||
</p>
|
||
<h3>Event: 'end'<span><a class="mark" href="#all_event_end_3" id="all_event_end_3">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Emitted exactly once for each response. After that, no more <code>'data'</code> events
|
||
will be emitted on the response.
|
||
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_8" id="all_event_close_8">#</a></span></h3>
|
||
<p><code>function () { }</code>
|
||
|
||
</p>
|
||
<p>Indicates that the underlaying connection was terminated before
|
||
<code>response.end()</code> was called or able to flush.
|
||
|
||
</p>
|
||
<p>Just like <code>'end'</code>, this event occurs only once per response, and no more
|
||
<code>'data'</code> events will fire afterwards. See [http.ServerResponse][]'s <code>'close'</code>
|
||
event for more information.
|
||
|
||
</p>
|
||
<p>Note: <code>'close'</code> can fire after <code>'end'</code>, but not vice versa.
|
||
|
||
|
||
</p>
|
||
<h3>response.statusCode<span><a class="mark" href="#all_response_statuscode_1" id="all_response_statuscode_1">#</a></span></h3>
|
||
<p>The 3-digit HTTP response status code. E.G. <code>404</code>.
|
||
|
||
</p>
|
||
<h3>response.httpVersion<span><a class="mark" href="#all_response_httpversion" id="all_response_httpversion">#</a></span></h3>
|
||
<p>The HTTP version of the connected-to server. Probably either
|
||
<code>'1.1'</code> or <code>'1.0'</code>.
|
||
Also <code>response.httpVersionMajor</code> is the first integer and
|
||
<code>response.httpVersionMinor</code> is the second.
|
||
|
||
</p>
|
||
<h3>response.headers<span><a class="mark" href="#all_response_headers" id="all_response_headers">#</a></span></h3>
|
||
<p>The response headers object.
|
||
|
||
</p>
|
||
<h3>response.trailers<span><a class="mark" href="#all_response_trailers" id="all_response_trailers">#</a></span></h3>
|
||
<p>The response trailers object. Only populated after the 'end' event.
|
||
|
||
</p>
|
||
<h3>response.setEncoding([encoding])<span><a class="mark" href="#all_response_setencoding_encoding" id="all_response_setencoding_encoding">#</a></span></h3>
|
||
<p>Set the encoding for the response body. See <a href="stream.html#stream_stream_setencoding_encoding">stream.setEncoding()</a> for more
|
||
information.
|
||
|
||
</p>
|
||
<h3>response.pause()<span><a class="mark" href="#all_response_pause" id="all_response_pause">#</a></span></h3>
|
||
<p>Pauses response from emitting events. Useful to throttle back a download.
|
||
|
||
</p>
|
||
<h3>response.resume()<span><a class="mark" href="#all_response_resume" id="all_response_resume">#</a></span></h3>
|
||
<p>Resumes a paused response.
|
||
|
||
</p>
|
||
<h1>HTTPS<span><a class="mark" href="#all_https" id="all_https">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a
|
||
separate module.
|
||
|
||
</p>
|
||
<h2>Class: https.Server<span><a class="mark" href="#all_class_https_server" id="all_class_https_server">#</a></span></h2>
|
||
<p>This class is a subclass of <code>tls.Server</code> and emits events same as
|
||
<code>http.Server</code>. See <code>http.Server</code> for more information.
|
||
|
||
</p>
|
||
<h2>https.createServer(options, [requestListener])<span><a class="mark" href="#all_https_createserver_options_requestlistener" id="all_https_createserver_options_requestlistener">#</a></span></h2>
|
||
<p>Returns a new HTTPS web server object. The <code>options</code> is similar to
|
||
<a href="tls.html#tls_tls_createserver_options_secureconnectionlistener">tls.createServer()</a>. The <code>requestListener</code> is a function which is
|
||
automatically added to the <code>'request'</code> event.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>// curl -k https://localhost:8000/
|
||
var https = require('https');
|
||
var fs = require('fs');
|
||
|
||
var options = {
|
||
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
|
||
};
|
||
|
||
https.createServer(options, function (req, res) {
|
||
res.writeHead(200);
|
||
res.end("hello world\n");
|
||
}).listen(8000);</code></pre>
|
||
<p>Or
|
||
|
||
</p>
|
||
<pre><code>var https = require('https');
|
||
var fs = require('fs');
|
||
|
||
var options = {
|
||
pfx: fs.readFileSync('server.pfx')
|
||
};
|
||
|
||
https.createServer(options, function (req, res) {
|
||
res.writeHead(200);
|
||
res.end("hello world\n");
|
||
}).listen(8000);</code></pre>
|
||
<h3>server.listen(port, [host], [backlog], [callback])<span><a class="mark" href="#all_server_listen_port_host_backlog_callback_1" id="all_server_listen_port_host_backlog_callback_1">#</a></span></h3>
|
||
<h3>server.listen(path, [callback])<span><a class="mark" href="#all_server_listen_path_callback_2" id="all_server_listen_path_callback_2">#</a></span></h3>
|
||
<h3>server.listen(handle, [callback])<span><a class="mark" href="#all_server_listen_handle_callback_2" id="all_server_listen_handle_callback_2">#</a></span></h3>
|
||
<p>See <a href="http.html#http_server_listen_port_hostname_backlog_callback">http.listen()</a> for details.
|
||
|
||
</p>
|
||
<h3>server.close([callback])<span><a class="mark" href="#all_server_close_callback_2" id="all_server_close_callback_2">#</a></span></h3>
|
||
<p>See <a href="http.html#http_server_close_callback">http.close()</a> for details.
|
||
|
||
</p>
|
||
<h2>https.request(options, callback)<span><a class="mark" href="#all_https_request_options_callback" id="all_https_request_options_callback">#</a></span></h2>
|
||
<p>Makes a request to a secure web server.
|
||
|
||
</p>
|
||
<p><code>options</code> can be an object or a string. If <code>options</code> is a string, it is
|
||
automatically parsed with <a href="url.html#url.parse">url.parse()</a>.
|
||
|
||
</p>
|
||
<p>All options from <a href="http.html#http_http_request_options_callback">http.request()</a> are valid.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var https = require('https');
|
||
|
||
var options = {
|
||
host: 'encrypted.google.com',
|
||
port: 443,
|
||
path: '/',
|
||
method: 'GET'
|
||
};
|
||
|
||
var req = https.request(options, function(res) {
|
||
console.log("statusCode: ", res.statusCode);
|
||
console.log("headers: ", res.headers);
|
||
|
||
res.on('data', function(d) {
|
||
process.stdout.write(d);
|
||
});
|
||
});
|
||
req.end();
|
||
|
||
req.on('error', function(e) {
|
||
console.error(e);
|
||
});</code></pre>
|
||
<p>The options argument has the following options
|
||
|
||
</p>
|
||
<ul>
|
||
<li>host: IP or domain of host to make request to. Defaults to <code>'localhost'</code>.</li>
|
||
<li>port: port of host to request to. Defaults to 443.</li>
|
||
<li>path: Path to request. Default <code>'/'</code>.</li>
|
||
<li><p>method: HTTP request method. Default <code>'GET'</code>.</p>
|
||
</li>
|
||
<li><p><code>host</code>: A domain name or IP address of the server to issue the request to.
|
||
Defaults to <code>'localhost'</code>.</p>
|
||
</li>
|
||
<li><code>hostname</code>: To support <code>url.parse()</code> <code>hostname</code> is preferred over <code>host</code></li>
|
||
<li><code>port</code>: Port of remote server. Defaults to 443.</li>
|
||
<li><code>method</code>: A string specifying the HTTP request method. Defaults to <code>'GET'</code>.</li>
|
||
<li><code>path</code>: Request path. Defaults to <code>'/'</code>. Should include query string if any.
|
||
E.G. <code>'/index.html?page=12'</code></li>
|
||
<li><code>headers</code>: An object containing request headers.</li>
|
||
<li><code>auth</code>: Basic authentication i.e. <code>'user:password'</code> to compute an
|
||
Authorization header.</li>
|
||
<li><code>agent</code>: Controls <a href="#https_class_https_agent">Agent</a> behavior. When an Agent is used request will
|
||
default to <code>Connection: keep-alive</code>. Possible values:<ul>
|
||
<li><code>undefined</code> (default): use <a href="#https_https_globalagent">globalAgent</a> for this host and port.</li>
|
||
<li><code>Agent</code> object: explicitly use the passed in <code>Agent</code>.</li>
|
||
<li><code>false</code>: opts out of connection pooling with an Agent, defaults request to
|
||
<code>Connection: close</code>.</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
<p>The following options from <a href="tls.html#tls_tls_connect_options_secureconnectlistener">tls.connect()</a> can also be specified. However, a
|
||
<a href="#https_https_globalagent">globalAgent</a> silently ignores these.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>pfx</code>: Certificate, Private key and CA certificates to use for SSL. Default <code>null</code>.</li>
|
||
<li><code>key</code>: Private key to use for SSL. Default <code>null</code>.</li>
|
||
<li><code>passphrase</code>: A string of passphrase for the private key or pfx. Default <code>null</code>.</li>
|
||
<li><code>cert</code>: Public x509 certificate to use. Default <code>null</code>.</li>
|
||
<li><code>ca</code>: An authority certificate or array of authority certificates to check
|
||
the remote host against.</li>
|
||
<li><code>ciphers</code>: A string describing the ciphers to use or exclude. Consult
|
||
<a href="http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT</a> for
|
||
details on the format.</li>
|
||
<li><code>rejectUnauthorized</code>: If <code>true</code>, the server certificate is verified against
|
||
the list of supplied CAs. An <code>'error'</code> event is emitted if verification
|
||
fails. Verification happens at the connection level, <em>before</em> the HTTP
|
||
request is sent. Default <code>false</code>.</li>
|
||
</ul>
|
||
<p>In order to specify these options, use a custom <code>Agent</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var options = {
|
||
host: 'encrypted.google.com',
|
||
port: 443,
|
||
path: '/',
|
||
method: 'GET',
|
||
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
|
||
};
|
||
options.agent = new https.Agent(options);
|
||
|
||
var req = https.request(options, function(res) {
|
||
...
|
||
}</code></pre>
|
||
<p>Or does not use an <code>Agent</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var options = {
|
||
host: 'encrypted.google.com',
|
||
port: 443,
|
||
path: '/',
|
||
method: 'GET',
|
||
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
|
||
agent: false
|
||
};
|
||
|
||
var req = https.request(options, function(res) {
|
||
...
|
||
}</code></pre>
|
||
<h2>https.get(options, callback)<span><a class="mark" href="#all_https_get_options_callback" id="all_https_get_options_callback">#</a></span></h2>
|
||
<p>Like <code>http.get()</code> but for HTTPS.
|
||
|
||
</p>
|
||
<p><code>options</code> can be an object or a string. If <code>options</code> is a string, it is
|
||
automatically parsed with <a href="url.html#url.parse">url.parse()</a>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var https = require('https');
|
||
|
||
https.get('https://encrypted.google.com/', function(res) {
|
||
console.log("statusCode: ", res.statusCode);
|
||
console.log("headers: ", res.headers);
|
||
|
||
res.on('data', function(d) {
|
||
process.stdout.write(d);
|
||
});
|
||
|
||
}).on('error', function(e) {
|
||
console.error(e);
|
||
});</code></pre>
|
||
<h2>Class: https.Agent<span><a class="mark" href="#all_class_https_agent" id="all_class_https_agent">#</a></span></h2>
|
||
<p>An Agent object for HTTPS similar to <a href="http.html#http_class_http_agent">http.Agent</a>. See [https.request()][]
|
||
for more information.
|
||
|
||
|
||
</p>
|
||
<h2>https.globalAgent<span><a class="mark" href="#all_https_globalagent" id="all_https_globalagent">#</a></span></h2>
|
||
<p>Global instance of <a href="#https_class_https_agent">https.Agent</a> for all HTTPS client requests.
|
||
|
||
</p>
|
||
<h1>URL<span><a class="mark" href="#all_url" id="all_url">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>This module has utilities for URL resolution and parsing.
|
||
Call <code>require('url')</code> to use it.
|
||
|
||
</p>
|
||
<p>Parsed URL objects have some or all of the following fields, depending on
|
||
whether or not they exist in the URL string. Any parts that are not in the URL
|
||
string will not be in the parsed object. Examples are shown for the URL
|
||
|
||
</p>
|
||
<p><code>'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'</code>
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>href</code>: The full URL that was originally parsed. Both the protocol and host are lowercased.</p>
|
||
<p> Example: <code>'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'</code></p>
|
||
</li>
|
||
<li><p><code>protocol</code>: The request protocol, lowercased.</p>
|
||
<p> Example: <code>'http:'</code></p>
|
||
</li>
|
||
<li><p><code>host</code>: The full lowercased host portion of the URL, including port
|
||
information.</p>
|
||
<p> Example: <code>'host.com:8080'</code></p>
|
||
</li>
|
||
<li><p><code>auth</code>: The authentication information portion of a URL.</p>
|
||
<p> Example: <code>'user:pass'</code></p>
|
||
</li>
|
||
<li><p><code>hostname</code>: Just the lowercased hostname portion of the host.</p>
|
||
<p> Example: <code>'host.com'</code></p>
|
||
</li>
|
||
<li><p><code>port</code>: The port number portion of the host.</p>
|
||
<p> Example: <code>'8080'</code></p>
|
||
</li>
|
||
<li><p><code>pathname</code>: The path section of the URL, that comes after the host and
|
||
before the query, including the initial slash if present.</p>
|
||
<p> Example: <code>'/p/a/t/h'</code></p>
|
||
</li>
|
||
<li><p><code>search</code>: The 'query string' portion of the URL, including the leading
|
||
question mark.</p>
|
||
<p> Example: <code>'?query=string'</code></p>
|
||
</li>
|
||
<li><p><code>path</code>: Concatenation of <code>pathname</code> and <code>search</code>.</p>
|
||
<p> Example: <code>'/p/a/t/h?query=string'</code></p>
|
||
</li>
|
||
<li><p><code>query</code>: Either the 'params' portion of the query string, or a
|
||
querystring-parsed object.</p>
|
||
<p> Example: <code>'query=string'</code> or <code>{'query':'string'}</code></p>
|
||
</li>
|
||
<li><p><code>hash</code>: The 'fragment' portion of the URL including the pound-sign.</p>
|
||
<p> Example: <code>'#hash'</code></p>
|
||
</li>
|
||
</ul>
|
||
<p>The following methods are provided by the URL module:
|
||
|
||
</p>
|
||
<h2>url.parse(urlStr, [parseQueryString], [slashesDenoteHost])<span><a class="mark" href="#all_url_parse_urlstr_parsequerystring_slashesdenotehost" id="all_url_parse_urlstr_parsequerystring_slashesdenotehost">#</a></span></h2>
|
||
<p>Take a URL string, and return an object.
|
||
|
||
</p>
|
||
<p>Pass <code>true</code> as the second argument to also parse
|
||
the query string using the <code>querystring</code> module.
|
||
Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<p>Pass <code>true</code> as the third argument to treat <code>//foo/bar</code> as
|
||
<code>{ host: 'foo', pathname: '/bar' }</code> rather than
|
||
<code>{ pathname: '//foo/bar' }</code>. Defaults to <code>false</code>.
|
||
|
||
</p>
|
||
<h2>url.format(urlObj)<span><a class="mark" href="#all_url_format_urlobj" id="all_url_format_urlobj">#</a></span></h2>
|
||
<p>Take a parsed URL object, and return a formatted URL string.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>href</code> will be ignored.</li>
|
||
<li><code>protocol</code>is treated the same with or without the trailing <code>:</code> (colon).<ul>
|
||
<li>The protocols <code>http</code>, <code>https</code>, <code>ftp</code>, <code>gopher</code>, <code>file</code> will be
|
||
postfixed with <code>://</code> (colon-slash-slash).</li>
|
||
<li>All other protocols <code>mailto</code>, <code>xmpp</code>, <code>aim</code>, <code>sftp</code>, <code>foo</code>, etc will
|
||
be postfixed with <code>:</code> (colon)</li>
|
||
</ul>
|
||
</li>
|
||
<li><code>auth</code> will be used if present.</li>
|
||
<li><code>hostname</code> will only be used if <code>host</code> is absent.</li>
|
||
<li><code>port</code> will only be used if <code>host</code> is absent.</li>
|
||
<li><code>host</code> will be used in place of <code>hostname</code> and <code>port</code></li>
|
||
<li><code>pathname</code> is treated the same with or without the leading <code>/</code> (slash)</li>
|
||
<li><code>search</code> will be used in place of <code>query</code></li>
|
||
<li><code>query</code> (object; see <code>querystring</code>) will only be used if <code>search</code> is absent.</li>
|
||
<li><code>search</code> is treated the same with or without the leading <code>?</code> (question mark)</li>
|
||
<li><code>hash</code> is treated the same with or without the leading <code>#</code> (pound sign, anchor)</li>
|
||
</ul>
|
||
<h2>url.resolve(from, to)<span><a class="mark" href="#all_url_resolve_from_to" id="all_url_resolve_from_to">#</a></span></h2>
|
||
<p>Take a base URL, and a href URL, and resolve them as a browser would for
|
||
an anchor tag.
|
||
|
||
</p>
|
||
<h1>Query String<span><a class="mark" href="#all_query_string" id="all_query_string">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<!--name=querystring-->
|
||
|
||
<p>This module provides utilities for dealing with query strings.
|
||
It provides the following methods:
|
||
|
||
</p>
|
||
<h2>querystring.stringify(obj, [sep], [eq])<span><a class="mark" href="#all_querystring_stringify_obj_sep_eq" id="all_querystring_stringify_obj_sep_eq">#</a></span></h2>
|
||
<p>Serialize an object to a query string.
|
||
Optionally override the default separator (<code>'&'</code>) and assignment (<code>'='</code>)
|
||
characters.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
|
||
// returns
|
||
'foo=bar&baz=qux&baz=quux&corge='
|
||
|
||
querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
|
||
// returns
|
||
'foo:bar;baz:qux'</code></pre>
|
||
<h2>querystring.parse(str, [sep], [eq], [options])<span><a class="mark" href="#all_querystring_parse_str_sep_eq_options" id="all_querystring_parse_str_sep_eq_options">#</a></span></h2>
|
||
<p>Deserialize a query string to an object.
|
||
Optionally override the default separator (<code>'&'</code>) and assignment (<code>'='</code>)
|
||
characters.
|
||
|
||
</p>
|
||
<p>Options object may contain <code>maxKeys</code> property (equal to 1000 by default), it'll
|
||
be used to limit processed keys. Set it to 0 to remove key count limitation.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>querystring.parse('foo=bar&baz=qux&baz=quux&corge')
|
||
// returns
|
||
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }</code></pre>
|
||
<h2>querystring.escape<span><a class="mark" href="#all_querystring_escape" id="all_querystring_escape">#</a></span></h2>
|
||
<p>The escape function used by <code>querystring.stringify</code>,
|
||
provided so that it could be overridden if necessary.
|
||
|
||
</p>
|
||
<h2>querystring.unescape<span><a class="mark" href="#all_querystring_unescape" id="all_querystring_unescape">#</a></span></h2>
|
||
<p>The unescape function used by <code>querystring.parse</code>,
|
||
provided so that it could be overridden if necessary.
|
||
|
||
</p>
|
||
<h1>punycode<span><a class="mark" href="#all_punycode" id="all_punycode">#</a></span></h1>
|
||
<pre><code>Stability: 2 - Unstable</code></pre>
|
||
<p><a href="http://mths.be/punycode">Punycode.js</a> is bundled with Node.js v0.6.2+. Use
|
||
<code>require('punycode')</code> to access it. (To use it with other Node.js versions,
|
||
use npm to install the <code>punycode</code> module first.)
|
||
|
||
</p>
|
||
<h2>punycode.decode(string)<span><a class="mark" href="#all_punycode_decode_string" id="all_punycode_decode_string">#</a></span></h2>
|
||
<p>Converts a Punycode string of ASCII code points to a string of Unicode code
|
||
points.
|
||
|
||
</p>
|
||
<pre><code>// decode domain name parts
|
||
punycode.decode('maana-pta'); // 'mañana'
|
||
punycode.decode('--dqo34k'); // '☃-⌘'</code></pre>
|
||
<h2>punycode.encode(string)<span><a class="mark" href="#all_punycode_encode_string" id="all_punycode_encode_string">#</a></span></h2>
|
||
<p>Converts a string of Unicode code points to a Punycode string of ASCII code
|
||
points.
|
||
|
||
</p>
|
||
<pre><code>// encode domain name parts
|
||
punycode.encode('mañana'); // 'maana-pta'
|
||
punycode.encode('☃-⌘'); // '--dqo34k'</code></pre>
|
||
<h2>punycode.toUnicode(domain)<span><a class="mark" href="#all_punycode_tounicode_domain" id="all_punycode_tounicode_domain">#</a></span></h2>
|
||
<p>Converts a Punycode string representing a domain name to Unicode. Only the
|
||
Punycoded parts of the domain name will be converted, i.e. it doesn't matter if
|
||
you call it on a string that has already been converted to Unicode.
|
||
|
||
</p>
|
||
<pre><code>// decode domain names
|
||
punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
|
||
punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'</code></pre>
|
||
<h2>punycode.toASCII(domain)<span><a class="mark" href="#all_punycode_toascii_domain" id="all_punycode_toascii_domain">#</a></span></h2>
|
||
<p>Converts a Unicode string representing a domain name to Punycode. Only the
|
||
non-ASCII parts of the domain name will be converted, i.e. it doesn't matter if
|
||
you call it with a domain that's already in ASCII.
|
||
|
||
</p>
|
||
<pre><code>// encode domain names
|
||
punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
|
||
punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'</code></pre>
|
||
<h2>punycode.ucs2<span><a class="mark" href="#all_punycode_ucs2" id="all_punycode_ucs2">#</a></span></h2>
|
||
<h3>punycode.ucs2.decode(string)<span><a class="mark" href="#all_punycode_ucs2_decode_string" id="all_punycode_ucs2_decode_string">#</a></span></h3>
|
||
<p>Creates an array containing the decimal code points of each Unicode character
|
||
in the string. While <a href="http://mathiasbynens.be/notes/javascript-encoding">JavaScript uses UCS-2
|
||
internally</a>, this function
|
||
will convert a pair of surrogate halves (each of which UCS-2 exposes as
|
||
separate characters) into a single code point, matching UTF-16.
|
||
|
||
</p>
|
||
<pre><code>punycode.ucs2.decode('abc'); // [97, 98, 99]
|
||
// surrogate pair for U+1D306 tetragram for centre:
|
||
punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]</code></pre>
|
||
<h3>punycode.ucs2.encode(codePoints)<span><a class="mark" href="#all_punycode_ucs2_encode_codepoints" id="all_punycode_ucs2_encode_codepoints">#</a></span></h3>
|
||
<p>Creates a string based on an array of decimal code points.
|
||
|
||
</p>
|
||
<pre><code>punycode.ucs2.encode([97, 98, 99]); // 'abc'
|
||
punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'</code></pre>
|
||
<h2>punycode.version<span><a class="mark" href="#all_punycode_version" id="all_punycode_version">#</a></span></h2>
|
||
<p>A string representing the current Punycode.js version number.
|
||
|
||
</p>
|
||
<h1>Readline<span><a class="mark" href="#all_readline" id="all_readline">#</a></span></h1>
|
||
<pre><code>Stability: 2 - Unstable</code></pre>
|
||
<p>To use this module, do <code>require('readline')</code>. Readline allows reading of a
|
||
stream (such as <code>process.stdin</code>) on a line-by-line basis.
|
||
|
||
</p>
|
||
<p>Note that once you've invoked this module, your node program will not
|
||
terminate until you've closed the interface. Here's how to allow your
|
||
program to gracefully exit:
|
||
|
||
</p>
|
||
<pre><code>var readline = require('readline');
|
||
|
||
var rl = readline.createInterface({
|
||
input: process.stdin,
|
||
output: process.stdout
|
||
});
|
||
|
||
rl.question("What do you think of node.js? ", function(answer) {
|
||
// TODO: Log the answer in a database
|
||
console.log("Thank you for your valuable feedback:", answer);
|
||
|
||
rl.close();
|
||
});</code></pre>
|
||
<h2>readline.createInterface(options)<span><a class="mark" href="#all_readline_createinterface_options" id="all_readline_createinterface_options">#</a></span></h2>
|
||
<p>Creates a readline <code>Interface</code> instance. Accepts an "options" Object that takes
|
||
the following values:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>input</code> - the readable stream to listen to (Required).</p>
|
||
</li>
|
||
<li><p><code>output</code> - the writable stream to write readline data to (Required).</p>
|
||
</li>
|
||
<li><p><code>completer</code> - an optional function that is used for Tab autocompletion. See
|
||
below for an example of using this.</p>
|
||
</li>
|
||
<li><p><code>terminal</code> - pass <code>true</code> if the <code>input</code> and <code>output</code> streams should be
|
||
treated like a TTY, and have ANSI/VT100 escape codes written to it.
|
||
Defaults to checking <code>isTTY</code> on the <code>output</code> stream upon instantiation.</p>
|
||
</li>
|
||
</ul>
|
||
<p>The <code>completer</code> function is given a the current line entered by the user, and
|
||
is supposed to return an Array with 2 entries:
|
||
|
||
</p>
|
||
<ol>
|
||
<li><p>An Array with matching entries for the completion.</p>
|
||
</li>
|
||
<li><p>The substring that was used for the matching.</p>
|
||
</li>
|
||
</ol>
|
||
<p>Which ends up looking something like:
|
||
<code>[[substr1, substr2, ...], originalsubstring]</code>.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>function completer(line) {
|
||
var completions = '.help .error .exit .quit .q'.split(' ')
|
||
var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })
|
||
// show all completions if none found
|
||
return [hits.length ? hits : completions, line]
|
||
}</code></pre>
|
||
<p>Also <code>completer</code> can be run in async mode if it accepts two arguments:
|
||
|
||
</p>
|
||
<pre><code>function completer(linePartial, callback) {
|
||
callback(null, [['123'], linePartial]);
|
||
}</code></pre>
|
||
<p><code>createInterface</code> is commonly used with <code>process.stdin</code> and
|
||
<code>process.stdout</code> in order to accept user input:
|
||
|
||
</p>
|
||
<pre><code>var readline = require('readline');
|
||
var rl = readline.createInterface({
|
||
input: process.stdin,
|
||
output: process.stdout
|
||
});</code></pre>
|
||
<p>Once you have a readline instance, you most commonly listen for the
|
||
<code>"line"</code> event.
|
||
|
||
</p>
|
||
<p>If <code>terminal</code> is <code>true</code> for this instance then the <code>output</code> stream will get
|
||
the best compatibility if it defines an <code>output.columns</code> property, and fires
|
||
a <code>"resize"</code> event on the <code>output</code> if/when the columns ever change
|
||
(<code>process.stdout</code> does this automatically when it is a TTY).
|
||
|
||
</p>
|
||
<h2>Class: Interface<span><a class="mark" href="#all_class_interface" id="all_class_interface">#</a></span></h2>
|
||
<p>The class that represents a readline interface with an input and output
|
||
stream.
|
||
|
||
</p>
|
||
<h3>rl.setPrompt(prompt, length)<span><a class="mark" href="#all_rl_setprompt_prompt_length" id="all_rl_setprompt_prompt_length">#</a></span></h3>
|
||
<p>Sets the prompt, for example when you run <code>node</code> on the command line, you see
|
||
<code>> </code>, which is node's prompt.
|
||
|
||
</p>
|
||
<h3>rl.prompt([preserveCursor])<span><a class="mark" href="#all_rl_prompt_preservecursor" id="all_rl_prompt_preservecursor">#</a></span></h3>
|
||
<p>Readies readline for input from the user, putting the current <code>setPrompt</code>
|
||
options on a new line, giving the user a new spot to write. Set <code>preserveCursor</code>
|
||
to <code>true</code> to prevent the cursor placement being reset to <code>0</code>.
|
||
|
||
</p>
|
||
<p>This will also resume the <code>input</code> stream used with <code>createInterface</code> if it has
|
||
been paused.
|
||
|
||
</p>
|
||
<h3>rl.question(query, callback)<span><a class="mark" href="#all_rl_question_query_callback" id="all_rl_question_query_callback">#</a></span></h3>
|
||
<p>Prepends the prompt with <code>query</code> and invokes <code>callback</code> with the user's
|
||
response. Displays the query to the user, and then invokes <code>callback</code>
|
||
with the user's response after it has been typed.
|
||
|
||
</p>
|
||
<p>This will also resume the <code>input</code> stream used with <code>createInterface</code> if
|
||
it has been paused.
|
||
|
||
</p>
|
||
<p>Example usage:
|
||
|
||
</p>
|
||
<pre><code>interface.question('What is your favorite food?', function(answer) {
|
||
console.log('Oh, so your favorite food is ' + answer);
|
||
});</code></pre>
|
||
<h3>rl.pause()<span><a class="mark" href="#all_rl_pause" id="all_rl_pause">#</a></span></h3>
|
||
<p>Pauses the readline <code>input</code> stream, allowing it to be resumed later if needed.
|
||
|
||
</p>
|
||
<h3>rl.resume()<span><a class="mark" href="#all_rl_resume" id="all_rl_resume">#</a></span></h3>
|
||
<p>Resumes the readline <code>input</code> stream.
|
||
|
||
</p>
|
||
<h3>rl.close()<span><a class="mark" href="#all_rl_close" id="all_rl_close">#</a></span></h3>
|
||
<p>Closes the <code>Interface</code> instance, relinquishing control on the <code>input</code> and
|
||
<code>output</code> streams. The "close" event will also be emitted.
|
||
|
||
</p>
|
||
<h3>rl.write(data, [key])<span><a class="mark" href="#all_rl_write_data_key" id="all_rl_write_data_key">#</a></span></h3>
|
||
<p>Writes <code>data</code> to <code>output</code> stream. <code>key</code> is an object literal to represent a key
|
||
sequence; available if the terminal is a TTY.
|
||
|
||
</p>
|
||
<p>This will also resume the <code>input</code> stream if it has been paused.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>rl.write('Delete me!');
|
||
// Simulate ctrl+u to delete the line written previously
|
||
rl.write(null, {ctrl: true, name: 'u'});</code></pre>
|
||
<h2>Events<span><a class="mark" href="#all_events_1" id="all_events_1">#</a></span></h2>
|
||
<h3>Event: 'line'<span><a class="mark" href="#all_event_line" id="all_event_line">#</a></span></h3>
|
||
<p><code>function (line) {}</code>
|
||
|
||
</p>
|
||
<p>Emitted whenever the <code>input</code> stream receives a <code>\n</code>, usually received when the
|
||
user hits enter, or return. This is a good hook to listen for user input.
|
||
|
||
</p>
|
||
<p>Example of listening for <code>line</code>:
|
||
|
||
</p>
|
||
<pre><code>rl.on('line', function (cmd) {
|
||
console.log('You just typed: '+cmd);
|
||
});</code></pre>
|
||
<h3>Event: 'pause'<span><a class="mark" href="#all_event_pause" id="all_event_pause">#</a></span></h3>
|
||
<p><code>function () {}</code>
|
||
|
||
</p>
|
||
<p>Emitted whenever the <code>input</code> stream is paused.
|
||
|
||
</p>
|
||
<p>Also emitted whenever the <code>input</code> stream is not paused and receives the
|
||
<code>SIGCONT</code> event. (See events <code>SIGTSTP</code> and <code>SIGCONT</code>)
|
||
|
||
</p>
|
||
<p>Example of listening for <code>pause</code>:
|
||
|
||
</p>
|
||
<pre><code>rl.on('pause', function() {
|
||
console.log('Readline paused.');
|
||
});</code></pre>
|
||
<h3>Event: 'resume'<span><a class="mark" href="#all_event_resume" id="all_event_resume">#</a></span></h3>
|
||
<p><code>function () {}</code>
|
||
|
||
</p>
|
||
<p>Emitted whenever the <code>input</code> stream is resumed.
|
||
|
||
</p>
|
||
<p>Example of listening for <code>resume</code>:
|
||
|
||
</p>
|
||
<pre><code>rl.on('resume', function() {
|
||
console.log('Readline resumed.');
|
||
});</code></pre>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_9" id="all_event_close_9">#</a></span></h3>
|
||
<p><code>function () {}</code>
|
||
|
||
</p>
|
||
<p>Emitted when <code>close()</code> is called.
|
||
|
||
</p>
|
||
<p>Also emitted when the <code>input</code> stream receives its "end" event. The <code>Interface</code>
|
||
instance should be considered "finished" once this is emitted. For example, when
|
||
the <code>input</code> stream receives <code>^D</code>, respectively known as <code>EOT</code>.
|
||
|
||
</p>
|
||
<p>This event is also called if there is no <code>SIGINT</code> event listener present when
|
||
the <code>input</code> stream receives a <code>^C</code>, respectively known as <code>SIGINT</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'SIGINT'<span><a class="mark" href="#all_event_sigint" id="all_event_sigint">#</a></span></h3>
|
||
<p><code>function () {}</code>
|
||
|
||
</p>
|
||
<p>Emitted whenever the <code>input</code> stream receives a <code>^C</code>, respectively known as
|
||
<code>SIGINT</code>. If there is no <code>SIGINT</code> event listener present when the <code>input</code>
|
||
stream receives a <code>SIGINT</code>, <code>pause</code> will be triggered.
|
||
|
||
</p>
|
||
<p>Example of listening for <code>SIGINT</code>:
|
||
|
||
</p>
|
||
<pre><code>rl.on('SIGINT', function() {
|
||
rl.question('Are you sure you want to exit?', function(answer) {
|
||
if (answer.match(/^y(es)?$/i)) rl.pause();
|
||
});
|
||
});</code></pre>
|
||
<h3>Event: 'SIGTSTP'<span><a class="mark" href="#all_event_sigtstp" id="all_event_sigtstp">#</a></span></h3>
|
||
<p><code>function () {}</code>
|
||
|
||
</p>
|
||
<p><strong>This does not work on Windows.</strong>
|
||
|
||
</p>
|
||
<p>Emitted whenever the <code>input</code> stream receives a <code>^Z</code>, respectively known as
|
||
<code>SIGTSTP</code>. If there is no <code>SIGTSTP</code> event listener present when the <code>input</code>
|
||
stream receives a <code>SIGTSTP</code>, the program will be sent to the background.
|
||
|
||
</p>
|
||
<p>When the program is resumed with <code>fg</code>, the <code>pause</code> and <code>SIGCONT</code> events will be
|
||
emitted. You can use either to resume the stream.
|
||
|
||
</p>
|
||
<p>The <code>pause</code> and <code>SIGCONT</code> events will not be triggered if the stream was paused
|
||
before the program was sent to the background.
|
||
|
||
</p>
|
||
<p>Example of listening for <code>SIGTSTP</code>:
|
||
|
||
</p>
|
||
<pre><code>rl.on('SIGTSTP', function() {
|
||
// This will override SIGTSTP and prevent the program from going to the
|
||
// background.
|
||
console.log('Caught SIGTSTP.');
|
||
});</code></pre>
|
||
<h3>Event: 'SIGCONT'<span><a class="mark" href="#all_event_sigcont" id="all_event_sigcont">#</a></span></h3>
|
||
<p><code>function () {}</code>
|
||
|
||
</p>
|
||
<p><strong>This does not work on Windows.</strong>
|
||
|
||
</p>
|
||
<p>Emitted whenever the <code>input</code> stream is sent to the background with <code>^Z</code>,
|
||
respectively known as <code>SIGTSTP</code>, and then continued with <code>fg(1)</code>. This event
|
||
only emits if the stream was not paused before sending the program to the
|
||
background.
|
||
|
||
</p>
|
||
<p>Example of listening for <code>SIGCONT</code>:
|
||
|
||
</p>
|
||
<pre><code>rl.on('SIGCONT', function() {
|
||
// `prompt` will automatically resume the stream
|
||
rl.prompt();
|
||
});</code></pre>
|
||
<h2>Example: Tiny CLI<span><a class="mark" href="#all_example_tiny_cli" id="all_example_tiny_cli">#</a></span></h2>
|
||
<p>Here's an example of how to use all these together to craft a tiny command
|
||
line interface:
|
||
|
||
</p>
|
||
<pre><code>var readline = require('readline'),
|
||
rl = readline.createInterface(process.stdin, process.stdout);
|
||
|
||
rl.setPrompt('OHAI> ');
|
||
rl.prompt();
|
||
|
||
rl.on('line', function(line) {
|
||
switch(line.trim()) {
|
||
case 'hello':
|
||
console.log('world!');
|
||
break;
|
||
default:
|
||
console.log('Say what? I might have heard `' + line.trim() + '`');
|
||
break;
|
||
}
|
||
rl.prompt();
|
||
}).on('close', function() {
|
||
console.log('Have a great day!');
|
||
process.exit(0);
|
||
});</code></pre>
|
||
<h1>REPL<span><a class="mark" href="#all_repl" id="all_repl">#</a></span></h1>
|
||
<p>A Read-Eval-Print-Loop (REPL) is available both as a standalone program and
|
||
easily includable in other programs. The REPL provides a way to interactively
|
||
run JavaScript and see the results. It can be used for debugging, testing, or
|
||
just trying things out.
|
||
|
||
</p>
|
||
<p>By executing <code>node</code> without any arguments from the command-line you will be
|
||
dropped into the REPL. It has simplistic emacs line-editing.
|
||
|
||
</p>
|
||
<pre><code>mjr:~$ node
|
||
Type '.help' for options.
|
||
> a = [ 1, 2, 3];
|
||
[ 1, 2, 3 ]
|
||
> a.forEach(function (v) {
|
||
... console.log(v);
|
||
... });
|
||
1
|
||
2
|
||
3</code></pre>
|
||
<p>For advanced line-editors, start node with the environmental variable
|
||
<code>NODE_NO_READLINE=1</code>. This will start the main and debugger REPL in canonical
|
||
terminal settings which will allow you to use with <code>rlwrap</code>.
|
||
|
||
</p>
|
||
<p>For example, you could add this to your bashrc file:
|
||
|
||
</p>
|
||
<pre><code>alias node="env NODE_NO_READLINE=1 rlwrap node"</code></pre>
|
||
<h2>repl.start(options)<span><a class="mark" href="#all_repl_start_options" id="all_repl_start_options">#</a></span></h2>
|
||
<p>Returns and starts a <code>REPLServer</code> instance. Accepts an "options" Object that
|
||
takes the following values:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><p><code>prompt</code> - the prompt and <code>stream</code> for all I/O. Defaults to <code>> </code>.</p>
|
||
</li>
|
||
<li><p><code>input</code> - the readable stream to listen to. Defaults to <code>process.stdin</code>.</p>
|
||
</li>
|
||
<li><p><code>output</code> - the writable stream to write readline data to. Defaults to
|
||
<code>process.stdout</code>.</p>
|
||
</li>
|
||
<li><p><code>terminal</code> - pass <code>true</code> if the <code>stream</code> should be treated like a TTY, and
|
||
have ANSI/VT100 escape codes written to it. Defaults to checking <code>isTTY</code>
|
||
on the <code>output</code> stream upon instantiation.</p>
|
||
</li>
|
||
<li><p><code>eval</code> - function that will be used to eval each given line. Defaults to
|
||
an async wrapper for <code>eval()</code>. See below for an example of a custom <code>eval</code>.</p>
|
||
</li>
|
||
<li><p><code>useColors</code> - a boolean which specifies whether or not the <code>writer</code> function
|
||
should output colors. If a different <code>writer</code> function is set then this does
|
||
nothing. Defaults to the repl's <code>terminal</code> value.</p>
|
||
</li>
|
||
<li><p><code>useGlobal</code> - if set to <code>true</code>, then the repl will use the <code>global</code> object,
|
||
instead of running scripts in a separate context. Defaults to <code>false</code>.</p>
|
||
</li>
|
||
<li><p><code>ignoreUndefined</code> - if set to <code>true</code>, then the repl will not output the
|
||
return value of command if it's <code>undefined</code>. Defaults to <code>false</code>.</p>
|
||
</li>
|
||
<li><p><code>writer</code> - the function to invoke for each command that gets evaluated which
|
||
returns the formatting (including coloring) to display. Defaults to
|
||
<code>util.inspect</code>.</p>
|
||
</li>
|
||
</ul>
|
||
<p>You can use your own <code>eval</code> function if it has following signature:
|
||
|
||
</p>
|
||
<pre><code>function eval(cmd, context, filename, callback) {
|
||
callback(null, result);
|
||
}</code></pre>
|
||
<p>Multiple REPLs may be started against the same running instance of node. Each
|
||
will share the same global object but will have unique I/O.
|
||
|
||
</p>
|
||
<p>Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
|
||
|
||
</p>
|
||
<pre><code>var net = require("net"),
|
||
repl = require("repl");
|
||
|
||
connections = 0;
|
||
|
||
repl.start({
|
||
prompt: "node via stdin> ",
|
||
input: process.stdin,
|
||
output: process.stdout
|
||
});
|
||
|
||
net.createServer(function (socket) {
|
||
connections += 1;
|
||
repl.start({
|
||
prompt: "node via Unix socket> ",
|
||
input: socket,
|
||
output: socket
|
||
}).on('exit', function() {
|
||
socket.end();
|
||
})
|
||
}).listen("/tmp/node-repl-sock");
|
||
|
||
net.createServer(function (socket) {
|
||
connections += 1;
|
||
repl.start({
|
||
prompt: "node via TCP socket> ",
|
||
input: socket,
|
||
output: socket
|
||
}).on('exit', function() {
|
||
socket.end();
|
||
});
|
||
}).listen(5001);</code></pre>
|
||
<p>Running this program from the command line will start a REPL on stdin. Other
|
||
REPL clients may connect through the Unix socket or TCP socket. <code>telnet</code> is useful
|
||
for connecting to TCP sockets, and <code>socat</code> can be used to connect to both Unix and
|
||
TCP sockets.
|
||
|
||
</p>
|
||
<p>By starting a REPL from a Unix socket-based server instead of stdin, you can
|
||
connect to a long-running node process without restarting it.
|
||
|
||
</p>
|
||
<p>For an example of running a "full-featured" (<code>terminal</code>) REPL over
|
||
a <code>net.Server</code> and <code>net.Socket</code> instance, see: <a href="https://gist.github.com/2209310">https://gist.github.com/2209310</a>
|
||
|
||
</p>
|
||
<p>For an example of running a REPL instance over <code>curl(1)</code>,
|
||
see: <a href="https://gist.github.com/2053342">https://gist.github.com/2053342</a>
|
||
|
||
</p>
|
||
<h3>Event: 'exit'<span><a class="mark" href="#all_event_exit_1" id="all_event_exit_1">#</a></span></h3>
|
||
<p><code>function () {}</code>
|
||
|
||
</p>
|
||
<p>Emitted when the user exits the REPL in any of the defined ways. Namely, typing
|
||
<code>.exit</code> at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D
|
||
to signal "end" on the <code>input</code> stream.
|
||
|
||
</p>
|
||
<p>Example of listening for <code>exit</code>:
|
||
|
||
</p>
|
||
<pre><code>r.on('exit', function () {
|
||
console.log('Got "exit" event from repl!');
|
||
process.exit();
|
||
});</code></pre>
|
||
<h2>REPL Features<span><a class="mark" href="#all_repl_features" id="all_repl_features">#</a></span></h2>
|
||
<!-- type=misc -->
|
||
|
||
<p>Inside the REPL, Control+D will exit. Multi-line expressions can be input.
|
||
Tab completion is supported for both global and local variables.
|
||
|
||
</p>
|
||
<p>The special variable <code>_</code> (underscore) contains the result of the last expression.
|
||
|
||
</p>
|
||
<pre><code>> [ "a", "b", "c" ]
|
||
[ 'a', 'b', 'c' ]
|
||
> _.length
|
||
3
|
||
> _ += 1
|
||
4</code></pre>
|
||
<p>The REPL provides access to any variables in the global scope. You can expose
|
||
a variable to the REPL explicitly by assigning it to the <code>context</code> object
|
||
associated with each <code>REPLServer</code>. For example:
|
||
|
||
</p>
|
||
<pre><code>// repl_test.js
|
||
var repl = require("repl"),
|
||
msg = "message";
|
||
|
||
repl.start().context.m = msg;</code></pre>
|
||
<p>Things in the <code>context</code> object appear as local within the REPL:
|
||
|
||
</p>
|
||
<pre><code>mjr:~$ node repl_test.js
|
||
> m
|
||
'message'</code></pre>
|
||
<p>There are a few special REPL commands:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>.break</code> - While inputting a multi-line expression, sometimes you get lost
|
||
or just don't care about completing it. <code>.break</code> will start over.</li>
|
||
<li><code>.clear</code> - Resets the <code>context</code> object to an empty object and clears any
|
||
multi-line expression.</li>
|
||
<li><code>.exit</code> - Close the I/O stream, which will cause the REPL to exit.</li>
|
||
<li><code>.help</code> - Show this list of special commands.</li>
|
||
<li><code>.save</code> - Save the current REPL session to a file<blockquote>
|
||
<p>.save ./file/to/save.js</p>
|
||
</blockquote>
|
||
</li>
|
||
<li><code>.load</code> - Load a file into the current REPL session.<blockquote>
|
||
<p>.load ./file/to/load.js</p>
|
||
</blockquote>
|
||
</li>
|
||
</ul>
|
||
<p>The following key combinations in the REPL have these special effects:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code><ctrl>C</code> - Similar to the <code>.break</code> keyword. Terminates the current
|
||
command. Press twice on a blank line to forcibly exit.</li>
|
||
<li><code><ctrl>D</code> - Similar to the <code>.exit</code> keyword.</li>
|
||
</ul>
|
||
<h1>Executing JavaScript<span><a class="mark" href="#all_executing_javascript" id="all_executing_javascript">#</a></span></h1>
|
||
<pre><code>Stability: 2 - Unstable. See Caveats, below.</code></pre>
|
||
<!--name=vm-->
|
||
|
||
<p>You can access this module with:
|
||
|
||
</p>
|
||
<pre><code>var vm = require('vm');</code></pre>
|
||
<p>JavaScript code can be compiled and run immediately or compiled, saved, and run later.
|
||
|
||
</p>
|
||
<h2>Caveats<span><a class="mark" href="#all_caveats_1" id="all_caveats_1">#</a></span></h2>
|
||
<p>The <code>vm</code> module has many known issues and edge cases. If you run into
|
||
issues or unexpected behavior, please consult
|
||
<a href="https://github.com/joyent/node/issues/search?q=vm">the open issues on GitHub</a>.
|
||
Some of the biggest problems are described below.
|
||
|
||
</p>
|
||
<h3>Sandboxes<span><a class="mark" href="#all_sandboxes" id="all_sandboxes">#</a></span></h3>
|
||
<p>The <code>sandbox</code> argument to <code>vm.runInNewContext</code> and <code>vm.createContext</code>,
|
||
along with the <code>initSandbox</code> argument to <code>vm.createContext</code>, do not
|
||
behave as one might normally expect and their behavior varies
|
||
between different versions of Node.
|
||
|
||
</p>
|
||
<p>The key issue to be aware of is that V8 provides no way to directly
|
||
control the global object used within a context. As a result, while
|
||
properties of your <code>sandbox</code> object will be available in the context,
|
||
any properties from the <code>prototype</code>s of the <code>sandbox</code> may not be
|
||
available. Furthermore, the <code>this</code> expression within the global scope
|
||
of the context evaluates to the empty object (<code>{}</code>) instead of to
|
||
your sandbox.
|
||
|
||
</p>
|
||
<p>Your sandbox's properties are also not shared directly with the script.
|
||
Instead, the properties of the sandbox are copied into the context at
|
||
the beginning of execution, and then after execution, the properties
|
||
are copied back out in an attempt to propagate any changes.
|
||
|
||
</p>
|
||
<h3>Globals<span><a class="mark" href="#all_globals" id="all_globals">#</a></span></h3>
|
||
<p>Properties of the global object, like <code>Array</code> and <code>String</code>, have
|
||
different values inside of a context. This means that common
|
||
expressions like <code>[] instanceof Array</code> or
|
||
<code>Object.getPrototypeOf([]) === Array.prototype</code> may not produce
|
||
expected results when used inside of scripts evaluated via the <code>vm</code> module.
|
||
|
||
</p>
|
||
<p>Some of these problems have known workarounds listed in the issues for
|
||
<code>vm</code> on GitHub. for example, <code>Array.isArray</code> works around
|
||
the example problem with <code>Array</code>.
|
||
|
||
</p>
|
||
<h2>vm.runInThisContext(code, [filename])<span><a class="mark" href="#all_vm_runinthiscontext_code_filename" id="all_vm_runinthiscontext_code_filename">#</a></span></h2>
|
||
<p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it and returns the result. Running
|
||
code does not have access to local scope. <code>filename</code> is optional, it's used only
|
||
in stack traces.
|
||
|
||
</p>
|
||
<p>Example of using <code>vm.runInThisContext</code> and <code>eval</code> to run the same code:
|
||
|
||
</p>
|
||
<pre><code>var localVar = 123,
|
||
usingscript, evaled,
|
||
vm = require('vm');
|
||
|
||
usingscript = vm.runInThisContext('localVar = 1;',
|
||
'myfile.vm');
|
||
console.log('localVar: ' + localVar + ', usingscript: ' +
|
||
usingscript);
|
||
evaled = eval('localVar = 1;');
|
||
console.log('localVar: ' + localVar + ', evaled: ' +
|
||
evaled);
|
||
|
||
// localVar: 123, usingscript: 1
|
||
// localVar: 1, evaled: 1</code></pre>
|
||
<p><code>vm.runInThisContext</code> does not have access to the local scope, so <code>localVar</code> is unchanged.
|
||
<code>eval</code> does have access to the local scope, so <code>localVar</code> is changed.
|
||
|
||
</p>
|
||
<p>In case of syntax error in <code>code</code>, <code>vm.runInThisContext</code> emits the syntax error to stderr
|
||
and throws an exception.
|
||
|
||
|
||
</p>
|
||
<h2>vm.runInNewContext(code, [sandbox], [filename])<span><a class="mark" href="#all_vm_runinnewcontext_code_sandbox_filename" id="all_vm_runinnewcontext_code_sandbox_filename">#</a></span></h2>
|
||
<p><code>vm.runInNewContext</code> compiles <code>code</code>, then runs it in <code>sandbox</code> and returns the
|
||
result. Running code does not have access to local scope. The object <code>sandbox</code>
|
||
will be used as the global object for <code>code</code>.
|
||
<code>sandbox</code> and <code>filename</code> are optional, <code>filename</code> is only used in stack traces.
|
||
|
||
</p>
|
||
<p>Example: compile and execute code that increments a global variable and sets a new one.
|
||
These globals are contained in the sandbox.
|
||
|
||
</p>
|
||
<pre><code>var util = require('util'),
|
||
vm = require('vm'),
|
||
sandbox = {
|
||
animal: 'cat',
|
||
count: 2
|
||
};
|
||
|
||
vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
|
||
console.log(util.inspect(sandbox));
|
||
|
||
// { animal: 'cat', count: 3, name: 'kitty' }</code></pre>
|
||
<p>Note that running untrusted code is a tricky business requiring great care. To prevent accidental
|
||
global variable leakage, <code>vm.runInNewContext</code> is quite useful, but safely running untrusted code
|
||
requires a separate process.
|
||
|
||
</p>
|
||
<p>In case of syntax error in <code>code</code>, <code>vm.runInNewContext</code> emits the syntax error to stderr
|
||
and throws an exception.
|
||
|
||
</p>
|
||
<h2>vm.runInContext(code, context, [filename])<span><a class="mark" href="#all_vm_runincontext_code_context_filename" id="all_vm_runincontext_code_context_filename">#</a></span></h2>
|
||
<p><code>vm.runInContext</code> compiles <code>code</code>, then runs it in <code>context</code> and returns the
|
||
result. A (V8) context comprises a global object, together with a set of
|
||
built-in objects and functions. Running code does not have access to local scope
|
||
and the global object held within <code>context</code> will be used as the global object
|
||
for <code>code</code>.
|
||
<code>filename</code> is optional, it's used only in stack traces.
|
||
|
||
</p>
|
||
<p>Example: compile and execute code in a existing context.
|
||
|
||
</p>
|
||
<pre><code>var util = require('util'),
|
||
vm = require('vm'),
|
||
initSandbox = {
|
||
animal: 'cat',
|
||
count: 2
|
||
},
|
||
context = vm.createContext(initSandbox);
|
||
|
||
vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
|
||
console.log(util.inspect(context));
|
||
|
||
// { animal: 'cat', count: 3, name: 'CATT' }</code></pre>
|
||
<p>Note that <code>createContext</code> will perform a shallow clone of the supplied sandbox object in order to
|
||
initialize the global object of the freshly constructed context.
|
||
|
||
</p>
|
||
<p>Note that running untrusted code is a tricky business requiring great care. To prevent accidental
|
||
global variable leakage, <code>vm.runInContext</code> is quite useful, but safely running untrusted code
|
||
requires a separate process.
|
||
|
||
</p>
|
||
<p>In case of syntax error in <code>code</code>, <code>vm.runInContext</code> emits the syntax error to stderr
|
||
and throws an exception.
|
||
|
||
</p>
|
||
<h2>vm.createContext([initSandbox])<span><a class="mark" href="#all_vm_createcontext_initsandbox" id="all_vm_createcontext_initsandbox">#</a></span></h2>
|
||
<p><code>vm.createContext</code> creates a new context which is suitable for use as the 2nd argument of a subsequent
|
||
call to <code>vm.runInContext</code>. A (V8) context comprises a global object together with a set of
|
||
build-in objects and functions. The optional argument <code>initSandbox</code> will be shallow-copied
|
||
to seed the initial contents of the global object used by the context.
|
||
|
||
</p>
|
||
<h2>vm.createScript(code, [filename])<span><a class="mark" href="#all_vm_createscript_code_filename" id="all_vm_createscript_code_filename">#</a></span></h2>
|
||
<p><code>createScript</code> compiles <code>code</code> but does not run it. Instead, it returns a
|
||
<code>vm.Script</code> object representing this compiled code. This script can be run
|
||
later many times using methods below. The returned script is not bound to any
|
||
global object. It is bound before each run, just for that run. <code>filename</code> is
|
||
optional, it's only used in stack traces.
|
||
|
||
</p>
|
||
<p>In case of syntax error in <code>code</code>, <code>createScript</code> prints the syntax error to stderr
|
||
and throws an exception.
|
||
|
||
|
||
</p>
|
||
<h2>Class: Script<span><a class="mark" href="#all_class_script" id="all_class_script">#</a></span></h2>
|
||
<p>A class for running scripts. Returned by vm.createScript.
|
||
|
||
</p>
|
||
<h3>script.runInThisContext()<span><a class="mark" href="#all_script_runinthiscontext" id="all_script_runinthiscontext">#</a></span></h3>
|
||
<p>Similar to <code>vm.runInThisContext</code> but a method of a precompiled <code>Script</code> object.
|
||
<code>script.runInThisContext</code> runs the code of <code>script</code> and returns the result.
|
||
Running code does not have access to local scope, but does have access to the <code>global</code> object
|
||
(v8: in actual context).
|
||
|
||
</p>
|
||
<p>Example of using <code>script.runInThisContext</code> to compile code once and run it multiple times:
|
||
|
||
</p>
|
||
<pre><code>var vm = require('vm');
|
||
|
||
globalVar = 0;
|
||
|
||
var script = vm.createScript('globalVar += 1', 'myfile.vm');
|
||
|
||
for (var i = 0; i < 1000 ; i += 1) {
|
||
script.runInThisContext();
|
||
}
|
||
|
||
console.log(globalVar);
|
||
|
||
// 1000</code></pre>
|
||
<h3>script.runInNewContext([sandbox])<span><a class="mark" href="#all_script_runinnewcontext_sandbox" id="all_script_runinnewcontext_sandbox">#</a></span></h3>
|
||
<p>Similar to <code>vm.runInNewContext</code> a method of a precompiled <code>Script</code> object.
|
||
<code>script.runInNewContext</code> runs the code of <code>script</code> with <code>sandbox</code> as the global object and returns the result.
|
||
Running code does not have access to local scope. <code>sandbox</code> is optional.
|
||
|
||
</p>
|
||
<p>Example: compile code that increments a global variable and sets one, then execute this code multiple times.
|
||
These globals are contained in the sandbox.
|
||
|
||
</p>
|
||
<pre><code>var util = require('util'),
|
||
vm = require('vm'),
|
||
sandbox = {
|
||
animal: 'cat',
|
||
count: 2
|
||
};
|
||
|
||
var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
|
||
|
||
for (var i = 0; i < 10 ; i += 1) {
|
||
script.runInNewContext(sandbox);
|
||
}
|
||
|
||
console.log(util.inspect(sandbox));
|
||
|
||
// { animal: 'cat', count: 12, name: 'kitty' }</code></pre>
|
||
<p>Note that running untrusted code is a tricky business requiring great care. To prevent accidental
|
||
global variable leakage, <code>script.runInNewContext</code> is quite useful, but safely running untrusted code
|
||
requires a separate process.
|
||
|
||
</p>
|
||
<h1>Child Process<span><a class="mark" href="#all_child_process" id="all_child_process">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>Node provides a tri-directional <code>popen(3)</code> facility through the
|
||
<code>child_process</code> module.
|
||
|
||
</p>
|
||
<p>It is possible to stream data through a child's <code>stdin</code>, <code>stdout</code>, and
|
||
<code>stderr</code> in a fully non-blocking way.
|
||
|
||
</p>
|
||
<p>To create a child process use <code>require('child_process').spawn()</code> or
|
||
<code>require('child_process').fork()</code>. The semantics of each are slightly
|
||
different, and explained below.
|
||
|
||
</p>
|
||
<h2>Class: ChildProcess<span><a class="mark" href="#all_class_childprocess" id="all_class_childprocess">#</a></span></h2>
|
||
<p><code>ChildProcess</code> is an <a href="events.html#events_class_events_eventemitter">EventEmitter</a>.
|
||
|
||
</p>
|
||
<p>Child processes always have three streams associated with them. <code>child.stdin</code>,
|
||
<code>child.stdout</code>, and <code>child.stderr</code>. These may be shared with the stdio
|
||
streams of the parent process, or they may be separate stream objects
|
||
which can be piped to and from.
|
||
|
||
</p>
|
||
<p>The ChildProcess class is not intended to be used directly. Use the
|
||
<code>spawn()</code> or <code>fork()</code> methods to create a Child Process instance.
|
||
|
||
</p>
|
||
<h3>Event: 'exit'<span><a class="mark" href="#all_event_exit_2" id="all_event_exit_2">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
|
||
<li><code>signal</code> <span class="type">String</span> the signal passed to kill the child process, if it
|
||
was killed by the parent.</li>
|
||
</div></ul>
|
||
<p>This event is emitted after the child process ends. If the process terminated
|
||
normally, <code>code</code> is the final exit code of the process, otherwise <code>null</code>. If
|
||
the process terminated due to receipt of a signal, <code>signal</code> is the string name
|
||
of the signal, otherwise <code>null</code>.
|
||
|
||
</p>
|
||
<p>Note that the child process stdio streams might still be open.
|
||
|
||
</p>
|
||
<p>See <code>waitpid(2)</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_10" id="all_event_close_10">#</a></span></h3>
|
||
<p>This event is emitted when the stdio streams of a child process have all
|
||
terminated. This is distinct from 'exit', since multiple processes
|
||
might share the same stdio streams.
|
||
|
||
</p>
|
||
<h3>Event: 'disconnect'<span><a class="mark" href="#all_event_disconnect" id="all_event_disconnect">#</a></span></h3>
|
||
<p>This event is emitted after using the <code>.disconnect()</code> method in the parent or
|
||
in the child. After disconnecting it is no longer possible to send messages.
|
||
An alternative way to check if you can send messages is to see if the
|
||
<code>child.connected</code> property is <code>true</code>.
|
||
|
||
</p>
|
||
<h3>Event: 'message'<span><a class="mark" href="#all_event_message_1" id="all_event_message_1">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>message</code> <span class="type">Object</span> a parsed JSON object or primitive value</li>
|
||
<li><code>sendHandle</code> <span class="type">Handle object</span> a Socket or Server object</li>
|
||
</div></ul>
|
||
<p>Messages send by <code>.send(message, [sendHandle])</code> are obtained using the
|
||
<code>message</code> event.
|
||
|
||
</p>
|
||
<h3>child.stdin<span><a class="mark" href="#all_child_stdin" id="all_child_stdin">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Stream object</span></li>
|
||
</div></ul>
|
||
<p>A <code>Writable Stream</code> that represents the child process's <code>stdin</code>.
|
||
Closing this stream via <code>end()</code> often causes the child process to terminate.
|
||
|
||
</p>
|
||
<p>If the child stdio streams are shared with the parent, then this will
|
||
not be set.
|
||
|
||
</p>
|
||
<h3>child.stdout<span><a class="mark" href="#all_child_stdout" id="all_child_stdout">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Stream object</span></li>
|
||
</div></ul>
|
||
<p>A <code>Readable Stream</code> that represents the child process's <code>stdout</code>.
|
||
|
||
</p>
|
||
<p>If the child stdio streams are shared with the parent, then this will
|
||
not be set.
|
||
|
||
</p>
|
||
<h3>child.stderr<span><a class="mark" href="#all_child_stderr" id="all_child_stderr">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Stream object</span></li>
|
||
</div></ul>
|
||
<p>A <code>Readable Stream</code> that represents the child process's <code>stderr</code>.
|
||
|
||
</p>
|
||
<p>If the child stdio streams are shared with the parent, then this will
|
||
not be set.
|
||
|
||
</p>
|
||
<h3>child.pid<span><a class="mark" href="#all_child_pid" id="all_child_pid">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Integer</span></li>
|
||
</div></ul>
|
||
<p>The PID of the child process.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var spawn = require('child_process').spawn,
|
||
grep = spawn('grep', ['ssh']);
|
||
|
||
console.log('Spawned child pid: ' + grep.pid);
|
||
grep.stdin.end();</code></pre>
|
||
<h3>child.kill([signal])<span><a class="mark" href="#all_child_kill_signal" id="all_child_kill_signal">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>signal</code> <span class="type">String</span></li>
|
||
</div></ul>
|
||
<p>Send a signal to the child process. If no argument is given, the process will
|
||
be sent <code>'SIGTERM'</code>. See <code>signal(7)</code> for a list of available signals.
|
||
|
||
</p>
|
||
<pre><code>var spawn = require('child_process').spawn,
|
||
grep = spawn('grep', ['ssh']);
|
||
|
||
grep.on('exit', function (code, signal) {
|
||
console.log('child process terminated due to receipt of signal '+signal);
|
||
});
|
||
|
||
// send SIGHUP to process
|
||
grep.kill('SIGHUP');</code></pre>
|
||
<p>Note that while the function is called <code>kill</code>, the signal delivered to the child
|
||
process may not actually kill it. <code>kill</code> really just sends a signal to a process.
|
||
|
||
</p>
|
||
<p>See <code>kill(2)</code>
|
||
|
||
</p>
|
||
<h3>child.send(message, [sendHandle])<span><a class="mark" href="#all_child_send_message_sendhandle" id="all_child_send_message_sendhandle">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>message</code> <span class="type">Object</span></li>
|
||
<li><code>sendHandle</code> <span class="type">Handle object</span></li>
|
||
</div></ul>
|
||
<p>When using <code>child_process.fork()</code> you can write to the child using
|
||
<code>child.send(message, [sendHandle])</code> and messages are received by
|
||
a <code>'message'</code> event on the child.
|
||
|
||
</p>
|
||
<p>For example:
|
||
|
||
</p>
|
||
<pre><code>var cp = require('child_process');
|
||
|
||
var n = cp.fork(__dirname + '/sub.js');
|
||
|
||
n.on('message', function(m) {
|
||
console.log('PARENT got message:', m);
|
||
});
|
||
|
||
n.send({ hello: 'world' });</code></pre>
|
||
<p>And then the child script, <code>'sub.js'</code> might look like this:
|
||
|
||
</p>
|
||
<pre><code>process.on('message', function(m) {
|
||
console.log('CHILD got message:', m);
|
||
});
|
||
|
||
process.send({ foo: 'bar' });</code></pre>
|
||
<p>In the child the <code>process</code> object will have a <code>send()</code> method, and <code>process</code>
|
||
will emit objects each time it receives a message on its channel.
|
||
|
||
</p>
|
||
<p>There is a special case when sending a <code>{cmd: 'NODE_foo'}</code> message. All messages
|
||
containing a <code>NODE_</code> prefix in its <code>cmd</code> property will not be emitted in
|
||
the <code>message</code> event, since they are internal messages used by node core.
|
||
Messages containing the prefix are emitted in the <code>internalMessage</code> event, you
|
||
should by all means avoid using this feature, it is subject to change without notice.
|
||
|
||
</p>
|
||
<p>The <code>sendHandle</code> option to <code>child.send()</code> is for sending a TCP server or
|
||
socket object to another process. The child will receive the object as its
|
||
second argument to the <code>message</code> event.
|
||
|
||
</p>
|
||
<p><strong>send server object</strong>
|
||
|
||
</p>
|
||
<p>Here is an example of sending a server:
|
||
|
||
</p>
|
||
<pre><code>var child = require('child_process').fork('child.js');
|
||
|
||
// Open up the server object and send the handle.
|
||
var server = require('net').createServer();
|
||
server.on('connection', function (socket) {
|
||
socket.end('handled by parent');
|
||
});
|
||
server.listen(1337, function() {
|
||
child.send('server', server);
|
||
});</code></pre>
|
||
<p>And the child would the receive the server object as:
|
||
|
||
</p>
|
||
<pre><code>process.on('message', function(m, server) {
|
||
if (m === 'server') {
|
||
server.on('connection', function (socket) {
|
||
socket.end('handled by child');
|
||
});
|
||
}
|
||
});</code></pre>
|
||
<p>Note that the server is now shared between the parent and child, this means
|
||
that some connections will be handled by the parent and some by the child.
|
||
|
||
</p>
|
||
<p><strong>send socket object</strong>
|
||
|
||
</p>
|
||
<p>Here is an example of sending a socket. It will spawn two children and handle
|
||
connections with the remote address <code>74.125.127.100</code> as VIP by sending the
|
||
socket to a "special" child process. Other sockets will go to a "normal" process.
|
||
|
||
</p>
|
||
<pre><code>var normal = require('child_process').fork('child.js', ['normal']);
|
||
var special = require('child_process').fork('child.js', ['special']);
|
||
|
||
// Open up the server and send sockets to child
|
||
var server = require('net').createServer();
|
||
server.on('connection', function (socket) {
|
||
|
||
// if this is a VIP
|
||
if (socket.remoteAddress === '74.125.127.100') {
|
||
special.send('socket', socket);
|
||
return;
|
||
}
|
||
// just the usual dudes
|
||
normal.send('socket', socket);
|
||
});
|
||
server.listen(1337);</code></pre>
|
||
<p>The <code>child.js</code> could look like this:
|
||
|
||
</p>
|
||
<pre><code>process.on('message', function(m, socket) {
|
||
if (m === 'socket') {
|
||
socket.end('You were handled as a ' + process.argv[2] + ' person');
|
||
}
|
||
});</code></pre>
|
||
<p>Note that once a single socket has been sent to a child the parent can no
|
||
longer keep track of when the socket is destroyed. To indicate this condition
|
||
the <code>.connections</code> property becomes <code>null</code>.
|
||
It is also recommended not to use <code>.maxConnections</code> in this condition.
|
||
|
||
</p>
|
||
<h3>child.disconnect()<span><a class="mark" href="#all_child_disconnect" id="all_child_disconnect">#</a></span></h3>
|
||
<p>To close the IPC connection between parent and child use the
|
||
<code>child.disconnect()</code> method. This allows the child to exit gracefully since
|
||
there is no IPC channel keeping it alive. When calling this method the
|
||
<code>disconnect</code> event will be emitted in both parent and child, and the
|
||
<code>connected</code> flag will be set to <code>false</code>. Please note that you can also call
|
||
<code>process.disconnect()</code> in the child process.
|
||
|
||
</p>
|
||
<h2>child_process.spawn(command, [args], [options])<span><a class="mark" href="#all_child_process_spawn_command_args_options" id="all_child_process_spawn_command_args_options">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>command</code> <span class="type">String</span> The command to run</li>
|
||
<li><code>args</code> <span class="type">Array</span> List of string arguments</li>
|
||
<li><code>options</code> <span class="type">Object</span><ul>
|
||
<li><code>cwd</code> <span class="type">String</span> Current working directory of the child process</li>
|
||
<li><code>stdio</code> <span class="type">Array|String</span> Child's stdio configuration. (See below)</li>
|
||
<li><code>customFds</code> <span class="type">Array</span> <strong>Deprecated</strong> File descriptors for the child to use
|
||
for stdio. (See below)</li>
|
||
<li><code>env</code> <span class="type">Object</span> Environment key-value pairs</li>
|
||
<li><code>detached</code> <span class="type">Boolean</span> The child will be a process group leader. (See below)</li>
|
||
<li><code>uid</code> <span class="type">Number</span> Sets the user identity of the process. (See setuid(2).)</li>
|
||
<li><code>gid</code> <span class="type">Number</span> Sets the group identity of the process. (See setgid(2).)</li>
|
||
</ul>
|
||
</li>
|
||
<li>return: <span class="type">ChildProcess object</span></li>
|
||
</div></ul>
|
||
<p>Launches a new process with the given <code>command</code>, with command line arguments in <code>args</code>.
|
||
If omitted, <code>args</code> defaults to an empty Array.
|
||
|
||
</p>
|
||
<p>The third argument is used to specify additional options, which defaults to:
|
||
|
||
</p>
|
||
<pre><code>{ cwd: undefined,
|
||
env: process.env
|
||
}</code></pre>
|
||
<p><code>cwd</code> allows you to specify the working directory from which the process is spawned.
|
||
Use <code>env</code> to specify environment variables that will be visible to the new process.
|
||
|
||
</p>
|
||
<p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the exit code:
|
||
|
||
</p>
|
||
<pre><code>var spawn = require('child_process').spawn,
|
||
ls = spawn('ls', ['-lh', '/usr']);
|
||
|
||
ls.stdout.on('data', function (data) {
|
||
console.log('stdout: ' + data);
|
||
});
|
||
|
||
ls.stderr.on('data', function (data) {
|
||
console.log('stderr: ' + data);
|
||
});
|
||
|
||
ls.on('exit', function (code) {
|
||
console.log('child process exited with code ' + code);
|
||
});</code></pre>
|
||
<p>Example: A very elaborate way to run 'ps ax | grep ssh'
|
||
|
||
</p>
|
||
<pre><code>var spawn = require('child_process').spawn,
|
||
ps = spawn('ps', ['ax']),
|
||
grep = spawn('grep', ['ssh']);
|
||
|
||
ps.stdout.on('data', function (data) {
|
||
grep.stdin.write(data);
|
||
});
|
||
|
||
ps.stderr.on('data', function (data) {
|
||
console.log('ps stderr: ' + data);
|
||
});
|
||
|
||
ps.on('exit', function (code) {
|
||
if (code !== 0) {
|
||
console.log('ps process exited with code ' + code);
|
||
}
|
||
grep.stdin.end();
|
||
});
|
||
|
||
grep.stdout.on('data', function (data) {
|
||
console.log('' + data);
|
||
});
|
||
|
||
grep.stderr.on('data', function (data) {
|
||
console.log('grep stderr: ' + data);
|
||
});
|
||
|
||
grep.on('exit', function (code) {
|
||
if (code !== 0) {
|
||
console.log('grep process exited with code ' + code);
|
||
}
|
||
});</code></pre>
|
||
<p>Example of checking for failed exec:
|
||
|
||
</p>
|
||
<pre><code>var spawn = require('child_process').spawn,
|
||
child = spawn('bad_command');
|
||
|
||
child.stderr.setEncoding('utf8');
|
||
child.stderr.on('data', function (data) {
|
||
if (/^execvp\(\)/.test(data)) {
|
||
console.log('Failed to start child process.');
|
||
}
|
||
});</code></pre>
|
||
<p>Note that if spawn receives an empty options object, it will result in
|
||
spawning the process with an empty environment rather than using
|
||
<code>process.env</code>. This due to backwards compatibility issues with a deprecated
|
||
API.
|
||
|
||
</p>
|
||
<p>The 'stdio' option to <code>child_process.spawn()</code> is an array where each
|
||
index corresponds to a fd in the child. The value is one of the following:
|
||
|
||
</p>
|
||
<ol>
|
||
<li><code>'pipe'</code> - Create a pipe between the child process and the parent process.
|
||
The parent end of the pipe is exposed to the parent as a property on the
|
||
<code>child_process</code> object as <code>ChildProcess.stdio[fd]</code>. Pipes created for
|
||
fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout
|
||
and ChildProcess.stderr, respectively.</li>
|
||
<li><code>'ipc'</code> - Create an IPC channel for passing messages/file descriptors
|
||
between parent and child. A ChildProcess may have at most <em>one</em> IPC stdio
|
||
file descriptor. Setting this option enables the ChildProcess.send() method.
|
||
If the child writes JSON messages to this file descriptor, then this will
|
||
trigger ChildProcess.on('message'). If the child is a Node.js program, then
|
||
the presence of an IPC channel will enable process.send() and
|
||
process.on('message').</li>
|
||
<li><code>'ignore'</code> - Do not set this file descriptor in the child. Note that Node
|
||
will always open fd 0 - 2 for the processes it spawns. When any of these is
|
||
ignored node will open <code>/dev/null</code> and attach it to the child's fd.</li>
|
||
<li><code>Stream</code> object - Share a readable or writable stream that refers to a tty,
|
||
file, socket, or a pipe with the child process. The stream's underlying
|
||
file descriptor is duplicated in the child process to the fd that
|
||
corresponds to the index in the <code>stdio</code> array.</li>
|
||
<li>Positive integer - The integer value is interpreted as a file descriptor
|
||
that is is currently open in the parent process. It is shared with the child
|
||
process, similar to how <code>Stream</code> objects can be shared.</li>
|
||
<li><code>null</code>, <code>undefined</code> - Use default value. For stdio fds 0, 1 and 2 (in other
|
||
words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
|
||
default is <code>'ignore'</code>.</li>
|
||
</ol>
|
||
<p>As a shorthand, the <code>stdio</code> argument may also be one of the following
|
||
strings, rather than an array:
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>ignore</code> - <code>['ignore', 'ignore', 'ignore']</code></li>
|
||
<li><code>pipe</code> - <code>['pipe', 'pipe', 'pipe']</code></li>
|
||
<li><code>inherit</code> - <code>[process.stdin, process.stdout, process.stderr]</code> or <code>[0,1,2]</code></li>
|
||
</ul>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var spawn = require('child_process').spawn;
|
||
|
||
// Child will use parent's stdios
|
||
spawn('prg', [], { stdio: 'inherit' });
|
||
|
||
// Spawn child sharing only stderr
|
||
spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
|
||
|
||
// Open an extra fd=4, to interact with programs present a
|
||
// startd-style interface.
|
||
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });</code></pre>
|
||
<p>If the <code>detached</code> option is set, the child process will be made the leader of a
|
||
new process group. This makes it possible for the child to continue running
|
||
after the parent exits.
|
||
|
||
</p>
|
||
<p>By default, the parent will wait for the detached child to exit. To prevent
|
||
the parent from waiting for a given <code>child</code>, use the <code>child.unref()</code> method,
|
||
and the parent's event loop will not include the child in its reference count.
|
||
|
||
</p>
|
||
<p>Example of detaching a long-running process and redirecting its output to a
|
||
file:
|
||
|
||
</p>
|
||
<pre><code> var fs = require('fs'),
|
||
spawn = require('child_process').spawn,
|
||
out = fs.openSync('./out.log', 'a'),
|
||
err = fs.openSync('./out.log', 'a');
|
||
|
||
var child = spawn('prg', [], {
|
||
detached: true,
|
||
stdio: [ 'ignore', out, err ]
|
||
});
|
||
|
||
child.unref();</code></pre>
|
||
<p>When using the <code>detached</code> option to start a long-running process, the process
|
||
will not stay running in the background unless it is provided with a <code>stdio</code>
|
||
configuration that is not connected to the parent. If the parent's <code>stdio</code> is
|
||
inherited, the child will remain attached to the controlling terminal.
|
||
|
||
</p>
|
||
<p>There is a deprecated option called <code>customFds</code> which allows one to specify
|
||
specific file descriptors for the stdio of the child process. This API was
|
||
not portable to all platforms and therefore removed.
|
||
With <code>customFds</code> it was possible to hook up the new process' <code>[stdin, stdout,
|
||
stderr]</code> to existing streams; <code>-1</code> meant that a new stream should be created.
|
||
Use at your own risk.
|
||
|
||
</p>
|
||
<p>There are several internal options. In particular <code>stdinStream</code>,
|
||
<code>stdoutStream</code>, <code>stderrStream</code>. They are for INTERNAL USE ONLY. As with all
|
||
undocumented APIs in Node, they should not be used.
|
||
|
||
</p>
|
||
<p>See also: <code>child_process.exec()</code> and <code>child_process.fork()</code>
|
||
|
||
</p>
|
||
<h2>child_process.exec(command, [options], callback)<span><a class="mark" href="#all_child_process_exec_command_options_callback" id="all_child_process_exec_command_options_callback">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>command</code> <span class="type">String</span> The command to run, with space-separated arguments</li>
|
||
<li><code>options</code> <span class="type">Object</span><ul>
|
||
<li><code>cwd</code> <span class="type">String</span> Current working directory of the child process</li>
|
||
<li><code>stdio</code> <span class="type">Array|String</span> Child's stdio configuration. (See above)</li>
|
||
<li><code>customFds</code> <span class="type">Array</span> <strong>Deprecated</strong> File descriptors for the child to use
|
||
for stdio. (See above)</li>
|
||
<li><code>env</code> <span class="type">Object</span> Environment key-value pairs</li>
|
||
<li><code>encoding</code> <span class="type">String</span> (Default: 'utf8')</li>
|
||
<li><code>timeout</code> <span class="type">Number</span> (Default: 0)</li>
|
||
<li><code>maxBuffer</code> <span class="type">Number</span> (Default: 200*1024)</li>
|
||
<li><code>killSignal</code> <span class="type">String</span> (Default: 'SIGTERM')</li>
|
||
</ul>
|
||
</li>
|
||
<li><code>callback</code> <span class="type">Function</span> called with the output when process terminates<ul>
|
||
<li><code>error</code> <span class="type">Error</span></li>
|
||
<li><code>stdout</code> <span class="type">Buffer</span></li>
|
||
<li><code>stderr</code> <span class="type">Buffer</span></li>
|
||
</ul>
|
||
</li>
|
||
<li>Return: ChildProcess object</li>
|
||
</div></ul>
|
||
<p>Runs a command in a shell and buffers the output.
|
||
|
||
</p>
|
||
<pre><code>var exec = require('child_process').exec,
|
||
child;
|
||
|
||
child = exec('cat *.js bad_file | wc -l',
|
||
function (error, stdout, stderr) {
|
||
console.log('stdout: ' + stdout);
|
||
console.log('stderr: ' + stderr);
|
||
if (error !== null) {
|
||
console.log('exec error: ' + error);
|
||
}
|
||
});</code></pre>
|
||
<p>The callback gets the arguments <code>(error, stdout, stderr)</code>. On success, <code>error</code>
|
||
will be <code>null</code>. On error, <code>error</code> will be an instance of <code>Error</code> and <code>err.code</code>
|
||
will be the exit code of the child process, and <code>err.signal</code> will be set to the
|
||
signal that terminated the process.
|
||
|
||
</p>
|
||
<p>There is a second optional argument to specify several options. The
|
||
default options are
|
||
|
||
</p>
|
||
<pre><code>{ encoding: 'utf8',
|
||
timeout: 0,
|
||
maxBuffer: 200*1024,
|
||
killSignal: 'SIGTERM',
|
||
cwd: null,
|
||
env: null }</code></pre>
|
||
<p>If <code>timeout</code> is greater than 0, then it will kill the child process
|
||
if it runs longer than <code>timeout</code> milliseconds. The child process is killed with
|
||
<code>killSignal</code> (default: <code>'SIGTERM'</code>). <code>maxBuffer</code> specifies the largest
|
||
amount of data allowed on stdout or stderr - if this value is exceeded then
|
||
the child process is killed.
|
||
|
||
|
||
</p>
|
||
<h2>child_process.execFile(file, args, options, callback)<span><a class="mark" href="#all_child_process_execfile_file_args_options_callback" id="all_child_process_execfile_file_args_options_callback">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>file</code> <span class="type">String</span> The filename of the program to run</li>
|
||
<li><code>args</code> <span class="type">Array</span> List of string arguments</li>
|
||
<li><code>options</code> <span class="type">Object</span><ul>
|
||
<li><code>cwd</code> <span class="type">String</span> Current working directory of the child process</li>
|
||
<li><code>stdio</code> <span class="type">Array|String</span> Child's stdio configuration. (See above)</li>
|
||
<li><code>customFds</code> <span class="type">Array</span> <strong>Deprecated</strong> File descriptors for the child to use
|
||
for stdio. (See above)</li>
|
||
<li><code>env</code> <span class="type">Object</span> Environment key-value pairs</li>
|
||
<li><code>encoding</code> <span class="type">String</span> (Default: 'utf8')</li>
|
||
<li><code>timeout</code> <span class="type">Number</span> (Default: 0)</li>
|
||
<li><code>maxBuffer</code> <span class="type">Number</span> (Default: 200*1024)</li>
|
||
<li><code>killSignal</code> <span class="type">String</span> (Default: 'SIGTERM')</li>
|
||
</ul>
|
||
</li>
|
||
<li><code>callback</code> <span class="type">Function</span> called with the output when process terminates<ul>
|
||
<li><code>error</code> <span class="type">Error</span></li>
|
||
<li><code>stdout</code> <span class="type">Buffer</span></li>
|
||
<li><code>stderr</code> <span class="type">Buffer</span></li>
|
||
</ul>
|
||
</li>
|
||
<li>Return: ChildProcess object</li>
|
||
</div></ul>
|
||
<p>This is similar to <code>child_process.exec()</code> except it does not execute a
|
||
subshell but rather the specified file directly. This makes it slightly
|
||
leaner than <code>child_process.exec</code>. It has the same options.
|
||
|
||
|
||
</p>
|
||
<h2>child_process.fork(modulePath, [args], [options])<span><a class="mark" href="#all_child_process_fork_modulepath_args_options" id="all_child_process_fork_modulepath_args_options">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>modulePath</code> <span class="type">String</span> The module to run in the child</li>
|
||
<li><code>args</code> <span class="type">Array</span> List of string arguments</li>
|
||
<li><code>options</code> <span class="type">Object</span><ul>
|
||
<li><code>cwd</code> <span class="type">String</span> Current working directory of the child process</li>
|
||
<li><code>env</code> <span class="type">Object</span> Environment key-value pairs</li>
|
||
<li><code>encoding</code> <span class="type">String</span> (Default: 'utf8')</li>
|
||
</ul>
|
||
</li>
|
||
<li>Return: ChildProcess object</li>
|
||
</div></ul>
|
||
<p>This is a special case of the <code>spawn()</code> functionality for spawning Node
|
||
processes. In addition to having all the methods in a normal ChildProcess
|
||
instance, the returned object has a communication channel built-in. See
|
||
<code>child.send(message, [sendHandle])</code> for details.
|
||
|
||
</p>
|
||
<p>By default the spawned Node process will have the stdout, stderr associated
|
||
with the parent's. To change this behavior set the <code>silent</code> property in the
|
||
<code>options</code> object to <code>true</code>.
|
||
|
||
</p>
|
||
<p>The child process does not automatically exit once it's done, you need to call
|
||
<code>process.exit()</code> explicitly. This limitation may be lifted in the future.
|
||
|
||
</p>
|
||
<p>These child Nodes are still whole new instances of V8. Assume at least 30ms
|
||
startup and 10mb memory for each new Node. That is, you cannot create many
|
||
thousands of them.
|
||
|
||
</p>
|
||
<h1>Assert<span><a class="mark" href="#all_assert" id="all_assert">#</a></span></h1>
|
||
<pre><code>Stability: 5 - Locked</code></pre>
|
||
<p>This module is used for writing unit tests for your applications, you can
|
||
access it with <code>require('assert')</code>.
|
||
|
||
</p>
|
||
<h2>assert.fail(actual, expected, message, operator)<span><a class="mark" href="#all_assert_fail_actual_expected_message_operator" id="all_assert_fail_actual_expected_message_operator">#</a></span></h2>
|
||
<p>Throws an exception that displays the values for <code>actual</code> and <code>expected</code> separated by the provided operator.
|
||
|
||
</p>
|
||
<h2>assert(value, message), assert.ok(value, [message])<span><a class="mark" href="#all_assert_value_message_assert_ok_value_message" id="all_assert_value_message_assert_ok_value_message">#</a></span></h2>
|
||
<p>Tests if value is truthy, it is equivalent to <code>assert.equal(true, !!value, message);</code>
|
||
|
||
</p>
|
||
<h2>assert.equal(actual, expected, [message])<span><a class="mark" href="#all_assert_equal_actual_expected_message" id="all_assert_equal_actual_expected_message">#</a></span></h2>
|
||
<p>Tests shallow, coercive equality with the equal comparison operator ( <code>==</code> ).
|
||
|
||
</p>
|
||
<h2>assert.notEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_notequal_actual_expected_message" id="all_assert_notequal_actual_expected_message">#</a></span></h2>
|
||
<p>Tests shallow, coercive non-equality with the not equal comparison operator ( <code>!=</code> ).
|
||
|
||
</p>
|
||
<h2>assert.deepEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_deepequal_actual_expected_message" id="all_assert_deepequal_actual_expected_message">#</a></span></h2>
|
||
<p>Tests for deep equality.
|
||
|
||
</p>
|
||
<h2>assert.notDeepEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_notdeepequal_actual_expected_message" id="all_assert_notdeepequal_actual_expected_message">#</a></span></h2>
|
||
<p>Tests for any deep inequality.
|
||
|
||
</p>
|
||
<h2>assert.strictEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_strictequal_actual_expected_message" id="all_assert_strictequal_actual_expected_message">#</a></span></h2>
|
||
<p>Tests strict equality, as determined by the strict equality operator ( <code>===</code> )
|
||
|
||
</p>
|
||
<h2>assert.notStrictEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_notstrictequal_actual_expected_message" id="all_assert_notstrictequal_actual_expected_message">#</a></span></h2>
|
||
<p>Tests strict non-equality, as determined by the strict not equal operator ( <code>!==</code> )
|
||
|
||
</p>
|
||
<h2>assert.throws(block, [error], [message])<span><a class="mark" href="#all_assert_throws_block_error_message" id="all_assert_throws_block_error_message">#</a></span></h2>
|
||
<p>Expects <code>block</code> to throw an error. <code>error</code> can be constructor, regexp or
|
||
validation function.
|
||
|
||
</p>
|
||
<p>Validate instanceof using constructor:
|
||
|
||
</p>
|
||
<pre><code>assert.throws(
|
||
function() {
|
||
throw new Error("Wrong value");
|
||
},
|
||
Error
|
||
);</code></pre>
|
||
<p>Validate error message using RegExp:
|
||
|
||
</p>
|
||
<pre><code>assert.throws(
|
||
function() {
|
||
throw new Error("Wrong value");
|
||
},
|
||
/value/
|
||
);</code></pre>
|
||
<p>Custom error validation:
|
||
|
||
</p>
|
||
<pre><code>assert.throws(
|
||
function() {
|
||
throw new Error("Wrong value");
|
||
},
|
||
function(err) {
|
||
if ( (err instanceof Error) && /value/.test(err) ) {
|
||
return true;
|
||
}
|
||
},
|
||
"unexpected error"
|
||
);</code></pre>
|
||
<h2>assert.doesNotThrow(block, [error], [message])<span><a class="mark" href="#all_assert_doesnotthrow_block_error_message" id="all_assert_doesnotthrow_block_error_message">#</a></span></h2>
|
||
<p>Expects <code>block</code> not to throw an error, see assert.throws for details.
|
||
|
||
</p>
|
||
<h2>assert.ifError(value)<span><a class="mark" href="#all_assert_iferror_value" id="all_assert_iferror_value">#</a></span></h2>
|
||
<p>Tests if value is not a false value, throws if it is a true value. Useful when
|
||
testing the first argument, <code>error</code> in callbacks.
|
||
|
||
</p>
|
||
<h1>TTY<span><a class="mark" href="#all_tty" id="all_tty">#</a></span></h1>
|
||
<pre><code>Stability: 2 - Unstable</code></pre>
|
||
<p>The <code>tty</code> module houses the <code>tty.ReadStream</code> and <code>tty.WriteStream</code> classes. In
|
||
most cases, you will not need to use this module directly.
|
||
|
||
</p>
|
||
<p>When node detects that it is being run inside a TTY context, then <code>process.stdin</code>
|
||
will be a <code>tty.ReadStream</code> instance and <code>process.stdout</code> will be
|
||
a <code>tty.WriteStream</code> instance. The preferred way to check if node is being run in
|
||
a TTY context is to check <code>process.stdout.isTTY</code>:
|
||
|
||
</p>
|
||
<pre><code>$ node -p -e "Boolean(process.stdout.isTTY)"
|
||
true
|
||
$ node -p -e "Boolean(process.stdout.isTTY)" | cat
|
||
false</code></pre>
|
||
<h2>tty.isatty(fd)<span><a class="mark" href="#all_tty_isatty_fd" id="all_tty_isatty_fd">#</a></span></h2>
|
||
<p>Returns <code>true</code> or <code>false</code> depending on if the <code>fd</code> is associated with a
|
||
terminal.
|
||
|
||
|
||
</p>
|
||
<h2>tty.setRawMode(mode)<span><a class="mark" href="#all_tty_setrawmode_mode" id="all_tty_setrawmode_mode">#</a></span></h2>
|
||
<p>Deprecated. Use <code>tty.ReadStream#setRawMode()</code>
|
||
(i.e. <code>process.stdin.setRawMode()</code>) instead.
|
||
|
||
|
||
</p>
|
||
<h2>Class: ReadStream<span><a class="mark" href="#all_class_readstream" id="all_class_readstream">#</a></span></h2>
|
||
<p>A <code>net.Socket</code> subclass that represents the readable portion of a tty. In normal
|
||
circumstances, <code>process.stdin</code> will be the only <code>tty.ReadStream</code> instance in any
|
||
node program (only when <code>isatty(0)</code> is true).
|
||
|
||
</p>
|
||
<h3>rs.isRaw<span><a class="mark" href="#all_rs_israw" id="all_rs_israw">#</a></span></h3>
|
||
<p>A <code>Boolean</code> that is initialized to <code>false</code>. It represents the current "raw" state
|
||
of the <code>tty.ReadStream</code> instance.
|
||
|
||
</p>
|
||
<h3>rs.setRawMode(mode)<span><a class="mark" href="#all_rs_setrawmode_mode" id="all_rs_setrawmode_mode">#</a></span></h3>
|
||
<p><code>mode</code> should be <code>true</code> or <code>false</code>. This sets the properties of the
|
||
<code>tty.ReadStream</code> to act either as a raw device or default. <code>isRaw</code> will be set
|
||
to the resulting mode.
|
||
|
||
|
||
</p>
|
||
<h2>Class WriteStream<span><a class="mark" href="#all_class_writestream" id="all_class_writestream">#</a></span></h2>
|
||
<p>A <code>net.Socket</code> subclass that represents the writable portion of a tty. In normal
|
||
circumstances, <code>process.stdout</code> will be the only <code>tty.WriteStream</code> instance
|
||
ever created (and only when <code>isatty(1)</code> is true).
|
||
|
||
</p>
|
||
<h3>ws.columns<span><a class="mark" href="#all_ws_columns" id="all_ws_columns">#</a></span></h3>
|
||
<p>A <code>Number</code> that gives the number of columns the TTY currently has. This property
|
||
gets updated on "resize" events.
|
||
|
||
</p>
|
||
<h3>ws.rows<span><a class="mark" href="#all_ws_rows" id="all_ws_rows">#</a></span></h3>
|
||
<p>A <code>Number</code> that gives the number of rows the TTY currently has. This property
|
||
gets updated on "resize" events.
|
||
|
||
</p>
|
||
<h3>Event: 'resize'<span><a class="mark" href="#all_event_resize" id="all_event_resize">#</a></span></h3>
|
||
<p><code>function () {}</code>
|
||
|
||
</p>
|
||
<p>Emitted by <code>refreshSize()</code> when either of the <code>columns</code> or <code>rows</code> properties
|
||
has changed.
|
||
|
||
</p>
|
||
<pre><code>process.stdout.on('resize', function() {
|
||
console.log('screen size has changed!');
|
||
console.log(process.stdout.columns + 'x' + process.stdout.rows);
|
||
});</code></pre>
|
||
<h1>Zlib<span><a class="mark" href="#all_zlib" id="all_zlib">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<p>You can access this module with:
|
||
|
||
</p>
|
||
<pre><code>var zlib = require('zlib');</code></pre>
|
||
<p>This provides bindings to Gzip/Gunzip, Deflate/Inflate, and
|
||
DeflateRaw/InflateRaw classes. Each class takes the same options, and
|
||
is a readable/writable Stream.
|
||
|
||
</p>
|
||
<h2>Examples<span><a class="mark" href="#all_examples" id="all_examples">#</a></span></h2>
|
||
<p>Compressing or decompressing a file can be done by piping an
|
||
fs.ReadStream into a zlib stream, then into an fs.WriteStream.
|
||
|
||
</p>
|
||
<pre><code>var gzip = zlib.createGzip();
|
||
var fs = require('fs');
|
||
var inp = fs.createReadStream('input.txt');
|
||
var out = fs.createWriteStream('input.txt.gz');
|
||
|
||
inp.pipe(gzip).pipe(out);</code></pre>
|
||
<p>Compressing or decompressing data in one step can be done by using
|
||
the convenience methods.
|
||
|
||
</p>
|
||
<pre><code>var input = '.................................';
|
||
zlib.deflate(input, function(err, buffer) {
|
||
if (!err) {
|
||
console.log(buffer.toString('base64'));
|
||
}
|
||
});
|
||
|
||
var buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');
|
||
zlib.unzip(buffer, function(err, buffer) {
|
||
if (!err) {
|
||
console.log(buffer.toString());
|
||
}
|
||
});</code></pre>
|
||
<p>To use this module in an HTTP client or server, use the
|
||
<a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3">accept-encoding</a>
|
||
on requests, and the
|
||
<a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11">content-encoding</a>
|
||
header on responses.
|
||
|
||
</p>
|
||
<p><strong>Note: these examples are drastically simplified to show
|
||
the basic concept.</strong> Zlib encoding can be expensive, and the results
|
||
ought to be cached. See <a href="#zlib_memory_usage_tuning">Memory Usage Tuning</a>
|
||
below for more information on the speed/memory/compression
|
||
tradeoffs involved in zlib usage.
|
||
|
||
</p>
|
||
<pre><code>// client request example
|
||
var zlib = require('zlib');
|
||
var http = require('http');
|
||
var fs = require('fs');
|
||
var request = http.get({ host: 'izs.me',
|
||
path: '/',
|
||
port: 80,
|
||
headers: { 'accept-encoding': 'gzip,deflate' } });
|
||
request.on('response', function(response) {
|
||
var output = fs.createWriteStream('izs.me_index.html');
|
||
|
||
switch (response.headers['content-encoding']) {
|
||
// or, just use zlib.createUnzip() to handle both cases
|
||
case 'gzip':
|
||
response.pipe(zlib.createGunzip()).pipe(output);
|
||
break;
|
||
case 'deflate':
|
||
response.pipe(zlib.createInflate()).pipe(output);
|
||
break;
|
||
default:
|
||
response.pipe(output);
|
||
break;
|
||
}
|
||
});
|
||
|
||
// server example
|
||
// Running a gzip operation on every request is quite expensive.
|
||
// It would be much more efficient to cache the compressed buffer.
|
||
var zlib = require('zlib');
|
||
var http = require('http');
|
||
var fs = require('fs');
|
||
http.createServer(function(request, response) {
|
||
var raw = fs.createReadStream('index.html');
|
||
var acceptEncoding = request.headers['accept-encoding'];
|
||
if (!acceptEncoding) {
|
||
acceptEncoding = '';
|
||
}
|
||
|
||
// Note: this is not a conformant accept-encoding parser.
|
||
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
|
||
if (acceptEncoding.match(/\bdeflate\b/)) {
|
||
response.writeHead(200, { 'content-encoding': 'deflate' });
|
||
raw.pipe(zlib.createDeflate()).pipe(response);
|
||
} else if (acceptEncoding.match(/\bgzip\b/)) {
|
||
response.writeHead(200, { 'content-encoding': 'gzip' });
|
||
raw.pipe(zlib.createGzip()).pipe(response);
|
||
} else {
|
||
response.writeHead(200, {});
|
||
raw.pipe(response);
|
||
}
|
||
}).listen(1337);</code></pre>
|
||
<h2>zlib.createGzip([options])<span><a class="mark" href="#all_zlib_creategzip_options" id="all_zlib_creategzip_options">#</a></span></h2>
|
||
<p>Returns a new <a href="#zlib_class_zlib_gzip">Gzip</a> object with an
|
||
<a href="#zlib_options">options</a>.
|
||
|
||
</p>
|
||
<h2>zlib.createGunzip([options])<span><a class="mark" href="#all_zlib_creategunzip_options" id="all_zlib_creategunzip_options">#</a></span></h2>
|
||
<p>Returns a new <a href="#zlib_class_zlib_gunzip">Gunzip</a> object with an
|
||
<a href="#zlib_options">options</a>.
|
||
|
||
</p>
|
||
<h2>zlib.createDeflate([options])<span><a class="mark" href="#all_zlib_createdeflate_options" id="all_zlib_createdeflate_options">#</a></span></h2>
|
||
<p>Returns a new <a href="#zlib_class_zlib_deflate">Deflate</a> object with an
|
||
<a href="#zlib_options">options</a>.
|
||
|
||
</p>
|
||
<h2>zlib.createInflate([options])<span><a class="mark" href="#all_zlib_createinflate_options" id="all_zlib_createinflate_options">#</a></span></h2>
|
||
<p>Returns a new <a href="#zlib_class_zlib_inflate">Inflate</a> object with an
|
||
<a href="#zlib_options">options</a>.
|
||
|
||
</p>
|
||
<h2>zlib.createDeflateRaw([options])<span><a class="mark" href="#all_zlib_createdeflateraw_options" id="all_zlib_createdeflateraw_options">#</a></span></h2>
|
||
<p>Returns a new <a href="#zlib_class_zlib_deflateraw">DeflateRaw</a> object with an
|
||
<a href="#zlib_options">options</a>.
|
||
|
||
</p>
|
||
<h2>zlib.createInflateRaw([options])<span><a class="mark" href="#all_zlib_createinflateraw_options" id="all_zlib_createinflateraw_options">#</a></span></h2>
|
||
<p>Returns a new <a href="#zlib_class_zlib_inflateraw">InflateRaw</a> object with an
|
||
<a href="#zlib_options">options</a>.
|
||
|
||
</p>
|
||
<h2>zlib.createUnzip([options])<span><a class="mark" href="#all_zlib_createunzip_options" id="all_zlib_createunzip_options">#</a></span></h2>
|
||
<p>Returns a new <a href="#zlib_class_zlib_unzip">Unzip</a> object with an
|
||
<a href="#zlib_options">options</a>.
|
||
|
||
|
||
</p>
|
||
<h2>Class: zlib.Gzip<span><a class="mark" href="#all_class_zlib_gzip" id="all_class_zlib_gzip">#</a></span></h2>
|
||
<p>Compress data using gzip.
|
||
|
||
</p>
|
||
<h2>Class: zlib.Gunzip<span><a class="mark" href="#all_class_zlib_gunzip" id="all_class_zlib_gunzip">#</a></span></h2>
|
||
<p>Decompress a gzip stream.
|
||
|
||
</p>
|
||
<h2>Class: zlib.Deflate<span><a class="mark" href="#all_class_zlib_deflate" id="all_class_zlib_deflate">#</a></span></h2>
|
||
<p>Compress data using deflate.
|
||
|
||
</p>
|
||
<h2>Class: zlib.Inflate<span><a class="mark" href="#all_class_zlib_inflate" id="all_class_zlib_inflate">#</a></span></h2>
|
||
<p>Decompress a deflate stream.
|
||
|
||
</p>
|
||
<h2>Class: zlib.DeflateRaw<span><a class="mark" href="#all_class_zlib_deflateraw" id="all_class_zlib_deflateraw">#</a></span></h2>
|
||
<p>Compress data using deflate, and do not append a zlib header.
|
||
|
||
</p>
|
||
<h2>Class: zlib.InflateRaw<span><a class="mark" href="#all_class_zlib_inflateraw" id="all_class_zlib_inflateraw">#</a></span></h2>
|
||
<p>Decompress a raw deflate stream.
|
||
|
||
</p>
|
||
<h2>Class: zlib.Unzip<span><a class="mark" href="#all_class_zlib_unzip" id="all_class_zlib_unzip">#</a></span></h2>
|
||
<p>Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
|
||
the header.
|
||
|
||
</p>
|
||
<h2>Convenience Methods<span><a class="mark" href="#all_convenience_methods" id="all_convenience_methods">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>All of these take a string or buffer as the first argument, and call the
|
||
supplied callback with <code>callback(error, result)</code>. The
|
||
compression/decompression engine is created using the default settings
|
||
in all convenience methods. To supply different options, use the
|
||
zlib classes directly.
|
||
|
||
</p>
|
||
<h2>zlib.deflate(buf, callback)<span><a class="mark" href="#all_zlib_deflate_buf_callback" id="all_zlib_deflate_buf_callback">#</a></span></h2>
|
||
<p>Compress a string with Deflate.
|
||
|
||
</p>
|
||
<h2>zlib.deflateRaw(buf, callback)<span><a class="mark" href="#all_zlib_deflateraw_buf_callback" id="all_zlib_deflateraw_buf_callback">#</a></span></h2>
|
||
<p>Compress a string with DeflateRaw.
|
||
|
||
</p>
|
||
<h2>zlib.gzip(buf, callback)<span><a class="mark" href="#all_zlib_gzip_buf_callback" id="all_zlib_gzip_buf_callback">#</a></span></h2>
|
||
<p>Compress a string with Gzip.
|
||
|
||
</p>
|
||
<h2>zlib.gunzip(buf, callback)<span><a class="mark" href="#all_zlib_gunzip_buf_callback" id="all_zlib_gunzip_buf_callback">#</a></span></h2>
|
||
<p>Decompress a raw Buffer with Gunzip.
|
||
|
||
</p>
|
||
<h2>zlib.inflate(buf, callback)<span><a class="mark" href="#all_zlib_inflate_buf_callback" id="all_zlib_inflate_buf_callback">#</a></span></h2>
|
||
<p>Decompress a raw Buffer with Inflate.
|
||
|
||
</p>
|
||
<h2>zlib.inflateRaw(buf, callback)<span><a class="mark" href="#all_zlib_inflateraw_buf_callback" id="all_zlib_inflateraw_buf_callback">#</a></span></h2>
|
||
<p>Decompress a raw Buffer with InflateRaw.
|
||
|
||
</p>
|
||
<h2>zlib.unzip(buf, callback)<span><a class="mark" href="#all_zlib_unzip_buf_callback" id="all_zlib_unzip_buf_callback">#</a></span></h2>
|
||
<p>Decompress a raw Buffer with Unzip.
|
||
|
||
</p>
|
||
<h2>Options<span><a class="mark" href="#all_options" id="all_options">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>Each class takes an options object. All options are optional. (The
|
||
convenience methods use the default settings for all options.)
|
||
|
||
</p>
|
||
<p>Note that some options are only
|
||
relevant when compressing, and are ignored by the decompression classes.
|
||
|
||
</p>
|
||
<ul>
|
||
<li>chunkSize (default: 16*1024)</li>
|
||
<li>windowBits</li>
|
||
<li>level (compression only)</li>
|
||
<li>memLevel (compression only)</li>
|
||
<li>strategy (compression only)</li>
|
||
<li>dictionary (deflate/inflate only, empty dictionary by default)</li>
|
||
</ul>
|
||
<p>See the description of <code>deflateInit2</code> and <code>inflateInit2</code>
|
||
at <a href="http://zlib.net/manual.html#Advanced">http://zlib.net/manual.html#Advanced</a> for more information on these.
|
||
|
||
</p>
|
||
<h2>Memory Usage Tuning<span><a class="mark" href="#all_memory_usage_tuning" id="all_memory_usage_tuning">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>From <code>zlib/zconf.h</code>, modified to node's usage:
|
||
|
||
</p>
|
||
<p>The memory requirements for deflate are (in bytes):
|
||
|
||
</p>
|
||
<pre><code>(1 << (windowBits+2)) + (1 << (memLevel+9))</code></pre>
|
||
<p>that is: 128K for windowBits=15 + 128K for memLevel = 8
|
||
(default values) plus a few kilobytes for small objects.
|
||
|
||
</p>
|
||
<p>For example, if you want to reduce
|
||
the default memory requirements from 256K to 128K, set the options to:
|
||
|
||
</p>
|
||
<pre><code>{ windowBits: 14, memLevel: 7 }</code></pre>
|
||
<p>Of course this will generally degrade compression (there's no free lunch).
|
||
|
||
</p>
|
||
<p>The memory requirements for inflate are (in bytes)
|
||
|
||
</p>
|
||
<pre><code>1 << windowBits</code></pre>
|
||
<p>that is, 32K for windowBits=15 (default value) plus a few kilobytes
|
||
for small objects.
|
||
|
||
</p>
|
||
<p>This is in addition to a single internal output slab buffer of size
|
||
<code>chunkSize</code>, which defaults to 16K.
|
||
|
||
</p>
|
||
<p>The speed of zlib compression is affected most dramatically by the
|
||
<code>level</code> setting. A higher level will result in better compression, but
|
||
will take longer to complete. A lower level will result in less
|
||
compression, but will be much faster.
|
||
|
||
</p>
|
||
<p>In general, greater memory usage options will mean that node has to make
|
||
fewer calls to zlib, since it'll be able to process more data in a
|
||
single <code>write</code> operation. So, this is another factor that affects the
|
||
speed, at the cost of memory usage.
|
||
|
||
</p>
|
||
<h2>Constants<span><a class="mark" href="#all_constants" id="all_constants">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>All of the constants defined in zlib.h are also defined on
|
||
<code>require('zlib')</code>.
|
||
In the normal course of operations, you will not need to ever set any of
|
||
these. They are documented here so that their presence is not
|
||
surprising. This section is taken almost directly from the <a href="http://zlib.net/manual.html#Constants">zlib
|
||
documentation</a>. See
|
||
</p>
|
||
<p><a href="http://zlib.net/manual.html#Constants">http://zlib.net/manual.html#Constants</a> for more details.
|
||
|
||
</p>
|
||
<p>Allowed flush values.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>zlib.Z_NO_FLUSH</code></li>
|
||
<li><code>zlib.Z_PARTIAL_FLUSH</code></li>
|
||
<li><code>zlib.Z_SYNC_FLUSH</code></li>
|
||
<li><code>zlib.Z_FULL_FLUSH</code></li>
|
||
<li><code>zlib.Z_FINISH</code></li>
|
||
<li><code>zlib.Z_BLOCK</code></li>
|
||
<li><code>zlib.Z_TREES</code></li>
|
||
</ul>
|
||
<p>Return codes for the compression/decompression functions. Negative
|
||
values are errors, positive values are used for special but normal
|
||
events.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>zlib.Z_OK</code></li>
|
||
<li><code>zlib.Z_STREAM_END</code></li>
|
||
<li><code>zlib.Z_NEED_DICT</code></li>
|
||
<li><code>zlib.Z_ERRNO</code></li>
|
||
<li><code>zlib.Z_STREAM_ERROR</code></li>
|
||
<li><code>zlib.Z_DATA_ERROR</code></li>
|
||
<li><code>zlib.Z_MEM_ERROR</code></li>
|
||
<li><code>zlib.Z_BUF_ERROR</code></li>
|
||
<li><code>zlib.Z_VERSION_ERROR</code></li>
|
||
</ul>
|
||
<p>Compression levels.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>zlib.Z_NO_COMPRESSION</code></li>
|
||
<li><code>zlib.Z_BEST_SPEED</code></li>
|
||
<li><code>zlib.Z_BEST_COMPRESSION</code></li>
|
||
<li><code>zlib.Z_DEFAULT_COMPRESSION</code></li>
|
||
</ul>
|
||
<p>Compression strategy.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>zlib.Z_FILTERED</code></li>
|
||
<li><code>zlib.Z_HUFFMAN_ONLY</code></li>
|
||
<li><code>zlib.Z_RLE</code></li>
|
||
<li><code>zlib.Z_FIXED</code></li>
|
||
<li><code>zlib.Z_DEFAULT_STRATEGY</code></li>
|
||
</ul>
|
||
<p>Possible values of the data_type field.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>zlib.Z_BINARY</code></li>
|
||
<li><code>zlib.Z_TEXT</code></li>
|
||
<li><code>zlib.Z_ASCII</code></li>
|
||
<li><code>zlib.Z_UNKNOWN</code></li>
|
||
</ul>
|
||
<p>The deflate compression method (the only one supported in this version).
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>zlib.Z_DEFLATED</code></li>
|
||
</ul>
|
||
<p>For initializing zalloc, zfree, opaque.
|
||
|
||
</p>
|
||
<ul>
|
||
<li><code>zlib.Z_NULL</code></li>
|
||
</ul>
|
||
<h1>os<span><a class="mark" href="#all_os" id="all_os">#</a></span></h1>
|
||
<pre><code>Stability: 4 - API Frozen</code></pre>
|
||
<p>Provides a few basic operating-system related utility functions.
|
||
|
||
</p>
|
||
<p>Use <code>require('os')</code> to access this module.
|
||
|
||
</p>
|
||
<h2>os.tmpDir()<span><a class="mark" href="#all_os_tmpdir" id="all_os_tmpdir">#</a></span></h2>
|
||
<p>Returns the operating system's default directory for temp files.
|
||
|
||
</p>
|
||
<h2>os.hostname()<span><a class="mark" href="#all_os_hostname" id="all_os_hostname">#</a></span></h2>
|
||
<p>Returns the hostname of the operating system.
|
||
|
||
</p>
|
||
<h2>os.type()<span><a class="mark" href="#all_os_type" id="all_os_type">#</a></span></h2>
|
||
<p>Returns the operating system name.
|
||
|
||
</p>
|
||
<h2>os.platform()<span><a class="mark" href="#all_os_platform" id="all_os_platform">#</a></span></h2>
|
||
<p>Returns the operating system platform.
|
||
|
||
</p>
|
||
<h2>os.arch()<span><a class="mark" href="#all_os_arch" id="all_os_arch">#</a></span></h2>
|
||
<p>Returns the operating system CPU architecture.
|
||
|
||
</p>
|
||
<h2>os.release()<span><a class="mark" href="#all_os_release" id="all_os_release">#</a></span></h2>
|
||
<p>Returns the operating system release.
|
||
|
||
</p>
|
||
<h2>os.uptime()<span><a class="mark" href="#all_os_uptime" id="all_os_uptime">#</a></span></h2>
|
||
<p>Returns the system uptime in seconds.
|
||
|
||
</p>
|
||
<h2>os.loadavg()<span><a class="mark" href="#all_os_loadavg" id="all_os_loadavg">#</a></span></h2>
|
||
<p>Returns an array containing the 1, 5, and 15 minute load averages.
|
||
|
||
</p>
|
||
<h2>os.totalmem()<span><a class="mark" href="#all_os_totalmem" id="all_os_totalmem">#</a></span></h2>
|
||
<p>Returns the total amount of system memory in bytes.
|
||
|
||
</p>
|
||
<h2>os.freemem()<span><a class="mark" href="#all_os_freemem" id="all_os_freemem">#</a></span></h2>
|
||
<p>Returns the amount of free system memory in bytes.
|
||
|
||
</p>
|
||
<h2>os.cpus()<span><a class="mark" href="#all_os_cpus" id="all_os_cpus">#</a></span></h2>
|
||
<p>Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq).
|
||
|
||
</p>
|
||
<p>Example inspection of os.cpus:
|
||
|
||
</p>
|
||
<pre><code>[ { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||
speed: 2926,
|
||
times:
|
||
{ user: 252020,
|
||
nice: 0,
|
||
sys: 30340,
|
||
idle: 1070356870,
|
||
irq: 0 } },
|
||
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||
speed: 2926,
|
||
times:
|
||
{ user: 306960,
|
||
nice: 0,
|
||
sys: 26980,
|
||
idle: 1071569080,
|
||
irq: 0 } },
|
||
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||
speed: 2926,
|
||
times:
|
||
{ user: 248450,
|
||
nice: 0,
|
||
sys: 21750,
|
||
idle: 1070919370,
|
||
irq: 0 } },
|
||
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||
speed: 2926,
|
||
times:
|
||
{ user: 256880,
|
||
nice: 0,
|
||
sys: 19430,
|
||
idle: 1070905480,
|
||
irq: 20 } },
|
||
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||
speed: 2926,
|
||
times:
|
||
{ user: 511580,
|
||
nice: 20,
|
||
sys: 40900,
|
||
idle: 1070842510,
|
||
irq: 0 } },
|
||
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||
speed: 2926,
|
||
times:
|
||
{ user: 291660,
|
||
nice: 0,
|
||
sys: 34360,
|
||
idle: 1070888000,
|
||
irq: 10 } },
|
||
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||
speed: 2926,
|
||
times:
|
||
{ user: 308260,
|
||
nice: 0,
|
||
sys: 55410,
|
||
idle: 1071129970,
|
||
irq: 880 } },
|
||
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||
speed: 2926,
|
||
times:
|
||
{ user: 266450,
|
||
nice: 1480,
|
||
sys: 34920,
|
||
idle: 1072572010,
|
||
irq: 30 } } ]</code></pre>
|
||
<h2>os.networkInterfaces()<span><a class="mark" href="#all_os_networkinterfaces" id="all_os_networkinterfaces">#</a></span></h2>
|
||
<p>Get a list of network interfaces:
|
||
|
||
</p>
|
||
<pre><code>{ lo0:
|
||
[ { address: '::1', family: 'IPv6', internal: true },
|
||
{ address: 'fe80::1', family: 'IPv6', internal: true },
|
||
{ address: '127.0.0.1', family: 'IPv4', internal: true } ],
|
||
en1:
|
||
[ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',
|
||
internal: false },
|
||
{ address: '10.0.1.123', family: 'IPv4', internal: false } ],
|
||
vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],
|
||
vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],
|
||
ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }</code></pre>
|
||
<h2>os.EOL<span><a class="mark" href="#all_os_eol" id="all_os_eol">#</a></span></h2>
|
||
<p>A constant defining the appropriate End-of-line marker for the operating system.
|
||
|
||
</p>
|
||
<h1>Debugger<span><a class="mark" href="#all_debugger" id="all_debugger">#</a></span></h1>
|
||
<pre><code>Stability: 3 - Stable</code></pre>
|
||
<!-- type=misc -->
|
||
|
||
<p>V8 comes with an extensive debugger which is accessible out-of-process via a
|
||
simple <a href="http://code.google.com/p/v8/wiki/DebuggerProtocol">TCP protocol</a>.
|
||
Node has a built-in client for this debugger. To use this, start Node with the
|
||
<code>debug</code> argument; a prompt will appear:
|
||
|
||
</p>
|
||
<pre><code>% node debug myscript.js
|
||
< debugger listening on port 5858
|
||
connecting... ok
|
||
break in /home/indutny/Code/git/indutny/myscript.js:1
|
||
1 x = 5;
|
||
2 setTimeout(function () {
|
||
3 debugger;
|
||
debug></code></pre>
|
||
<p>Node's debugger client doesn't support the full range of commands, but
|
||
simple step and inspection is possible. By putting the statement <code>debugger;</code>
|
||
into the source code of your script, you will enable a breakpoint.
|
||
|
||
</p>
|
||
<p>For example, suppose <code>myscript.js</code> looked like this:
|
||
|
||
</p>
|
||
<pre><code>// myscript.js
|
||
x = 5;
|
||
setTimeout(function () {
|
||
debugger;
|
||
console.log("world");
|
||
}, 1000);
|
||
console.log("hello");</code></pre>
|
||
<p>Then once the debugger is run, it will break on line 4.
|
||
|
||
</p>
|
||
<pre><code>% node debug myscript.js
|
||
< debugger listening on port 5858
|
||
connecting... ok
|
||
break in /home/indutny/Code/git/indutny/myscript.js:1
|
||
1 x = 5;
|
||
2 setTimeout(function () {
|
||
3 debugger;
|
||
debug> cont
|
||
< hello
|
||
break in /home/indutny/Code/git/indutny/myscript.js:3
|
||
1 x = 5;
|
||
2 setTimeout(function () {
|
||
3 debugger;
|
||
4 console.log("world");
|
||
5 }, 1000);
|
||
debug> next
|
||
break in /home/indutny/Code/git/indutny/myscript.js:4
|
||
2 setTimeout(function () {
|
||
3 debugger;
|
||
4 console.log("world");
|
||
5 }, 1000);
|
||
6 console.log("hello");
|
||
debug> repl
|
||
Press Ctrl + C to leave debug repl
|
||
> x
|
||
5
|
||
> 2+2
|
||
4
|
||
debug> next
|
||
< world
|
||
break in /home/indutny/Code/git/indutny/myscript.js:5
|
||
3 debugger;
|
||
4 console.log("world");
|
||
5 }, 1000);
|
||
6 console.log("hello");
|
||
7
|
||
debug> quit
|
||
%</code></pre>
|
||
<p>The <code>repl</code> command allows you to evaluate code remotely. The <code>next</code> command
|
||
steps over to the next line. There are a few other commands available and more
|
||
to come. Type <code>help</code> to see others.
|
||
|
||
</p>
|
||
<h2>Watchers<span><a class="mark" href="#all_watchers" id="all_watchers">#</a></span></h2>
|
||
<p>You can watch expression and variable values while debugging your code.
|
||
On every breakpoint each expression from the watchers list will be evaluated
|
||
in the current context and displayed just before the breakpoint's source code
|
||
listing.
|
||
|
||
</p>
|
||
<p>To start watching an expression, type <code>watch("my_expression")</code>. <code>watchers</code>
|
||
prints the active watchers. To remove a watcher, type
|
||
<code>unwatch("my_expression")</code>.
|
||
|
||
</p>
|
||
<h2>Commands reference<span><a class="mark" href="#all_commands_reference" id="all_commands_reference">#</a></span></h2>
|
||
<h3>Stepping<span><a class="mark" href="#all_stepping" id="all_stepping">#</a></span></h3>
|
||
<ul>
|
||
<li><code>cont</code>, <code>c</code> - Continue execution</li>
|
||
<li><code>next</code>, <code>n</code> - Step next</li>
|
||
<li><code>step</code>, <code>s</code> - Step in</li>
|
||
<li><code>out</code>, <code>o</code> - Step out</li>
|
||
<li><code>pause</code> - Pause running code (like pause button in Developer TOols)</li>
|
||
</ul>
|
||
<h3>Breakpoints<span><a class="mark" href="#all_breakpoints" id="all_breakpoints">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>setBreakpoint()</code>, <code>sb()</code> - Set breakpoint on current line</li>
|
||
<li><code>setBreakpoint(line)</code>, <code>sb(line)</code> - Set breakpoint on specific line</li>
|
||
<li><code>setBreakpoint('fn()')</code>, <code>sb(...)</code> - Set breakpoint on a first statement in
|
||
functions body</li>
|
||
<li><code>setBreakpoint('script.js', 1)</code>, <code>sb(...)</code> - Set breakpoint on first line of
|
||
script.js</li>
|
||
<li><code>clearBreakpoint</code>, <code>cb(...)</code> - Clear breakpoint</li>
|
||
</div></ul>
|
||
<h3>Info<span><a class="mark" href="#all_info" id="all_info">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>backtrace</code>, <code>bt</code> - Print backtrace of current execution frame</li>
|
||
<li><code>list(5)</code> - List scripts source code with 5 line context (5 lines before and
|
||
after)</li>
|
||
<li><code>watch(expr)</code> - Add expression to watch list</li>
|
||
<li><code>unwatch(expr)</code> - Remove expression from watch list</li>
|
||
<li><code>watchers</code> - List all watchers and their values (automatically listed on each
|
||
breakpoint)</li>
|
||
<li><code>repl</code> - Open debugger's repl for evaluation in debugging script's context</li>
|
||
</div></ul>
|
||
<h3>Execution control<span><a class="mark" href="#all_execution_control" id="all_execution_control">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>run</code> - Run script (automatically runs on debugger's start)</li>
|
||
<li><code>restart</code> - Restart script</li>
|
||
<li><code>kill</code> - Kill script</li>
|
||
</div></ul>
|
||
<h3>Various<span><a class="mark" href="#all_various" id="all_various">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>scripts</code> - List all loaded scripts</li>
|
||
<li><code>version</code> - Display v8's version</li>
|
||
</div></ul>
|
||
<h2>Advanced Usage<span><a class="mark" href="#all_advanced_usage" id="all_advanced_usage">#</a></span></h2>
|
||
<p>The V8 debugger can be enabled and accessed either by starting Node with
|
||
the <code>--debug</code> command-line flag or by signaling an existing Node process
|
||
with <code>SIGUSR1</code>.
|
||
|
||
</p>
|
||
<h1>Cluster<span><a class="mark" href="#all_cluster" id="all_cluster">#</a></span></h1>
|
||
<pre><code>Stability: 1 - Experimental</code></pre>
|
||
<p>A single instance of Node runs in a single thread. To take advantage of
|
||
multi-core systems the user will sometimes want to launch a cluster of Node
|
||
processes to handle the load.
|
||
|
||
</p>
|
||
<p>The cluster module allows you to easily create a network of processes that
|
||
all share server ports.
|
||
|
||
</p>
|
||
<pre><code>var cluster = require('cluster');
|
||
var http = require('http');
|
||
var numCPUs = require('os').cpus().length;
|
||
|
||
if (cluster.isMaster) {
|
||
// Fork workers.
|
||
for (var i = 0; i < numCPUs; i++) {
|
||
cluster.fork();
|
||
}
|
||
|
||
cluster.on('exit', function(worker, code, signal) {
|
||
console.log('worker ' + worker.process.pid + ' died');
|
||
});
|
||
} else {
|
||
// Workers can share any TCP connection
|
||
// In this case its a HTTP server
|
||
http.createServer(function(req, res) {
|
||
res.writeHead(200);
|
||
res.end("hello world\n");
|
||
}).listen(8000);
|
||
}</code></pre>
|
||
<p>Running node will now share port 8000 between the workers:
|
||
|
||
</p>
|
||
<pre><code>% node server.js
|
||
Worker 2438 online
|
||
Worker 2437 online</code></pre>
|
||
<p>This feature was introduced recently, and may change in future versions.
|
||
Please try it out and provide feedback.
|
||
|
||
</p>
|
||
<p>Also note that, on Windows, it is not yet possible to set up a named pipe
|
||
server in a worker.
|
||
|
||
</p>
|
||
<h2>How It Works<span><a class="mark" href="#all_how_it_works" id="all_how_it_works">#</a></span></h2>
|
||
<!--type=misc-->
|
||
|
||
<p>The worker processes are spawned using the <code>child_process.fork</code> method,
|
||
so that they can communicate with the parent via IPC and pass server
|
||
handles back and forth.
|
||
|
||
</p>
|
||
<p>When you call <code>server.listen(...)</code> in a worker, it serializes the
|
||
arguments and passes the request to the master process. If the master
|
||
process already has a listening server matching the worker's
|
||
requirements, then it passes the handle to the worker. If it does not
|
||
already have a listening server matching that requirement, then it will
|
||
create one, and pass the handle to the child.
|
||
|
||
</p>
|
||
<p>This causes potentially surprising behavior in three edge cases:
|
||
|
||
</p>
|
||
<ol>
|
||
<li><code>server.listen({fd: 7})</code> Because the message is passed to the master,
|
||
file descriptor 7 <strong>in the parent</strong> will be listened on, and the
|
||
handle passed to the worker, rather than listening to the worker's
|
||
idea of what the number 7 file descriptor references.</li>
|
||
<li><code>server.listen(handle)</code> Listening on handles explicitly will cause
|
||
the worker to use the supplied handle, rather than talk to the master
|
||
process. If the worker already has the handle, then it's presumed
|
||
that you know what you are doing.</li>
|
||
<li><code>server.listen(0)</code> Normally, this will cause servers to listen on a
|
||
random port. However, in a cluster, each worker will receive the
|
||
same "random" port each time they do <code>listen(0)</code>. In essence, the
|
||
port is random the first time, but predictable thereafter. If you
|
||
want to listen on a unique port, generate a port number based on the
|
||
cluster worker ID.</li>
|
||
</ol>
|
||
<p>When multiple processes are all <code>accept()</code>ing on the same underlying
|
||
resource, the operating system load-balances across them very
|
||
efficiently. There is no routing logic in Node.js, or in your program,
|
||
and no shared state between the workers. Therefore, it is important to
|
||
design your program such that it does not rely too heavily on in-memory
|
||
data objects for things like sessions and login.
|
||
|
||
</p>
|
||
<p>Because workers are all separate processes, they can be killed or
|
||
re-spawned depending on your program's needs, without affecting other
|
||
workers. As long as there are some workers still alive, the server will
|
||
continue to accept connections. Node does not automatically manage the
|
||
number of workers for you, however. It is your responsibility to manage
|
||
the worker pool for your application's needs.
|
||
|
||
</p>
|
||
<h2>cluster.settings<span><a class="mark" href="#all_cluster_settings" id="all_cluster_settings">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Object</span><ul>
|
||
<li><code>exec</code> <span class="type">String</span> file path to worker file. (Default=<code>__filename</code>)</li>
|
||
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
|
||
(Default=<code>process.argv.slice(2)</code>)</li>
|
||
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent's stdio.
|
||
(Default=<code>false</code>)</li>
|
||
</ul>
|
||
</li>
|
||
</div></ul>
|
||
<p>All settings set by the <code>.setupMaster</code> is stored in this settings object.
|
||
This object is not supposed to be change or set manually, by you.
|
||
|
||
</p>
|
||
<h2>cluster.isMaster<span><a class="mark" href="#all_cluster_ismaster" id="all_cluster_ismaster">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Boolean</span></li>
|
||
</div></ul>
|
||
<p>True if the process is a master. This is determined
|
||
by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is
|
||
undefined, then <code>isMaster</code> is <code>true</code>.
|
||
|
||
</p>
|
||
<h2>cluster.isWorker<span><a class="mark" href="#all_cluster_isworker" id="all_cluster_isworker">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Boolean</span></li>
|
||
</div></ul>
|
||
<p>This boolean flag is true if the process is a worker forked from a master.
|
||
If the <code>process.env.NODE_UNIQUE_ID</code> is set to a value, then
|
||
<code>isWorker</code> is <code>true</code>.
|
||
|
||
</p>
|
||
<h2>Event: 'fork'<span><a class="mark" href="#all_event_fork" id="all_event_fork">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>worker</code> <span class="type">Worker object</span></li>
|
||
</div></ul>
|
||
<p>When a new worker is forked the cluster module will emit a 'fork' event.
|
||
This can be used to log worker activity, and create you own timeout.
|
||
|
||
</p>
|
||
<pre><code>var timeouts = [];
|
||
function errorMsg() {
|
||
console.error("Something must be wrong with the connection ...");
|
||
}
|
||
|
||
cluster.on('fork', function(worker) {
|
||
timeouts[worker.id] = setTimeout(errorMsg, 2000);
|
||
});
|
||
cluster.on('listening', function(worker, address) {
|
||
clearTimeout(timeouts[worker.id]);
|
||
});
|
||
cluster.on('exit', function(worker, code, signal) {
|
||
clearTimeout(timeouts[worker.id]);
|
||
errorMsg();
|
||
});</code></pre>
|
||
<h2>Event: 'online'<span><a class="mark" href="#all_event_online" id="all_event_online">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>worker</code> <span class="type">Worker object</span></li>
|
||
</div></ul>
|
||
<p>After forking a new worker, the worker should respond with a online message.
|
||
When the master receives a online message it will emit such event.
|
||
The difference between 'fork' and 'online' is that fork is emitted when the
|
||
master tries to fork a worker, and 'online' is emitted when the worker is
|
||
being executed.
|
||
|
||
</p>
|
||
<pre><code>cluster.on('online', function(worker) {
|
||
console.log("Yay, the worker responded after it was forked");
|
||
});</code></pre>
|
||
<h2>Event: 'listening'<span><a class="mark" href="#all_event_listening_2" id="all_event_listening_2">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>worker</code> <span class="type">Worker object</span></li>
|
||
<li><code>address</code> <span class="type">Object</span></li>
|
||
</div></ul>
|
||
<p>When calling <code>listen()</code> from a worker, a 'listening' event is automatically assigned
|
||
to the server instance. When the server is listening a message is send to the master
|
||
where the 'listening' event is emitted.
|
||
|
||
</p>
|
||
<p>The event handler is executed with two arguments, the <code>worker</code> contains the worker
|
||
object and the <code>address</code> object contains the following connection properties:
|
||
<code>address</code>, <code>port</code> and <code>addressType</code>. This is very useful if the worker is listening
|
||
on more than one address.
|
||
|
||
</p>
|
||
<pre><code>cluster.on('listening', function(worker, address) {
|
||
console.log("A worker is now connected to " + address.address + ":" + address.port);
|
||
});</code></pre>
|
||
<h2>Event: 'disconnect'<span><a class="mark" href="#all_event_disconnect_1" id="all_event_disconnect_1">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>worker</code> <span class="type">Worker object</span></li>
|
||
</div></ul>
|
||
<p>When a workers IPC channel has disconnected this event is emitted. This will happen
|
||
when the worker dies, usually after calling <code>.destroy()</code>.
|
||
|
||
</p>
|
||
<p>When calling <code>.disconnect()</code>, there may be a delay between the
|
||
<code>disconnect</code> and <code>exit</code> events. This event can be used to detect if
|
||
the process is stuck in a cleanup or if there are long-living
|
||
connections.
|
||
|
||
</p>
|
||
<pre><code>cluster.on('disconnect', function(worker) {
|
||
console.log('The worker #' + worker.id + ' has disconnected');
|
||
});</code></pre>
|
||
<h2>Event: 'exit'<span><a class="mark" href="#all_event_exit_3" id="all_event_exit_3">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>worker</code> <span class="type">Worker object</span></li>
|
||
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
|
||
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>'SIGHUP'</code>) that caused
|
||
the process to be killed.</li>
|
||
</div></ul>
|
||
<p>When any of the workers die the cluster module will emit the 'exit' event.
|
||
This can be used to restart the worker by calling <code>fork()</code> again.
|
||
|
||
</p>
|
||
<pre><code>cluster.on('exit', function(worker, code, signal) {
|
||
var exitCode = worker.process.exitCode;
|
||
console.log('worker ' + worker.process.pid + ' died ('+exitCode+'). restarting...');
|
||
cluster.fork();
|
||
});</code></pre>
|
||
<h2>Event: 'setup'<span><a class="mark" href="#all_event_setup" id="all_event_setup">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>worker</code> <span class="type">Worker object</span></li>
|
||
</div></ul>
|
||
<p>When the <code>.setupMaster()</code> function has been executed this event emits.
|
||
If <code>.setupMaster()</code> was not executed before <code>fork()</code> this function will
|
||
call <code>.setupMaster()</code> with no arguments.
|
||
|
||
</p>
|
||
<h2>cluster.setupMaster([settings])<span><a class="mark" href="#all_cluster_setupmaster_settings" id="all_cluster_setupmaster_settings">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>settings</code> <span class="type">Object</span><ul>
|
||
<li><code>exec</code> <span class="type">String</span> file path to worker file. (Default=<code>__filename</code>)</li>
|
||
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
|
||
(Default=<code>process.argv.slice(2)</code>)</li>
|
||
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent's stdio.
|
||
(Default=<code>false</code>)</li>
|
||
</ul>
|
||
</li>
|
||
</div></ul>
|
||
<p><code>setupMaster</code> is used to change the default 'fork' behavior. The new settings
|
||
are effective immediately and permanently, they cannot be changed later on.
|
||
|
||
</p>
|
||
<p>Example:
|
||
|
||
</p>
|
||
<pre><code>var cluster = require("cluster");
|
||
cluster.setupMaster({
|
||
exec : "worker.js",
|
||
args : ["--use", "https"],
|
||
silent : true
|
||
});
|
||
cluster.fork();</code></pre>
|
||
<h2>cluster.fork([env])<span><a class="mark" href="#all_cluster_fork_env" id="all_cluster_fork_env">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>env</code> <span class="type">Object</span> Key/value pairs to add to child process environment.</li>
|
||
<li>return <span class="type">Worker object</span></li>
|
||
</div></ul>
|
||
<p>Spawn a new worker process. This can only be called from the master process.
|
||
|
||
</p>
|
||
<h2>cluster.disconnect([callback])<span><a class="mark" href="#all_cluster_disconnect_callback" id="all_cluster_disconnect_callback">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><code>callback</code> <span class="type">Function</span> called when all workers are disconnected and handlers are closed</li>
|
||
</div></ul>
|
||
<p>When calling this method, all workers will commit a graceful suicide. When they are
|
||
disconnected all internal handlers will be closed, allowing the master process to
|
||
die graceful if no other event is waiting.
|
||
|
||
</p>
|
||
<p>The method takes an optional callback argument which will be called when finished.
|
||
|
||
</p>
|
||
<h2>cluster.worker<span><a class="mark" href="#all_cluster_worker" id="all_cluster_worker">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Object</span></li>
|
||
</div></ul>
|
||
<p>A reference to the current worker object. Not available in the master process.
|
||
|
||
</p>
|
||
<pre><code>var cluster = require('cluster');
|
||
|
||
if (cluster.isMaster) {
|
||
console.log('I am master');
|
||
cluster.fork();
|
||
cluster.fork();
|
||
} else if (cluster.isWorker) {
|
||
console.log('I am worker #' + cluster.worker.id);
|
||
}</code></pre>
|
||
<h2>cluster.workers<span><a class="mark" href="#all_cluster_workers" id="all_cluster_workers">#</a></span></h2>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Object</span></li>
|
||
</div></ul>
|
||
<p>A hash that stores the active worker objects, keyed by <code>id</code> field. Makes it
|
||
easy to loop through all the workers. It is only available in the master
|
||
process.
|
||
|
||
</p>
|
||
<pre><code>// Go through all workers
|
||
function eachWorker(callback) {
|
||
for (var id in cluster.workers) {
|
||
callback(cluster.workers[id]);
|
||
}
|
||
}
|
||
eachWorker(function(worker) {
|
||
worker.send('big announcement to all workers');
|
||
});</code></pre>
|
||
<p>Should you wish to reference a worker over a communication channel, using
|
||
the worker's unique id is the easiest way to find the worker.
|
||
|
||
</p>
|
||
<pre><code>socket.on('data', function(id) {
|
||
var worker = cluster.workers[id];
|
||
});</code></pre>
|
||
<h2>Class: Worker<span><a class="mark" href="#all_class_worker" id="all_class_worker">#</a></span></h2>
|
||
<p>A Worker object contains all public information and method about a worker.
|
||
In the master it can be obtained using <code>cluster.workers</code>. In a worker
|
||
it can be obtained using <code>cluster.worker</code>.
|
||
|
||
</p>
|
||
<h3>worker.id<span><a class="mark" href="#all_worker_id" id="all_worker_id">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">String</span></li>
|
||
</div></ul>
|
||
<p>Each new worker is given its own unique id, this id is stored in the
|
||
<code>id</code>.
|
||
|
||
</p>
|
||
<p>While a worker is alive, this is the key that indexes it in
|
||
cluster.workers
|
||
|
||
</p>
|
||
<h3>worker.process<span><a class="mark" href="#all_worker_process" id="all_worker_process">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">ChildProcess object</span></li>
|
||
</div></ul>
|
||
<p>All workers are created using <code>child_process.fork()</code>, the returned object
|
||
from this function is stored in process.
|
||
|
||
</p>
|
||
<p>See: <a href="child_process.html">Child Process module</a>
|
||
|
||
</p>
|
||
<h3>worker.suicide<span><a class="mark" href="#all_worker_suicide" id="all_worker_suicide">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><span class="type">Boolean</span></li>
|
||
</div></ul>
|
||
<p>This property is a boolean. It is set when a worker dies after calling <code>.destroy()</code>
|
||
or immediately after calling the <code>.disconnect()</code> method. Until then it is <code>undefined</code>.
|
||
|
||
</p>
|
||
<h3>worker.send(message, [sendHandle])<span><a class="mark" href="#all_worker_send_message_sendhandle" id="all_worker_send_message_sendhandle">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>message</code> <span class="type">Object</span></li>
|
||
<li><code>sendHandle</code> <span class="type">Handle object</span></li>
|
||
</div></ul>
|
||
<p>This function is equal to the send methods provided by
|
||
<code>child_process.fork()</code>. In the master you should use this function to
|
||
send a message to a specific worker. However in a worker you can also use
|
||
<code>process.send(message)</code>, since this is the same function.
|
||
|
||
</p>
|
||
<p>This example will echo back all messages from the master:
|
||
|
||
</p>
|
||
<pre><code>if (cluster.isMaster) {
|
||
var worker = cluster.fork();
|
||
worker.send('hi there');
|
||
|
||
} else if (cluster.isWorker) {
|
||
process.on('message', function(msg) {
|
||
process.send(msg);
|
||
});
|
||
}</code></pre>
|
||
<h3>worker.destroy()<span><a class="mark" href="#all_worker_destroy" id="all_worker_destroy">#</a></span></h3>
|
||
<p>This function will kill the worker, and inform the master to not spawn a
|
||
new worker. The boolean <code>suicide</code> lets you distinguish between voluntary
|
||
and accidental exit.
|
||
|
||
</p>
|
||
<pre><code>cluster.on('exit', function(worker, code, signal) {
|
||
if (worker.suicide === true) {
|
||
console.log('Oh, it was just suicide\' – no need to worry').
|
||
}
|
||
});
|
||
|
||
// destroy worker
|
||
worker.destroy();</code></pre>
|
||
<h3>worker.disconnect()<span><a class="mark" href="#all_worker_disconnect" id="all_worker_disconnect">#</a></span></h3>
|
||
<p>When calling this function the worker will no longer accept new connections, but
|
||
they will be handled by any other listening worker. Existing connection will be
|
||
allowed to exit as usual. When no more connections exist, the IPC channel to the worker
|
||
will close allowing it to die graceful. When the IPC channel is closed the <code>disconnect</code>
|
||
event will emit, this is then followed by the <code>exit</code> event, there is emitted when
|
||
the worker finally die.
|
||
|
||
</p>
|
||
<p>Because there might be long living connections, it is useful to implement a timeout.
|
||
This example ask the worker to disconnect and after 2 seconds it will destroy the
|
||
server. An alternative would be to execute <code>worker.destroy()</code> after 2 seconds, but
|
||
that would normally not allow the worker to do any cleanup if needed.
|
||
|
||
</p>
|
||
<pre><code>if (cluster.isMaster) {
|
||
var worker = cluster.fork();
|
||
var timeout;
|
||
|
||
worker.on('listening', function(address) {
|
||
worker.disconnect();
|
||
timeout = setTimeout(function() {
|
||
worker.send('force kill');
|
||
}, 2000);
|
||
});
|
||
|
||
worker.on('disconnect', function() {
|
||
clearTimeout(timeout);
|
||
});
|
||
|
||
} else if (cluster.isWorker) {
|
||
var net = require('net');
|
||
var server = net.createServer(function(socket) {
|
||
// connection never end
|
||
});
|
||
|
||
server.listen(8000);
|
||
|
||
server.on('close', function() {
|
||
// cleanup
|
||
});
|
||
|
||
process.on('message', function(msg) {
|
||
if (msg === 'force kill') {
|
||
server.destroy();
|
||
}
|
||
});
|
||
}</code></pre>
|
||
<h3>Event: 'message'<span><a class="mark" href="#all_event_message_2" id="all_event_message_2">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>message</code> <span class="type">Object</span></li>
|
||
</div></ul>
|
||
<p>This event is the same as the one provided by <code>child_process.fork()</code>.
|
||
In the master you should use this event, however in a worker you can also use
|
||
<code>process.on('message')</code>
|
||
|
||
</p>
|
||
<p>As an example, here is a cluster that keeps count of the number of requests
|
||
in the master process using the message system:
|
||
|
||
</p>
|
||
<pre><code>var cluster = require('cluster');
|
||
var http = require('http');
|
||
|
||
if (cluster.isMaster) {
|
||
|
||
// Keep track of http requests
|
||
var numReqs = 0;
|
||
setInterval(function() {
|
||
console.log("numReqs =", numReqs);
|
||
}, 1000);
|
||
|
||
// Count requestes
|
||
function messageHandler(msg) {
|
||
if (msg.cmd && msg.cmd == 'notifyRequest') {
|
||
numReqs += 1;
|
||
}
|
||
}
|
||
|
||
// Start workers and listen for messages containing notifyRequest
|
||
var numCPUs = require('os').cpus().length;
|
||
for (var i = 0; i < numCPUs; i++) {
|
||
cluster.fork();
|
||
}
|
||
|
||
Object.keys(cluster.workers).forEach(function(id) {
|
||
cluster.workers[id].on('message', messageHandler);
|
||
});
|
||
|
||
} else {
|
||
|
||
// Worker processes have a http server.
|
||
http.Server(function(req, res) {
|
||
res.writeHead(200);
|
||
res.end("hello world\n");
|
||
|
||
// notify master about the request
|
||
process.send({ cmd: 'notifyRequest' });
|
||
}).listen(8000);
|
||
}</code></pre>
|
||
<h3>Event: 'online'<span><a class="mark" href="#all_event_online_1" id="all_event_online_1">#</a></span></h3>
|
||
<p>Same as the <code>cluster.on('online')</code> event, but emits only when the state change
|
||
on the specified worker.
|
||
|
||
</p>
|
||
<pre><code>cluster.fork().on('online', function() {
|
||
// Worker is online
|
||
};</code></pre>
|
||
<h3>Event: 'listening'<span><a class="mark" href="#all_event_listening_3" id="all_event_listening_3">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>address</code> <span class="type">Object</span></li>
|
||
</div></ul>
|
||
<p>Same as the <code>cluster.on('listening')</code> event, but emits only when the state change
|
||
on the specified worker.
|
||
|
||
</p>
|
||
<pre><code>cluster.fork().on('listening', function(address) {
|
||
// Worker is listening
|
||
};</code></pre>
|
||
<h3>Event: 'disconnect'<span><a class="mark" href="#all_event_disconnect_2" id="all_event_disconnect_2">#</a></span></h3>
|
||
<p>Same as the <code>cluster.on('disconnect')</code> event, but emits only when the state change
|
||
on the specified worker.
|
||
|
||
</p>
|
||
<pre><code>cluster.fork().on('disconnect', function() {
|
||
// Worker has disconnected
|
||
};</code></pre>
|
||
<h3>Event: 'exit'<span><a class="mark" href="#all_event_exit_4" id="all_event_exit_4">#</a></span></h3>
|
||
<div class="signature"><ul>
|
||
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
|
||
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>'SIGHUP'</code>) that caused
|
||
the process to be killed.</li>
|
||
</div></ul>
|
||
<p>Emitted by the individual worker instance, when the underlying child process
|
||
is terminated. See <a href="child_process.html#child_process_event_exit">child_process event: 'exit'</a>.
|
||
|
||
</p>
|
||
<pre><code>var worker = cluster.fork();
|
||
worker.on('exit', function(code, signal) {
|
||
if( signal ) {
|
||
console.log("worker was killed by signal: "+signal);
|
||
} else if( code !== 0 ) {
|
||
console.log("worker exited with error code: "+code);
|
||
} else {
|
||
console.log("worker success!");
|
||
}
|
||
};</code></pre>
|
||
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div id="footer">
|
||
<ul class="clearfix">
|
||
<li><a href="/">Node.js</a></li>
|
||
<li><a href="/download/">Download</a></li>
|
||
<li><a href="/about/">About</a></li>
|
||
<li><a href="http://search.npmjs.org/">npm Registry</a></li>
|
||
<li><a href="http://nodejs.org/api/">Docs</a></li>
|
||
<li><a href="http://blog.nodejs.org">Blog</a></li>
|
||
<li><a href="/community/">Community</a></li>
|
||
<li><a href="/logos/">Logos</a></li>
|
||
<li><a href="http://jobs.nodejs.org/">Jobs</a></li>
|
||
<li><a href="http://twitter.com/nodejs" class="twitter">@nodejs</a></li>
|
||
</ul>
|
||
|
||
<p>Copyright <a href="http://joyent.com/">Joyent, Inc</a>, Node.js is a <a href="/trademark-policy.pdf">trademark</a> of Joyent, Inc. View <a href="https://raw.github.com/joyent/node/v0.8.14/LICENSE">license</a>.</p>
|
||
</div>
|
||
|
||
<script src="../sh_main.js"></script>
|
||
<script src="../sh_javascript.min.js"></script>
|
||
<script>highlight(undefined, undefined, 'pre');</script>
|
||
<script>
|
||
window._gaq = [['_setAccount', 'UA-10874194-2'], ['_trackPageview']];
|
||
(function(d, t) {
|
||
var g = d.createElement(t),
|
||
s = d.getElementsByTagName(t)[0];
|
||
g.src = '//www.google-analytics.com/ga.js';
|
||
s.parentNode.insertBefore(g, s);
|
||
}(document, 'script'));
|
||
</script>
|
||
</body>
|
||
</html>
|
||
|