Server IP : 127.0.0.2 / Your IP : 18.216.82.12 Web Server : Apache/2.4.18 (Ubuntu) System : User : www-data ( ) PHP Version : 7.0.33-0ubuntu0.16.04.16 Disable Function : disk_free_space,disk_total_space,diskfreespace,dl,exec,fpaththru,getmyuid,getmypid,highlight_file,ignore_user_abord,leak,listen,link,opcache_get_configuration,opcache_get_status,passthru,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,php_uname,phpinfo,posix_ctermid,posix_getcwd,posix_getegid,posix_geteuid,posix_getgid,posix_getgrgid,posix_getgrnam,posix_getgroups,posix_getlogin,posix_getpgid,posix_getpgrp,posix_getpid,posix,_getppid,posix_getpwnam,posix_getpwuid,posix_getrlimit,posix_getsid,posix_getuid,posix_isatty,posix_kill,posix_mkfifo,posix_setegid,posix_seteuid,posix_setgid,posix_setpgid,posix_setsid,posix_setuid,posix_times,posix_ttyname,posix_uname,pclose,popen,proc_open,proc_close,proc_get_status,proc_nice,proc_terminate,shell_exec,source,show_source,system,virtual MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /usr/share/doc/nodejs/api/ |
Upload File : |
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>About this Documentation Node.js v4.2.6 Manual & Documentation</title> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/sh.css"> <link rel="canonical" href="all.html"> </head> <body class="alt apidoc" id="api-section-all"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="/" title="Go back to the home page"> Node.js (1) </a> </div> <ul> <li><a class="nav-documentation" href="documentation.html">About these Docs</a></li> <li><a class="nav-synopsis" href="synopsis.html">Synopsis</a></li> <li><a class="nav-assert" href="assert.html">Assertion Testing</a></li> <li><a class="nav-buffer" href="buffer.html">Buffer</a></li> <li><a class="nav-addons" href="addons.html">C/C++ Addons</a></li> <li><a class="nav-child_process" href="child_process.html">Child Processes</a></li> <li><a class="nav-cluster" href="cluster.html">Cluster</a></li> <li><a class="nav-console" href="console.html">Console</a></li> <li><a class="nav-crypto" href="crypto.html">Crypto</a></li> <li><a class="nav-debugger" href="debugger.html">Debugger</a></li> <li><a class="nav-dns" href="dns.html">DNS</a></li> <li><a class="nav-domain" href="domain.html">Domain</a></li> <li><a class="nav-errors" href="errors.html">Errors</a></li> <li><a class="nav-events" href="events.html">Events</a></li> <li><a class="nav-fs" href="fs.html">File System</a></li> <li><a class="nav-globals" href="globals.html">Globals</a></li> <li><a class="nav-http" href="http.html">HTTP</a></li> <li><a class="nav-https" href="https.html">HTTPS</a></li> <li><a class="nav-modules" href="modules.html">Modules</a></li> <li><a class="nav-net" href="net.html">Net</a></li> <li><a class="nav-os" href="os.html">OS</a></li> <li><a class="nav-path" href="path.html">Path</a></li> <li><a class="nav-process" href="process.html">Process</a></li> <li><a class="nav-punycode" href="punycode.html">Punycode</a></li> <li><a class="nav-querystring" href="querystring.html">Query Strings</a></li> <li><a class="nav-readline" href="readline.html">Readline</a></li> <li><a class="nav-repl" href="repl.html">REPL</a></li> <li><a class="nav-stream" href="stream.html">Stream</a></li> <li><a class="nav-string_decoder" href="string_decoder.html">String Decoder</a></li> <li><a class="nav-timers" href="timers.html">Timers</a></li> <li><a class="nav-tls" href="tls.html">TLS/SSL</a></li> <li><a class="nav-tty" href="tty.html">TTY</a></li> <li><a class="nav-dgram" href="dgram.html">UDP/Datagram</a></li> <li><a class="nav-url" href="url.html">URL</a></li> <li><a class="nav-util" href="util.html">Utilities</a></li> <li><a class="nav-v8" href="v8.html">V8</a></li> <li><a class="nav-vm" href="vm.html">VM</a></li> <li><a class="nav-zlib" href="zlib.html">ZLIB</a></li> </ul> </div> <div id="column1" data-id="all" class="interior"> <header> <h1>Node.js v4.2.6 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_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> <li><a href="#all_atexit_hooks">AtExit hooks</a><ul> <li><a href="#all_void_atexit_callback_args">void AtExit(callback, args)</a></li> </ul> </li> </ul> </li> </ul> </li> <li><a href="#all_assert">Assert</a><ul> <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_deepequal_actual_expected_message">assert.deepEqual(actual, expected[, message])</a></li> <li><a href="#all_assert_deepstrictequal_actual_expected_message">assert.deepStrictEqual(actual, expected[, message])</a></li> <li><a href="#all_assert_doesnotthrow_block_error_message">assert.doesNotThrow(block[, error][, message])</a></li> <li><a href="#all_assert_equal_actual_expected_message">assert.equal(actual, expected[, message])</a></li> <li><a href="#all_assert_fail_actual_expected_message_operator">assert.fail(actual, expected, message, operator)</a></li> <li><a href="#all_assert_iferror_value">assert.ifError(value)</a></li> <li><a href="#all_assert_notdeepequal_actual_expected_message">assert.notDeepEqual(actual, expected[, message])</a></li> <li><a href="#all_assert_notdeepstrictequal_actual_expected_message">assert.notDeepStrictEqual(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_notstrictequal_actual_expected_message">assert.notStrictEqual(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_throws_block_error_message">assert.throws(block[, error][, message])</a></li> </ul> </li> <li><a href="#all_buffer">Buffer</a><ul> <li><a href="#all_class_buffer">Class: Buffer</a><ul> <li><a href="#all_new_buffer_array">new Buffer(array)</a></li> <li><a href="#all_new_buffer_buffer">new Buffer(buffer)</a></li> <li><a href="#all_new_buffer_size">new Buffer(size)</a></li> <li><a href="#all_new_buffer_str_encoding">new Buffer(str[, encoding])</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_compare_buf1_buf2">Class Method: Buffer.compare(buf1, buf2)</a></li> <li><a href="#all_class_method_buffer_concat_list_totallength">Class Method: Buffer.concat(list[, totalLength])</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_isencoding_encoding">Class Method: Buffer.isEncoding(encoding)</a></li> <li><a href="#all_buffer_entries">buffer.entries()</a></li> <li><a href="#all_buffer_keys">buffer.keys()</a></li> <li><a href="#all_buffer_values">buffer.values()</a></li> <li><a href="#all_buf_index">buf[index]</a></li> <li><a href="#all_buf_compare_otherbuffer">buf.compare(otherBuffer)</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_equals_otherbuffer">buf.equals(otherBuffer)</a></li> <li><a href="#all_buf_fill_value_offset_end">buf.fill(value[, offset][, end])</a></li> <li><a href="#all_buf_indexof_value_byteoffset">buf.indexOf(value[, byteOffset])</a></li> <li><a href="#all_buf_length">buf.length</a></li> <li><a href="#all_buf_readdoublebe_offset_noassert">buf.readDoubleBE(offset[, noAssert])</a></li> <li><a href="#all_buf_readdoublele_offset_noassert">buf.readDoubleLE(offset[, noAssert])</a></li> <li><a href="#all_buf_readfloatbe_offset_noassert">buf.readFloatBE(offset[, noAssert])</a></li> <li><a href="#all_buf_readfloatle_offset_noassert">buf.readFloatLE(offset[, noAssert])</a></li> <li><a href="#all_buf_readint8_offset_noassert">buf.readInt8(offset[, noAssert])</a></li> <li><a href="#all_buf_readint16be_offset_noassert">buf.readInt16BE(offset[, noAssert])</a></li> <li><a href="#all_buf_readint16le_offset_noassert">buf.readInt16LE(offset[, noAssert])</a></li> <li><a href="#all_buf_readint32be_offset_noassert">buf.readInt32BE(offset[, noAssert])</a></li> <li><a href="#all_buf_readint32le_offset_noassert">buf.readInt32LE(offset[, noAssert])</a></li> <li><a href="#all_buf_readintbe_offset_bytelength_noassert">buf.readIntBE(offset, byteLength[, noAssert])</a></li> <li><a href="#all_buf_readintle_offset_bytelength_noassert">buf.readIntLE(offset, byteLength[, noAssert])</a></li> <li><a href="#all_buf_readuint8_offset_noassert">buf.readUInt8(offset[, noAssert])</a></li> <li><a href="#all_buf_readuint16be_offset_noassert">buf.readUInt16BE(offset[, noAssert])</a></li> <li><a href="#all_buf_readuint16le_offset_noassert">buf.readUInt16LE(offset[, noAssert])</a></li> <li><a href="#all_buf_readuint32be_offset_noassert">buf.readUInt32BE(offset[, noAssert])</a></li> <li><a href="#all_buf_readuint32le_offset_noassert">buf.readUInt32LE(offset[, noAssert])</a></li> <li><a href="#all_buf_readuintbe_offset_bytelength_noassert">buf.readUIntBE(offset, byteLength[, noAssert])</a></li> <li><a href="#all_buf_readuintle_offset_bytelength_noassert">buf.readUIntLE(offset, byteLength[, noAssert])</a></li> <li><a href="#all_buf_slice_start_end">buf.slice([start[, end]])</a></li> <li><a href="#all_buf_tostring_encoding_start_end">buf.toString([encoding][, start][, end])</a></li> <li><a href="#all_buf_tojson">buf.toJSON()</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_writedoublebe_value_offset_noassert">buf.writeDoubleBE(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_writefloatbe_value_offset_noassert">buf.writeFloatBE(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_writeint8_value_offset_noassert">buf.writeInt8(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_writeint16le_value_offset_noassert">buf.writeInt16LE(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_writeint32le_value_offset_noassert">buf.writeInt32LE(value, offset[, noAssert])</a></li> <li><a href="#all_buf_writeintbe_value_offset_bytelength_noassert">buf.writeIntBE(value, offset, byteLength[, noAssert])</a></li> <li><a href="#all_buf_writeintle_value_offset_bytelength_noassert">buf.writeIntLE(value, offset, byteLength[, noAssert])</a></li> <li><a href="#all_buf_writeuint8_value_offset_noassert">buf.writeUInt8(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_writeuint16le_value_offset_noassert">buf.writeUInt16LE(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_writeuint32le_value_offset_noassert">buf.writeUInt32LE(value, offset[, noAssert])</a></li> <li><a href="#all_buf_writeuintbe_value_offset_bytelength_noassert">buf.writeUIntBE(value, offset, byteLength[, noAssert])</a></li> <li><a href="#all_buf_writeuintle_value_offset_bytelength_noassert">buf.writeUIntLE(value, offset, byteLength[, noAssert])</a></li> </ul> </li> <li><a href="#all_buffer_inspect_max_bytes">buffer.INSPECT_MAX_BYTES</a></li> <li><a href="#all_es6_iteration">ES6 iteration</a></li> <li><a href="#all_class_slowbuffer">Class: SlowBuffer</a></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_close">Event: 'close'</a></li> <li><a href="#all_event_disconnect">Event: 'disconnect'</a></li> <li><a href="#all_event_error">Event: 'error'</a></li> <li><a href="#all_event_exit">Event: 'exit'</a></li> <li><a href="#all_event_message">Event: 'message'</a></li> <li><a href="#all_child_connected">child.connected</a></li> <li><a href="#all_child_disconnect">child.disconnect()</a></li> <li><a href="#all_child_kill_signal">child.kill([signal])</a></li> <li><a href="#all_child_pid">child.pid</a></li> <li><a href="#all_child_send_message_sendhandle_callback">child.send(message[, sendHandle][, callback])</a><ul> <li><a href="#all_example_sending_server_object">Example: sending server object</a></li> <li><a href="#all_example_sending_socket_object">Example: sending socket object</a></li> </ul> </li> <li><a href="#all_child_stderr">child.stderr</a></li> <li><a href="#all_child_stdin">child.stdin</a></li> <li><a href="#all_child_stdio">child.stdio</a></li> <li><a href="#all_child_stdout">child.stdout</a></li> </ul> </li> <li><a href="#all_asynchronous_process_creation">Asynchronous Process Creation</a><ul> <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> <li><a href="#all_child_process_spawn_command_args_options">child_process.spawn(command[, args][, options])</a><ul> <li><a href="#all_options_detached">options.detached</a></li> <li><a href="#all_options_stdio">options.stdio</a></li> </ul> </li> </ul> </li> <li><a href="#all_synchronous_process_creation">Synchronous Process Creation</a><ul> <li><a href="#all_child_process_execfilesync_file_args_options">child_process.execFileSync(file[, args][, options])</a></li> <li><a href="#all_child_process_execsync_command_options">child_process.execSync(command[, options])</a></li> <li><a href="#all_child_process_spawnsync_command_args_options">child_process.spawnSync(command[, args][, options])</a></li> </ul> </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_class_worker">Class: Worker</a><ul> <li><a href="#all_event_disconnect_1">Event: 'disconnect'</a></li> <li><a href="#all_event_error_1">Event: 'error'</a></li> <li><a href="#all_event_exit_1">Event: 'exit'</a></li> <li><a href="#all_event_listening">Event: 'listening'</a></li> <li><a href="#all_event_message_1">Event: 'message'</a></li> <li><a href="#all_event_online">Event: 'online'</a></li> <li><a href="#all_worker_disconnect">worker.disconnect()</a></li> <li><a href="#all_worker_id">worker.id</a></li> <li><a href="#all_worker_isconnected">worker.isConnected()</a></li> <li><a href="#all_worker_isdead">worker.isDead()</a></li> <li><a href="#all_worker_kill_signal_sigterm">worker.kill([signal='SIGTERM'])</a></li> <li><a href="#all_worker_process">worker.process</a></li> <li><a href="#all_worker_send_message_sendhandle_callback">worker.send(message[, sendHandle][, callback])</a></li> <li><a href="#all_worker_suicide">worker.suicide</a></li> </ul> </li> <li><a href="#all_event_disconnect_2">Event: 'disconnect'</a></li> <li><a href="#all_event_exit_2">Event: 'exit'</a></li> <li><a href="#all_event_fork">Event: 'fork'</a></li> <li><a href="#all_event_listening_1">Event: 'listening'</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_setup">Event: 'setup'</a></li> <li><a href="#all_cluster_disconnect_callback">cluster.disconnect([callback])</a></li> <li><a href="#all_cluster_fork_env">cluster.fork([env])</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_cluster_schedulingpolicy">cluster.schedulingPolicy</a></li> <li><a href="#all_cluster_settings">cluster.settings</a></li> <li><a href="#all_cluster_setupmaster_settings">cluster.setupMaster([settings])</a></li> <li><a href="#all_cluster_worker">cluster.worker</a></li> <li><a href="#all_cluster_workers">cluster.workers</a></li> </ul> </li> <li><a href="#all_console">Console</a><ul> <li><a href="#all_asynchronous_vs_synchronous_consoles">Asynchronous vs Synchronous Consoles</a></li> <li><a href="#all_class_console">Class: Console</a><ul> <li><a href="#all_new_console_stdout_stderr">new Console(stdout[, stderr])</a></li> <li><a href="#all_console_assert_value_message">console.assert(value[, message][, ...])</a></li> <li><a href="#all_console_dir_obj_options">console.dir(obj[, options])</a></li> <li><a href="#all_console_error_data">console.error([data][, ...])</a></li> <li><a href="#all_console_info_data">console.info([data][, ...])</a></li> <li><a href="#all_console_log_data">console.log([data][, ...])</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_message">console.trace(message[, ...])</a></li> <li><a href="#all_console_warn_data">console.warn([data][, ...])</a></li> </ul> </li> </ul> </li> <li><a href="#all_crypto">Crypto</a><ul> <li><a href="#all_class_certificate">Class: Certificate</a><ul> <li><a href="#all_certificate_exportchallenge_spkac">Certificate.exportChallenge(spkac)</a></li> <li><a href="#all_certificate_exportpublickey_spkac">Certificate.exportPublicKey(spkac)</a></li> <li><a href="#all_certificate_verifyspkac_spkac">Certificate.verifySpkac(spkac)</a></li> </ul> </li> <li><a href="#all_class_cipher">Class: Cipher</a><ul> <li><a href="#all_cipher_final_output_encoding">cipher.final([output_encoding])</a></li> <li><a href="#all_cipher_getauthtag">cipher.getAuthTag()</a></li> <li><a href="#all_cipher_setaad_buffer">cipher.setAAD(buffer)</a></li> <li><a href="#all_cipher_setautopadding_auto_padding_true">cipher.setAutoPadding(auto_padding=true)</a></li> <li><a href="#all_cipher_update_data_input_encoding_output_encoding">cipher.update(data[, input_encoding][, output_encoding])</a></li> </ul> </li> <li><a href="#all_class_decipher">Class: Decipher</a><ul> <li><a href="#all_decipher_final_output_encoding">decipher.final([output_encoding])</a></li> <li><a href="#all_decipher_setaad_buffer">decipher.setAAD(buffer)</a></li> <li><a href="#all_decipher_setauthtag_buffer">decipher.setAuthTag(buffer)</a></li> <li><a href="#all_decipher_setautopadding_auto_padding_true">decipher.setAutoPadding(auto_padding=true)</a></li> <li><a href="#all_decipher_update_data_input_encoding_output_encoding">decipher.update(data[, input_encoding][, output_encoding])</a></li> </ul> </li> <li><a href="#all_class_diffiehellman">Class: DiffieHellman</a><ul> <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_generatekeys_encoding">diffieHellman.generateKeys([encoding])</a></li> <li><a href="#all_diffiehellman_getgenerator_encoding">diffieHellman.getGenerator([encoding])</a></li> <li><a href="#all_diffiehellman_getprime_encoding">diffieHellman.getPrime([encoding])</a></li> <li><a href="#all_diffiehellman_getprivatekey_encoding">diffieHellman.getPrivateKey([encoding])</a></li> <li><a href="#all_diffiehellman_getpublickey_encoding">diffieHellman.getPublicKey([encoding])</a></li> <li><a href="#all_diffiehellman_setprivatekey_private_key_encoding">diffieHellman.setPrivateKey(private_key[, encoding])</a></li> <li><a href="#all_diffiehellman_setpublickey_public_key_encoding">diffieHellman.setPublicKey(public_key[, encoding])</a></li> <li><a href="#all_diffiehellman_verifyerror">diffieHellman.verifyError</a></li> </ul> </li> <li><a href="#all_class_ecdh">Class: ECDH</a><ul> <li><a href="#all_ecdh_computesecret_other_public_key_input_encoding_output_encoding">ECDH.computeSecret(other_public_key[, input_encoding][, output_encoding])</a></li> <li><a href="#all_ecdh_generatekeys_encoding_format">ECDH.generateKeys([encoding[, format]])</a></li> <li><a href="#all_ecdh_getprivatekey_encoding">ECDH.getPrivateKey([encoding])</a></li> <li><a href="#all_ecdh_getpublickey_encoding_format">ECDH.getPublicKey([encoding[, format]])</a></li> <li><a href="#all_ecdh_setprivatekey_private_key_encoding">ECDH.setPrivateKey(private_key[, encoding])</a></li> <li><a href="#all_ecdh_setpublickey_public_key_encoding">ECDH.setPublicKey(public_key[, encoding])</a></li> </ul> </li> <li><a href="#all_class_hash">Class: Hash</a><ul> <li><a href="#all_hash_digest_encoding">hash.digest([encoding])</a></li> <li><a href="#all_hash_update_data_input_encoding">hash.update(data[, input_encoding])</a></li> </ul> </li> <li><a href="#all_class_hmac">Class: Hmac</a><ul> <li><a href="#all_hmac_digest_encoding">hmac.digest([encoding])</a></li> <li><a href="#all_hmac_update_data">hmac.update(data)</a></li> </ul> </li> <li><a href="#all_class_sign">Class: Sign</a><ul> <li><a href="#all_sign_sign_private_key_output_format">sign.sign(private_key[, output_format])</a></li> <li><a href="#all_sign_update_data">sign.update(data)</a></li> </ul> </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_default_encoding">crypto.DEFAULT_ENCODING</a></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_crypto_createcredentials_details">crypto.createCredentials(details)</a></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_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding">crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])</a></li> <li><a href="#all_crypto_creatediffiehellman_prime_length_generator">crypto.createDiffieHellman(prime_length[, generator])</a></li> <li><a href="#all_crypto_createecdh_curve_name">crypto.createECDH(curve_name)</a></li> <li><a href="#all_crypto_createhash_algorithm">crypto.createHash(algorithm)</a></li> <li><a href="#all_crypto_createhmac_algorithm_key">crypto.createHmac(algorithm, key)</a></li> <li><a href="#all_crypto_createsign_algorithm">crypto.createSign(algorithm)</a></li> <li><a href="#all_crypto_createverify_algorithm">crypto.createVerify(algorithm)</a></li> <li><a href="#all_crypto_getciphers">crypto.getCiphers()</a></li> <li><a href="#all_crypto_getcurves">crypto.getCurves()</a></li> <li><a href="#all_crypto_getdiffiehellman_group_name">crypto.getDiffieHellman(group_name)</a></li> <li><a href="#all_crypto_gethashes">crypto.getHashes()</a></li> <li><a href="#all_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback">crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)</a></li> <li><a href="#all_crypto_pbkdf2sync_password_salt_iterations_keylen_digest">crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])</a></li> <li><a href="#all_crypto_privatedecrypt_private_key_buffer">crypto.privateDecrypt(private_key, buffer)</a></li> <li><a href="#all_crypto_privateencrypt_private_key_buffer">crypto.privateEncrypt(private_key, buffer)</a></li> <li><a href="#all_crypto_publicdecrypt_public_key_buffer">crypto.publicDecrypt(public_key, buffer)</a></li> <li><a href="#all_crypto_publicencrypt_public_key_buffer">crypto.publicEncrypt(public_key, buffer)</a></li> <li><a href="#all_crypto_randombytes_size_callback">crypto.randomBytes(size[, callback])</a></li> <li><a href="#all_crypto_setengine_engine_flags">crypto.setEngine(engine[, flags])</a></li> <li><a href="#all_recent_api_changes">Recent API Changes</a></li> <li><a href="#all_caveats">Caveats</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_udp_datagram_sockets">UDP / Datagram Sockets</a><ul> <li><a href="#all_class_dgram_socket">Class: dgram.Socket</a><ul> <li><a href="#all_event_close_1">Event: 'close'</a></li> <li><a href="#all_event_error_2">Event: 'error'</a></li> <li><a href="#all_event_listening_2">Event: 'listening'</a></li> <li><a href="#all_event_message_3">Event: 'message'</a></li> <li><a href="#all_socket_addmembership_multicastaddress_multicastinterface">socket.addMembership(multicastAddress[, multicastInterface])</a></li> <li><a href="#all_socket_address">socket.address()</a></li> <li><a href="#all_socket_bind_port_address_callback">[socket.bind([port][, address][, callback])]</a></li> <li><a href="#all_socket_bind_options_callback">socket.bind(options[, callback])</a></li> <li><a href="#all_socket_close_callback">socket.close([callback])</a></li> <li><a href="#all_socket_dropmembership_multicastaddress_multicastinterface">socket.dropMembership(multicastAddress[, multicastInterface])</a></li> <li><a href="#all_socket_send_buf_offset_length_port_address_callback">socket.send(buf, offset, length, port, address[, callback])</a></li> <li><a href="#all_socket_setbroadcast_flag">socket.setBroadcast(flag)</a></li> <li><a href="#all_socket_setmulticastloopback_flag">socket.setMulticastLoopback(flag)</a></li> <li><a href="#all_socket_setmulticastttl_ttl">socket.setMulticastTTL(ttl)</a></li> <li><a href="#all_socket_setttl_ttl">socket.setTTL(ttl)</a></li> <li><a href="#all_socket_ref">socket.ref()</a></li> <li><a href="#all_socket_unref">socket.unref()</a></li> <li><a href="#all_change_to_asynchronous_socket_bind_behavior">Change to asynchronous <code>socket.bind()</code> behavior</a></li> </ul> </li> <li><a href="#all_dgram_module_functions"><code>dgram</code> module functions</a><ul> <li><a href="#all_dgram_createsocket_options_callback">dgram.createSocket(options[, callback])</a></li> </ul> </li> <li><a href="#all_dgram_createsocket_type_callback">dgram.createSocket(type[, callback])</a></li> </ul> </li> <li><a href="#all_dns">DNS</a><ul> <li><a href="#all_dns_getservers">dns.getServers()</a></li> <li><a href="#all_dns_lookup_hostname_options_callback">dns.lookup(hostname[, options], callback)</a><ul> <li><a href="#all_supported_getaddrinfo_flags">Supported getaddrinfo flags</a></li> </ul> </li> <li><a href="#all_dns_lookupservice_address_port_callback">dns.lookupService(address, port, callback)</a></li> <li><a href="#all_dns_resolve_hostname_rrtype_callback">dns.resolve(hostname[, rrtype], callback)</a></li> <li><a href="#all_dns_resolve4_hostname_callback">dns.resolve4(hostname, callback)</a></li> <li><a href="#all_dns_resolve6_hostname_callback">dns.resolve6(hostname, callback)</a></li> <li><a href="#all_dns_resolvecname_hostname_callback">dns.resolveCname(hostname, callback)</a></li> <li><a href="#all_dns_resolvemx_hostname_callback">dns.resolveMx(hostname, callback)</a></li> <li><a href="#all_dns_resolvens_hostname_callback">dns.resolveNs(hostname, callback)</a></li> <li><a href="#all_dns_resolvesoa_hostname_callback">dns.resolveSoa(hostname, callback)</a></li> <li><a href="#all_dns_resolvesrv_hostname_callback">dns.resolveSrv(hostname, callback)</a></li> <li><a href="#all_dns_resolvetxt_hostname_callback">dns.resolveTxt(hostname, callback)</a></li> <li><a href="#all_dns_reverse_ip_callback">dns.reverse(ip, callback)</a></li> <li><a href="#all_dns_setservers_servers">dns.setServers(servers)</a></li> <li><a href="#all_error_codes">Error codes</a></li> <li><a href="#all_implementation_considerations">Implementation considerations</a><ul> <li><a href="#all_dns_lookup"><code>dns.lookup()</code></a></li> <li><a href="#all_dns_resolve_dns_resolve_and_dns_reverse"><code>dns.resolve()</code>, <code>dns.resolve*()</code> and <code>dns.reverse()</code></a></li> </ul> </li> </ul> </li> <li><a href="#all_domain">Domain</a><ul> <li><a href="#all_warning_don_t_ignore_errors">Warning: Don't Ignore Errors!</a></li> <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_arg">domain.run(fn[, arg][, ...])</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_enter">domain.enter()</a></li> <li><a href="#all_domain_exit">domain.exit()</a></li> <li><a href="#all_domain_dispose">domain.dispose()</a></li> </ul> </li> </ul> </li> <li><a href="#all_errors">Errors</a><ul> <li><a href="#all_error_propagation_and_interception">Error Propagation and Interception</a><ul> <li><a href="#all_node_js_style_callbacks">Node.js style callbacks</a></li> </ul> </li> <li><a href="#all_class_error">Class: Error</a><ul> <li><a href="#all_new_error_message">new Error(message)</a></li> <li><a href="#all_error_capturestacktrace_targetobject_constructoropt">Error.captureStackTrace(targetObject[, constructorOpt])</a></li> <li><a href="#all_error_stacktracelimit">Error.stackTraceLimit</a><ul> <li><a href="#all_error_message">error.message</a></li> <li><a href="#all_error_stack">error.stack</a></li> </ul> </li> </ul> </li> <li><a href="#all_class_rangeerror">Class: RangeError</a></li> <li><a href="#all_class_referenceerror">Class: ReferenceError</a></li> <li><a href="#all_class_syntaxerror">Class: SyntaxError</a></li> <li><a href="#all_class_typeerror">Class: TypeError</a></li> <li><a href="#all_exceptions_vs_errors">Exceptions vs. Errors</a></li> <li><a href="#all_system_errors">System Errors</a><ul> <li><a href="#all_class_system_error">Class: System Error</a><ul> <li><a href="#all_error_code">error.code</a></li> <li><a href="#all_error_errno">error.errno</a></li> <li><a href="#all_error_syscall">error.syscall</a></li> </ul> </li> <li><a href="#all_common_system_errors">Common System Errors</a></li> </ul> </li> </ul> </li> <li><a href="#all_events">Events</a><ul> <li><a href="#all_passing_arguments_and_this_to_listeners">Passing arguments and <code>this</code> to listeners</a></li> <li><a href="#all_asynchronous_vs_synchronous">Asynchronous vs. Synchronous</a></li> <li><a href="#all_handling_events_only_once">Handling events only once</a></li> <li><a href="#all_error_events">Error events</a></li> <li><a href="#all_class_eventemitter">Class: EventEmitter</a><ul> <li><a href="#all_event_newlistener">Event: 'newListener'</a></li> <li><a href="#all_event_removelistener">Event: 'removeListener'</a></li> <li><a href="#all_eventemitter_listenercount_emitter_event">EventEmitter.listenerCount(emitter, event)</a></li> <li><a href="#all_eventemitter_defaultmaxlisteners">EventEmitter.defaultMaxListeners</a></li> <li><a href="#all_emitter_addlistener_event_listener">emitter.addListener(event, listener)</a></li> <li><a href="#all_emitter_emit_event_arg1_arg2">emitter.emit(event[, arg1][, arg2][, ...])</a></li> <li><a href="#all_emitter_getmaxlisteners">emitter.getMaxListeners()</a></li> <li><a href="#all_emitter_listenercount_event">emitter.listenerCount(event)</a></li> <li><a href="#all_emitter_listeners_event">emitter.listeners(event)</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_removealllisteners_event">emitter.removeAllListeners([event])</a></li> <li><a href="#all_emitter_removelistener_event_listener">emitter.removeListener(event, listener)</a></li> <li><a href="#all_emitter_setmaxlisteners_n">emitter.setMaxListeners(n)</a></li> </ul> </li> </ul> </li> <li><a href="#all_file_system">File System</a><ul> <li><a href="#all_class_fs_fswatcher">Class: fs.FSWatcher</a><ul> <li><a href="#all_event_change">Event: 'change'</a></li> <li><a href="#all_event_error_3">Event: 'error'</a></li> <li><a href="#all_watcher_close">watcher.close()</a></li> </ul> </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_class_fs_stats">Class: fs.Stats</a><ul> <li><a href="#all_stat_time_values">Stat Time Values</a></li> </ul> </li> <li><a href="#all_class_fs_writestream">Class: fs.WriteStream</a><ul> <li><a href="#all_event_open_1">Event: 'open'</a></li> <li><a href="#all_writestream_byteswritten">writeStream.bytesWritten</a></li> </ul> </li> <li><a href="#all_fs_access_path_mode_callback">fs.access(path[, mode], callback)</a></li> <li><a href="#all_fs_accesssync_path_mode">fs.accessSync(path[, mode])</a></li> <li><a href="#all_fs_appendfile_file_data_options_callback">fs.appendFile(file, data[, options], callback)</a></li> <li><a href="#all_fs_appendfilesync_file_data_options">fs.appendFileSync(file, data[, options])</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_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_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_createreadstream_path_options">fs.createReadStream(path[, options])</a></li> <li><a href="#all_fs_createwritestream_path_options">fs.createWriteStream(path[, options])</a></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_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_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_fstat_fd_callback">fs.fstat(fd, callback)</a></li> <li><a href="#all_fs_fstatsync_fd">fs.fstatSync(fd)</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_ftruncate_fd_len_callback">fs.ftruncate(fd, len, callback)</a></li> <li><a href="#all_fs_ftruncatesync_fd_len">fs.ftruncateSync(fd, len)</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_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_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_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_lstat_path_callback">fs.lstat(path, callback)</a></li> <li><a href="#all_fs_lstatsync_path">fs.lstatSync(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_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_read_fd_buffer_offset_length_position_callback">fs.read(fd, buffer, offset, length, position, callback)</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_readfile_file_options_callback">fs.readFile(file[, options], callback)</a></li> <li><a href="#all_fs_readfilesync_file_options">fs.readFileSync(file[, options])</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_readsync_fd_buffer_offset_length_position">fs.readSync(fd, buffer, offset, length, position)</a></li> <li><a href="#all_fs_realpathsync_path_cache">fs.realpathSync(path[, cache])</a></li> <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_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_stat_path_callback">fs.stat(path, callback)</a></li> <li><a href="#all_fs_statsync_path">fs.statSync(path)</a></li> <li><a href="#all_fs_symlink_target_path_type_callback">fs.symlink(target, path[, type], callback)</a></li> <li><a href="#all_fs_symlinksync_target_path_type">fs.symlinkSync(target, path[, type])</a></li> <li><a href="#all_fs_truncate_path_len_callback">fs.truncate(path, len, callback)</a></li> <li><a href="#all_fs_truncatesync_path_len">fs.truncateSync(path, len)</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_unwatchfile_filename_listener">fs.unwatchFile(filename[, listener])</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_watch_filename_options_listener">fs.watch(filename[, options][, listener])</a><ul> <li><a href="#all_caveats_1">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_watchfile_filename_options_listener">fs.watchFile(filename[, options], listener)</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_write_fd_data_position_encoding_callback">fs.write(fd, data[, position[, encoding]], callback)</a></li> <li><a href="#all_fs_writefile_file_data_options_callback">fs.writeFile(file, data[, options], callback)</a></li> <li><a href="#all_fs_writefilesync_file_data_options">fs.writeFileSync(file, data[, options])</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_writesync_fd_data_position_encoding">fs.writeSync(fd, data[, position[, encoding]])</a></li> </ul> </li> <li><a href="#all_global_objects">Global Objects</a><ul> <li><a href="#all_class_buffer_1">Class: Buffer</a></li> <li><a href="#all_dirname">__dirname</a></li> <li><a href="#all_filename">__filename</a></li> <li><a href="#all_clearinterval_t">clearInterval(t)</a></li> <li><a href="#all_cleartimeout_t">clearTimeout(t)</a></li> <li><a href="#all_console_1">console</a></li> <li><a href="#all_exports">exports</a></li> <li><a href="#all_global">global</a></li> <li><a href="#all_module">module</a></li> <li><a href="#all_process">process</a></li> <li><a href="#all_require">require()</a><ul> <li><a href="#all_require_cache">require.cache</a></li> <li><a href="#all_require_extensions">require.extensions</a></li> <li><a href="#all_require_resolve">require.resolve()</a></li> </ul> </li> <li><a href="#all_setinterval_cb_ms">setInterval(cb, ms)</a></li> <li><a href="#all_settimeout_cb_ms">setTimeout(cb, ms)</a></li> </ul> </li> <li><a href="#all_http">HTTP</a><ul> <li><a href="#all_class_http_agent">Class: http.Agent</a><ul> <li><a href="#all_new_agent_options">new Agent([options])</a></li> <li><a href="#all_agent_destroy">agent.destroy()</a></li> <li><a href="#all_agent_freesockets">agent.freeSockets</a></li> <li><a href="#all_agent_getname_options">agent.getName(options)</a></li> <li><a href="#all_agent_maxfreesockets">agent.maxFreeSockets</a></li> <li><a href="#all_agent_maxsockets">agent.maxSockets</a></li> <li><a href="#all_agent_requests">agent.requests</a></li> <li><a href="#all_agent_sockets">agent.sockets</a></li> </ul> </li> <li><a href="#all_class_http_clientrequest">Class: http.ClientRequest</a><ul> <li><a href="#all_event_abort">Event: 'abort'</a></li> <li><a href="#all_event_connect">Event: 'connect'</a></li> <li><a href="#all_event_continue">Event: 'continue'</a></li> <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_upgrade">Event: 'upgrade'</a></li> <li><a href="#all_request_abort">request.abort()</a></li> <li><a href="#all_request_end_data_encoding_callback">request.end([data][, encoding][, callback])</a></li> <li><a href="#all_request_flushheaders">request.flushHeaders()</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> <li><a href="#all_request_settimeout_timeout_callback">request.setTimeout(timeout[, callback])</a></li> <li><a href="#all_request_write_chunk_encoding_callback">request.write(chunk[, encoding][, callback])</a></li> </ul> </li> <li><a href="#all_class_http_server">Class: http.Server</a><ul> <li><a href="#all_event_checkcontinue">Event: 'checkContinue'</a></li> <li><a href="#all_event_clienterror">Event: 'clientError'</a></li> <li><a href="#all_event_close_2">Event: 'close'</a></li> <li><a href="#all_event_connect_1">Event: 'connect'</a></li> <li><a href="#all_event_connection">Event: 'connection'</a></li> <li><a href="#all_event_request">Event: 'request'</a></li> <li><a href="#all_event_upgrade_1">Event: 'upgrade'</a></li> <li><a href="#all_server_close_callback">server.close([callback])</a></li> <li><a href="#all_server_listen_handle_callback">server.listen(handle[, callback])</a></li> <li><a href="#all_server_listen_path_callback">server.listen(path[, callback])</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_maxheaderscount">server.maxHeadersCount</a></li> <li><a href="#all_server_settimeout_msecs_callback">server.setTimeout(msecs, callback)</a></li> <li><a href="#all_server_timeout">server.timeout</a></li> </ul> </li> <li><a href="#all_class_http_serverresponse">Class: http.ServerResponse</a><ul> <li><a href="#all_event_close_3">Event: 'close'</a></li> <li><a href="#all_event_finish">Event: 'finish'</a></li> <li><a href="#all_response_addtrailers_headers">response.addTrailers(headers)</a></li> <li><a href="#all_response_end_data_encoding_callback">response.end([data][, encoding][, callback])</a></li> <li><a href="#all_response_finished">response.finished</a></li> <li><a href="#all_response_getheader_name">response.getHeader(name)</a></li> <li><a href="#all_response_headerssent">response.headersSent</a></li> <li><a href="#all_response_removeheader_name">response.removeHeader(name)</a></li> <li><a href="#all_response_senddate">response.sendDate</a></li> <li><a href="#all_response_setheader_name_value">response.setHeader(name, value)</a></li> <li><a href="#all_response_settimeout_msecs_callback">response.setTimeout(msecs, callback)</a></li> <li><a href="#all_response_statuscode">response.statusCode</a></li> <li><a href="#all_response_statusmessage">response.statusMessage</a></li> <li><a href="#all_response_write_chunk_encoding_callback">response.write(chunk[, encoding][, callback])</a></li> <li><a href="#all_response_writecontinue">response.writeContinue()</a></li> <li><a href="#all_response_writehead_statuscode_statusmessage_headers">response.writeHead(statusCode[, statusMessage][, headers])</a></li> </ul> </li> <li><a href="#all_class_http_incomingmessage">Class: http.IncomingMessage</a><ul> <li><a href="#all_event_close_4">Event: 'close'</a></li> <li><a href="#all_message_headers">message.headers</a></li> <li><a href="#all_message_httpversion">message.httpVersion</a></li> <li><a href="#all_message_method">message.method</a></li> <li><a href="#all_message_rawheaders">message.rawHeaders</a></li> <li><a href="#all_message_rawtrailers">message.rawTrailers</a></li> <li><a href="#all_message_settimeout_msecs_callback">message.setTimeout(msecs, callback)</a></li> <li><a href="#all_message_statuscode">message.statusCode</a></li> <li><a href="#all_message_statusmessage">message.statusMessage</a></li> <li><a href="#all_message_socket">message.socket</a></li> <li><a href="#all_message_trailers">message.trailers</a></li> <li><a href="#all_message_url">message.url</a></li> </ul> </li> <li><a href="#all_http_methods">http.METHODS</a></li> <li><a href="#all_http_status_codes">http.STATUS_CODES</a></li> <li><a href="#all_http_createclient_port_host">http.createClient([port][, host])</a></li> <li><a href="#all_http_createserver_requestlistener">http.createServer([requestListener])</a></li> <li><a href="#all_http_get_options_callback">http.get(options[, callback])</a></li> <li><a href="#all_http_globalagent">http.globalAgent</a></li> <li><a href="#all_http_request_options_callback">http.request(options[, callback])</a></li> </ul> </li> <li><a href="#all_https">HTTPS</a><ul> <li><a href="#all_class_https_agent">Class: https.Agent</a></li> <li><a href="#all_class_https_server">Class: https.Server</a><ul> <li><a href="#all_server_settimeout_msecs_callback_1">server.setTimeout(msecs, callback)</a></li> <li><a href="#all_server_timeout_1">server.timeout</a></li> </ul> </li> <li><a href="#all_https_createserver_options_requestlistener">https.createServer(options[, requestListener])</a><ul> <li><a href="#all_server_close_callback_1">server.close([callback])</a></li> <li><a href="#all_server_listen_handle_callback_1">server.listen(handle[, callback])</a></li> <li><a href="#all_server_listen_path_callback_1">server.listen(path[, callback])</a></li> <li><a href="#all_server_listen_port_host_backlog_callback">server.listen(port[, host][, backlog][, callback])</a></li> </ul> </li> <li><a href="#all_https_get_options_callback">https.get(options, callback)</a></li> <li><a href="#all_https_globalagent">https.globalAgent</a></li> <li><a href="#all_https_request_options_callback">https.request(options, callback)</a></li> </ul> </li> <li><a href="#all_modules">Modules</a><ul> <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> <li><a href="#all_all_together">All Together...</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_core_modules">Core Modules</a></li> <li><a href="#all_cycles">Cycles</a></li> <li><a href="#all_file_modules">File Modules</a></li> <li><a href="#all_folders_as_modules">Folders as 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_loading_from_the_global_folders">Loading from the global folders</a></li> <li><a href="#all_the_module_object">The <code>module</code> Object</a><ul> <li><a href="#all_module_children">module.children</a></li> <li><a href="#all_module_exports">module.exports</a><ul> <li><a href="#all_exports_alias">exports alias</a></li> </ul> </li> <li><a href="#all_module_filename">module.filename</a></li> <li><a href="#all_module_id">module.id</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_require_id">module.require(id)</a></li> </ul> </li> </ul> </li> <li><a href="#all_net">net</a><ul> <li><a href="#all_class_net_server">Class: net.Server</a><ul> <li><a href="#all_event_close_5">Event: 'close'</a></li> <li><a href="#all_event_connection_1">Event: 'connection'</a></li> <li><a href="#all_event_error_4">Event: 'error'</a></li> <li><a href="#all_event_listening_3">Event: 'listening'</a></li> <li><a href="#all_server_address">server.address()</a></li> <li><a href="#all_server_close_callback_2">server.close([callback])</a></li> <li><a href="#all_server_connections">server.connections</a></li> <li><a href="#all_server_getconnections_callback">server.getConnections(callback)</a></li> <li><a href="#all_server_listen_handle_backlog_callback">server.listen(handle[, backlog][, callback])</a></li> <li><a href="#all_server_listen_options_callback">server.listen(options[, callback])</a></li> <li><a href="#all_server_listen_path_backlog_callback">server.listen(path[, backlog][, callback])</a></li> <li><a href="#all_server_listen_port_hostname_backlog_callback_1">server.listen(port[, hostname][, backlog][, callback])</a></li> <li><a href="#all_server_maxconnections">server.maxConnections</a></li> <li><a href="#all_server_ref">server.ref()</a></li> <li><a href="#all_server_unref">server.unref()</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_event_close_6">Event: 'close'</a></li> <li><a href="#all_event_connect_2">Event: 'connect'</a></li> <li><a href="#all_event_data">Event: 'data'</a></li> <li><a href="#all_event_drain">Event: 'drain'</a></li> <li><a href="#all_event_end">Event: 'end'</a></li> <li><a href="#all_event_error_5">Event: 'error'</a></li> <li><a href="#all_event_lookup">Event: 'lookup'</a></li> <li><a href="#all_event_timeout">Event: 'timeout'</a></li> <li><a href="#all_socket_address_1">socket.address()</a></li> <li><a href="#all_socket_buffersize">socket.bufferSize</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_socket_connect_options_connectlistener">socket.connect(options[, connectListener])</a></li> <li><a href="#all_socket_connect_path_connectlistener">socket.connect(path[, connectListener])</a></li> <li><a href="#all_socket_connect_port_host_connectlistener">socket.connect(port[, host][, connectListener])</a></li> <li><a href="#all_socket_destroy">socket.destroy()</a></li> <li><a href="#all_socket_end_data_encoding">socket.end([data][, encoding])</a></li> <li><a href="#all_socket_localaddress">socket.localAddress</a></li> <li><a href="#all_socket_localport">socket.localPort</a></li> <li><a href="#all_socket_pause">socket.pause()</a></li> <li><a href="#all_socket_ref_1">socket.ref()</a></li> <li><a href="#all_socket_remoteaddress">socket.remoteAddress</a></li> <li><a href="#all_socket_remotefamily">socket.remoteFamily</a></li> <li><a href="#all_socket_remoteport">socket.remotePort</a></li> <li><a href="#all_socket_resume">socket.resume()</a></li> <li><a href="#all_socket_setencoding_encoding">socket.setEncoding([encoding])</a></li> <li><a href="#all_socket_setkeepalive_enable_initialdelay">socket.setKeepAlive([enable][, initialDelay])</a></li> <li><a href="#all_socket_setnodelay_nodelay">socket.setNoDelay([noDelay])</a></li> <li><a href="#all_socket_settimeout_timeout_callback">socket.setTimeout(timeout[, callback])</a></li> <li><a href="#all_socket_unref_1">socket.unref()</a></li> <li><a href="#all_socket_write_data_encoding_callback">socket.write(data[, encoding][, callback])</a></li> </ul> </li> <li><a href="#all_net_connect_options_connectlistener">net.connect(options[, connectListener])</a></li> <li><a href="#all_net_connect_path_connectlistener">net.connect(path[, connectListener])</a></li> <li><a href="#all_net_connect_port_host_connectlistener">net.connect(port[, host][, connectListener])</a></li> <li><a href="#all_net_createconnection_options_connectlistener">net.createConnection(options[, connectListener])</a></li> <li><a href="#all_net_createconnection_path_connectlistener">net.createConnection(path[, connectListener])</a></li> <li><a href="#all_net_createconnection_port_host_connectlistener">net.createConnection(port[, host][, connectListener])</a></li> <li><a href="#all_net_createserver_options_connectionlistener">net.createServer([options][, connectionListener])</a></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_os">OS</a><ul> <li><a href="#all_os_eol">os.EOL</a></li> <li><a href="#all_os_arch">os.arch()</a></li> <li><a href="#all_os_cpus">os.cpus()</a></li> <li><a href="#all_os_endianness">os.endianness()</a></li> <li><a href="#all_os_freemem">os.freemem()</a></li> <li><a href="#all_os_homedir">os.homedir()</a></li> <li><a href="#all_os_hostname">os.hostname()</a></li> <li><a href="#all_os_loadavg">os.loadavg()</a></li> <li><a href="#all_os_networkinterfaces">os.networkInterfaces()</a></li> <li><a href="#all_os_platform">os.platform()</a></li> <li><a href="#all_os_release">os.release()</a></li> <li><a href="#all_os_tmpdir">os.tmpdir()</a></li> <li><a href="#all_os_totalmem">os.totalmem()</a></li> <li><a href="#all_os_type">os.type()</a></li> <li><a href="#all_os_uptime">os.uptime()</a></li> </ul> </li> <li><a href="#all_path">Path</a><ul> <li><a href="#all_path_basename_p_ext">path.basename(p[, ext])</a></li> <li><a href="#all_path_delimiter">path.delimiter</a></li> <li><a href="#all_path_dirname_p">path.dirname(p)</a></li> <li><a href="#all_path_extname_p">path.extname(p)</a></li> <li><a href="#all_path_format_pathobject">path.format(pathObject)</a></li> <li><a href="#all_path_isabsolute_path">path.isAbsolute(path)</a></li> <li><a href="#all_path_join_path1_path2">path.join([path1][, path2][, ...])</a></li> <li><a href="#all_path_normalize_p">path.normalize(p)</a></li> <li><a href="#all_path_parse_pathstring">path.parse(pathString)</a></li> <li><a href="#all_path_posix">path.posix</a></li> <li><a href="#all_path_relative_from_to">path.relative(from, to)</a></li> <li><a href="#all_path_resolve_from_to">path.resolve([from ...], to)</a></li> <li><a href="#all_path_sep">path.sep</a></li> <li><a href="#all_path_win32">path.win32</a></li> </ul> </li> <li><a href="#all_process_1">process</a><ul> <li><a href="#all_event_beforeexit">Event: 'beforeExit'</a></li> <li><a href="#all_event_exit_3">Event: 'exit'</a></li> <li><a href="#all_event_message_4">Event: 'message'</a></li> <li><a href="#all_event_rejectionhandled">Event: 'rejectionHandled'</a></li> <li><a href="#all_event_uncaughtexception">Event: 'uncaughtException'</a></li> <li><a href="#all_event_unhandledrejection">Event: 'unhandledRejection'</a></li> <li><a href="#all_exit_codes">Exit Codes</a></li> <li><a href="#all_signal_events">Signal Events</a></li> <li><a href="#all_process_abort">process.abort()</a></li> <li><a href="#all_process_arch">process.arch</a></li> <li><a href="#all_process_argv">process.argv</a></li> <li><a href="#all_process_chdir_directory">process.chdir(directory)</a></li> <li><a href="#all_process_config">process.config</a><ul> <li><a href="#all_process_connected">process.connected</a></li> </ul> </li> <li><a href="#all_process_cwd">process.cwd()</a></li> <li><a href="#all_process_disconnect">process.disconnect()</a></li> <li><a href="#all_process_env">process.env</a></li> <li><a href="#all_process_execargv">process.execArgv</a></li> <li><a href="#all_process_execpath">process.execPath</a></li> <li><a href="#all_process_exit_code">process.exit([code])</a></li> <li><a href="#all_process_exitcode">process.exitCode</a></li> <li><a href="#all_process_getegid">process.getegid()</a></li> <li><a href="#all_process_geteuid">process.geteuid()</a></li> <li><a href="#all_process_getgid">process.getgid()</a></li> <li><a href="#all_process_getgroups">process.getgroups()</a></li> <li><a href="#all_process_getuid">process.getuid()</a></li> <li><a href="#all_process_hrtime">process.hrtime()</a></li> <li><a href="#all_process_initgroups_user_extra_group">process.initgroups(user, extra_group)</a></li> <li><a href="#all_process_kill_pid_signal">process.kill(pid[, signal])</a></li> <li><a href="#all_process_mainmodule">process.mainModule</a></li> <li><a href="#all_process_memoryusage">process.memoryUsage()</a></li> <li><a href="#all_process_nexttick_callback_arg">process.nextTick(callback[, arg][, ...])</a></li> <li><a href="#all_process_pid">process.pid</a></li> <li><a href="#all_process_platform">process.platform</a></li> <li><a href="#all_process_release">process.release</a></li> <li><a href="#all_process_send_message_sendhandle_callback">process.send(message[, sendHandle][, callback])</a></li> <li><a href="#all_process_setegid_id">process.setegid(id)</a></li> <li><a href="#all_process_seteuid_id">process.seteuid(id)</a></li> <li><a href="#all_process_setgid_id">process.setgid(id)</a></li> <li><a href="#all_process_setgroups_groups">process.setgroups(groups)</a></li> <li><a href="#all_process_setuid_id">process.setuid(id)</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_stdout">process.stdout</a></li> <li><a href="#all_process_title">process.title</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_version">process.version</a></li> <li><a href="#all_process_versions">process.versions</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_toascii_domain">punycode.toASCII(domain)</a></li> <li><a href="#all_punycode_tounicode_domain">punycode.toUnicode(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_query_string">Query String</a><ul> <li><a href="#all_querystring_escape">querystring.escape</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_stringify_obj_sep_eq_options">querystring.stringify(obj[, sep][, eq][, options])</a></li> <li><a href="#all_querystring_unescape">querystring.unescape</a></li> </ul> </li> <li><a href="#all_readline">Readline</a><ul> <li><a href="#all_class_interface">Class: Interface</a><ul> <li><a href="#all_rl_close">rl.close()</a></li> <li><a href="#all_rl_pause">rl.pause()</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_resume">rl.resume()</a></li> <li><a href="#all_rl_setprompt_prompt">rl.setPrompt(prompt)</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_close_7">Event: 'close'</a></li> <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_sigcont">Event: 'SIGCONT'</a></li> <li><a href="#all_event_sigint">Event: 'SIGINT'</a></li> <li><a href="#all_event_sigtstp">Event: 'SIGTSTP'</a></li> </ul> </li> <li><a href="#all_example_tiny_cli">Example: Tiny CLI</a></li> <li><a href="#all_example_read_file_stream_line_by_line">Example: Read File Stream Line-by-Line</a></li> <li><a href="#all_readline_clearline_stream_dir">readline.clearLine(stream, dir)</a></li> <li><a href="#all_readline_clearscreendown_stream">readline.clearScreenDown(stream)</a></li> <li><a href="#all_readline_createinterface_options">readline.createInterface(options)</a></li> <li><a href="#all_readline_cursorto_stream_x_y">readline.cursorTo(stream, x, y)</a></li> <li><a href="#all_readline_movecursor_stream_dx_dy">readline.moveCursor(stream, dx, dy)</a></li> </ul> </li> <li><a href="#all_repl">REPL</a><ul> <li><a href="#all_environment_variable_options">Environment Variable Options</a></li> <li><a href="#all_persistent_history">Persistent History</a><ul> <li><a href="#all_node_repl_history_file">NODE_REPL_HISTORY_FILE</a></li> </ul> </li> <li><a href="#all_repl_features">REPL Features</a><ul> <li><a href="#all_customizing_object_displays_in_the_repl">Customizing Object displays in the REPL</a></li> </ul> </li> <li><a href="#all_class_replserver">Class: REPLServer</a><ul> <li><a href="#all_event_exit_4">Event: 'exit'</a></li> <li><a href="#all_event_reset">Event: 'reset'</a></li> <li><a href="#all_replserver_definecommand_keyword_cmd">replServer.defineCommand(keyword, cmd)</a></li> <li><a href="#all_replserver_displayprompt_preservecursor">replServer.displayPrompt([preserveCursor])</a></li> </ul> </li> <li><a href="#all_repl_start_options">repl.start(options)</a></li> </ul> </li> <li><a href="#all_stream">Stream</a><ul> <li><a href="#all_api_for_stream_consumers">API for Stream Consumers</a><ul> <li><a href="#all_class_stream_duplex">Class: stream.Duplex</a></li> <li><a href="#all_class_stream_readable">Class: stream.Readable</a><ul> <li><a href="#all_event_close_8">Event: 'close'</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_error_6">Event: 'error'</a></li> <li><a href="#all_event_readable">Event: 'readable'</a></li> <li><a href="#all_readable_ispaused">readable.isPaused()</a></li> <li><a href="#all_readable_pause">readable.pause()</a></li> <li><a href="#all_readable_pipe_destination_options">readable.pipe(destination[, options])</a></li> <li><a href="#all_readable_read_size">readable.read([size])</a></li> <li><a href="#all_readable_resume">readable.resume()</a></li> <li><a href="#all_readable_setencoding_encoding">readable.setEncoding(encoding)</a></li> <li><a href="#all_readable_unpipe_destination">readable.unpipe([destination])</a></li> <li><a href="#all_readable_unshift_chunk">readable.unshift(chunk)</a></li> <li><a href="#all_readable_wrap_stream">readable.wrap(stream)</a></li> </ul> </li> <li><a href="#all_class_stream_transform">Class: stream.Transform</a></li> <li><a href="#all_class_stream_writable">Class: stream.Writable</a><ul> <li><a href="#all_event_drain_1">Event: 'drain'</a></li> <li><a href="#all_event_error_7">Event: 'error'</a></li> <li><a href="#all_event_finish_1">Event: 'finish'</a></li> <li><a href="#all_event_pipe">Event: 'pipe'</a></li> <li><a href="#all_event_unpipe">Event: 'unpipe'</a></li> <li><a href="#all_writable_cork">writable.cork()</a></li> <li><a href="#all_writable_end_chunk_encoding_callback">writable.end([chunk][, encoding][, callback])</a></li> <li><a href="#all_writable_setdefaultencoding_encoding">writable.setDefaultEncoding(encoding)</a></li> <li><a href="#all_writable_uncork">writable.uncork()</a></li> <li><a href="#all_writable_write_chunk_encoding_callback">writable.write(chunk[, encoding][, callback])</a></li> </ul> </li> </ul> </li> <li><a href="#all_api_for_stream_implementors">API for Stream Implementors</a><ul> <li><a href="#all_class_stream_duplex_1">Class: stream.Duplex</a><ul> <li><a href="#all_new_stream_duplex_options">new stream.Duplex(options)</a></li> </ul> </li> <li><a href="#all_class_stream_passthrough">Class: stream.PassThrough</a></li> <li><a href="#all_class_stream_readable_1">Class: stream.Readable</a><ul> <li><a href="#all_new_stream_readable_options">new stream.Readable([options])</a></li> <li><a href="#all_readable_read_size_1">readable._read(size)</a></li> <li><a href="#all_readable_push_chunk_encoding">readable.push(chunk[, encoding])</a></li> <li><a href="#all_example_a_counting_stream">Example: A Counting Stream</a></li> <li><a href="#all_example_simpleprotocol_v1_sub_optimal">Example: SimpleProtocol v1 (Sub-optimal)</a></li> </ul> </li> <li><a href="#all_class_stream_transform_1">Class: stream.Transform</a><ul> <li><a href="#all_new_stream_transform_options">new stream.Transform([options])</a></li> <li><a href="#all_events_finish_and_end">Events: 'finish' and 'end'</a></li> <li><a href="#all_transform_flush_callback">transform._flush(callback)</a></li> <li><a href="#all_transform_transform_chunk_encoding_callback">transform._transform(chunk, encoding, callback)</a></li> <li><a href="#all_example_simpleprotocol_parser_v2">Example: <code>SimpleProtocol</code> parser v2</a></li> </ul> </li> <li><a href="#all_class_stream_writable_1">Class: stream.Writable</a><ul> <li><a href="#all_new_stream_writable_options">new stream.Writable([options])</a></li> <li><a href="#all_writable_write_chunk_encoding_callback_1">writable._write(chunk, encoding, callback)</a></li> <li><a href="#all_writable_writev_chunks_callback">writable._writev(chunks, callback)</a></li> </ul> </li> </ul> </li> <li><a href="#all_simplified_constructor_api">Simplified Constructor API</a><ul> <li><a href="#all_duplex">Duplex</a></li> <li><a href="#all_readable">Readable</a></li> <li><a href="#all_transform">Transform</a></li> <li><a href="#all_writable">Writable</a></li> </ul> </li> <li><a href="#all_streams_under_the_hood">Streams: Under the Hood</a><ul> <li><a href="#all_buffering">Buffering</a></li> <li><a href="#all_compatibility_with_older_node_js_versions">Compatibility with Older Node.js Versions</a></li> <li><a href="#all_object_mode">Object Mode</a></li> <li><a href="#all_stream_read_0"><code>stream.read(0)</code></a></li> <li><a href="#all_stream_push"><code>stream.push('')</code></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_decoder_end">decoder.end()</a></li> <li><a href="#all_decoder_write_buffer">decoder.write(buffer)</a></li> </ul> </li> </ul> </li> <li><a href="#all_timers">Timers</a><ul> <li><a href="#all_clearimmediate_immediateobject">clearImmediate(immediateObject)</a></li> <li><a href="#all_clearinterval_intervalobject">clearInterval(intervalObject)</a></li> <li><a href="#all_cleartimeout_timeoutobject">clearTimeout(timeoutObject)</a></li> <li><a href="#all_ref">ref()</a></li> <li><a href="#all_setimmediate_callback_arg">setImmediate(callback[, arg][, ...])</a></li> <li><a href="#all_setinterval_callback_delay_arg">setInterval(callback, delay[, arg][, ...])</a></li> <li><a href="#all_settimeout_callback_delay_arg">setTimeout(callback, delay[, arg][, ...])</a></li> <li><a href="#all_unref">unref()</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_modifying_the_default_tls_cipher_suite">Modifying the Default TLS Cipher suite</a></li> <li><a href="#all_npn_and_sni">NPN and SNI</a></li> <li><a href="#all_perfect_forward_secrecy">Perfect Forward Secrecy</a></li> <li><a href="#all_class_cryptostream">Class: CryptoStream</a><ul> <li><a href="#all_cryptostream_byteswritten">cryptoStream.bytesWritten</a></li> </ul> </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_clienterror_1">Event: 'clientError'</a></li> <li><a href="#all_event_newsession">Event: 'newSession'</a></li> <li><a href="#all_event_ocsprequest">Event: 'OCSPRequest'</a></li> <li><a href="#all_event_resumesession">Event: 'resumeSession'</a></li> <li><a href="#all_event_secureconnection">Event: 'secureConnection'</a></li> <li><a href="#all_server_addcontext_hostname_context">server.addContext(hostname, context)</a></li> <li><a href="#all_server_address_1">server.address()</a></li> <li><a href="#all_server_close_callback_3">server.close([callback])</a></li> <li><a href="#all_server_connections_1">server.connections</a></li> <li><a href="#all_server_getticketkeys">server.getTicketKeys()</a></li> <li><a href="#all_server_listen_port_hostname_callback">server.listen(port[, hostname][, callback])</a></li> <li><a href="#all_server_maxconnections_1">server.maxConnections</a></li> <li><a href="#all_server_setticketkeys_keys">server.setTicketKeys(keys)</a></li> </ul> </li> <li><a href="#all_class_tls_tlssocket">Class: tls.TLSSocket</a></li> <li><a href="#all_new_tls_tlssocket_socket_options">new tls.TLSSocket(socket[, options])</a><ul> <li><a href="#all_event_ocspresponse">Event: 'OCSPResponse'</a></li> <li><a href="#all_event_secureconnect">Event: 'secureConnect'</a></li> <li><a href="#all_tlssocket_address">tlsSocket.address()</a></li> <li><a href="#all_tlssocket_authorized">tlsSocket.authorized</a></li> <li><a href="#all_tlssocket_authorizationerror">tlsSocket.authorizationError</a></li> <li><a href="#all_tlssocket_encrypted">tlsSocket.encrypted</a></li> <li><a href="#all_tlssocket_getcipher">tlsSocket.getCipher()</a></li> <li><a href="#all_tlssocket_getpeercertificate_detailed">tlsSocket.getPeerCertificate([ detailed ])</a></li> <li><a href="#all_tlssocket_getsession">tlsSocket.getSession()</a></li> <li><a href="#all_tlssocket_gettlsticket">tlsSocket.getTLSTicket()</a></li> <li><a href="#all_tlssocket_localport">tlsSocket.localPort</a></li> <li><a href="#all_tlssocket_localaddress">tlsSocket.localAddress</a></li> <li><a href="#all_tlssocket_remoteaddress">tlsSocket.remoteAddress</a></li> <li><a href="#all_tlssocket_remotefamily">tlsSocket.remoteFamily</a></li> <li><a href="#all_tlssocket_remoteport">tlsSocket.remotePort</a></li> <li><a href="#all_tlssocket_renegotiate_options_callback">tlsSocket.renegotiate(options, callback)</a></li> <li><a href="#all_tlssocket_setmaxsendfragment_size">tlsSocket.setMaxSendFragment(size)</a></li> </ul> </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_createsecurecontext_details">tls.createSecureContext(details)</a></li> <li><a href="#all_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized">tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized])</a></li> <li><a href="#all_tls_createserver_options_secureconnectionlistener">tls.createServer(options[, secureConnectionListener])</a></li> <li><a href="#all_tls_getciphers">tls.getCiphers()</a></li> </ul> </li> <li><a href="#all_tty">TTY</a><ul> <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_event_resize">Event: 'resize'</a></li> <li><a href="#all_ws_columns">ws.columns</a></li> <li><a href="#all_ws_rows">ws.rows</a></li> </ul> </li> <li><a href="#all_tty_isatty_fd">tty.isatty(fd)</a></li> <li><a href="#all_tty_setrawmode_mode">tty.setRawMode(mode)</a></li> </ul> </li> <li><a href="#all_url">URL</a><ul> <li><a href="#all_url_parsing">URL Parsing</a><ul> <li><a href="#all_escaped_characters">Escaped Characters</a></li> </ul> </li> <li><a href="#all_url_format_urlobj">url.format(urlObj)</a></li> <li><a href="#all_url_parse_urlstr_parsequerystring_slashesdenotehost">url.parse(urlStr[, parseQueryString][, slashesDenoteHost])</a></li> <li><a href="#all_url_resolve_from_to">url.resolve(from, to)</a></li> </ul> </li> <li><a href="#all_util">util</a><ul> <li><a href="#all_util_debug_string">util.debug(string)</a></li> <li><a href="#all_util_debuglog_section">util.debuglog(section)</a></li> <li><a href="#all_util_deprecate_function_string">util.deprecate(function, string)</a></li> <li><a href="#all_util_error">util.error([...])</a></li> <li><a href="#all_util_format_format">util.format(format[, ...])</a></li> <li><a href="#all_util_inherits_constructor_superconstructor">util.inherits(constructor, superConstructor)</a></li> <li><a href="#all_util_inspect_object_options">util.inspect(object[, options])</a><ul> <li><a href="#all_customizing_util_inspect_colors">Customizing <code>util.inspect</code> colors</a></li> <li><a href="#all_custom_inspect_function_on_objects">Custom <code>inspect()</code> function on Objects</a></li> </ul> </li> <li><a href="#all_util_isarray_object">util.isArray(object)</a></li> <li><a href="#all_util_isboolean_object">util.isBoolean(object)</a></li> <li><a href="#all_util_isbuffer_object">util.isBuffer(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_isfunction_object">util.isFunction(object)</a></li> <li><a href="#all_util_isnull_object">util.isNull(object)</a></li> <li><a href="#all_util_isnullorundefined_object">util.isNullOrUndefined(object)</a></li> <li><a href="#all_util_isnumber_object">util.isNumber(object)</a></li> <li><a href="#all_util_isobject_object">util.isObject(object)</a></li> <li><a href="#all_util_isprimitive_object">util.isPrimitive(object)</a></li> <li><a href="#all_util_isregexp_object">util.isRegExp(object)</a></li> <li><a href="#all_util_isstring_object">util.isString(object)</a></li> <li><a href="#all_util_issymbol_object">util.isSymbol(object)</a></li> <li><a href="#all_util_isundefined_object">util.isUndefined(object)</a></li> <li><a href="#all_util_log_string">util.log(string)</a></li> <li><a href="#all_util_print">util.print([...])</a></li> <li><a href="#all_util_pump_readablestream_writablestream_callback">util.pump(readableStream, writableStream[, callback])</a></li> <li><a href="#all_util_puts">util.puts([...])</a></li> </ul> </li> <li><a href="#all_v8">V8</a><ul> <li><a href="#all_getheapstatistics">getHeapStatistics()</a></li> <li><a href="#all_setflagsfromstring_string">setFlagsFromString(string)</a></li> </ul> </li> <li><a href="#all_executing_javascript">Executing JavaScript</a><ul> <li><a href="#all_class_script">Class: Script</a><ul> <li><a href="#all_new_vm_script_code_options">new vm.Script(code, options)</a></li> <li><a href="#all_script_runincontext_contextifiedsandbox_options">script.runInContext(contextifiedSandbox[, options])</a></li> <li><a href="#all_script_runinnewcontext_sandbox_options">script.runInNewContext([sandbox][, options])</a></li> <li><a href="#all_script_runinthiscontext_options">script.runInThisContext([options])</a></li> </ul> </li> <li><a href="#all_vm_createcontext_sandbox">vm.createContext([sandbox])</a></li> <li><a href="#all_vm_iscontext_sandbox">vm.isContext(sandbox)</a></li> <li><a href="#all_vm_runincontext_code_contextifiedsandbox_options">vm.runInContext(code, contextifiedSandbox[, options])</a></li> <li><a href="#all_vm_runindebugcontext_code">vm.runInDebugContext(code)</a></li> <li><a href="#all_vm_runinnewcontext_code_sandbox_options">vm.runInNewContext(code[, sandbox][, options])</a></li> <li><a href="#all_vm_runinthiscontext_code_options">vm.runInThisContext(code[, options])</a></li> </ul> </li> <li><a href="#all_zlib">Zlib</a><ul> <li><a href="#all_examples">Examples</a></li> <li><a href="#all_memory_usage_tuning">Memory Usage Tuning</a></li> <li><a href="#all_constants">Constants</a></li> <li><a href="#all_class_options">Class Options</a></li> <li><a href="#all_class_zlib_deflate">Class: zlib.Deflate</a></li> <li><a href="#all_class_zlib_deflateraw">Class: zlib.DeflateRaw</a></li> <li><a href="#all_class_zlib_gunzip">Class: zlib.Gunzip</a></li> <li><a href="#all_class_zlib_gzip">Class: zlib.Gzip</a></li> <li><a href="#all_class_zlib_inflate">Class: zlib.Inflate</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_class_zlib_zlib">Class: zlib.Zlib</a><ul> <li><a href="#all_zlib_flush_kind_callback">zlib.flush([kind], callback)</a></li> <li><a href="#all_zlib_params_level_strategy_callback">zlib.params(level, strategy, callback)</a></li> <li><a href="#all_zlib_reset">zlib.reset()</a></li> </ul> </li> <li><a href="#all_zlib_createdeflate_options">zlib.createDeflate([options])</a></li> <li><a href="#all_zlib_createdeflateraw_options">zlib.createDeflateRaw([options])</a></li> <li><a href="#all_zlib_creategunzip_options">zlib.createGunzip([options])</a></li> <li><a href="#all_zlib_creategzip_options">zlib.createGzip([options])</a></li> <li><a href="#all_zlib_createinflate_options">zlib.createInflate([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_convenience_methods">Convenience Methods</a><ul> <li><a href="#all_zlib_deflate_buf_options_callback">zlib.deflate(buf[, options], callback)</a></li> <li><a href="#all_zlib_deflateraw_buf_options_callback">zlib.deflateRaw(buf[, options], callback)</a></li> <li><a href="#all_zlib_deflaterawsync_buf_options">zlib.deflateRawSync(buf[, options])</a></li> <li><a href="#all_zlib_deflatesync_buf_options">zlib.deflateSync(buf[, options])</a></li> <li><a href="#all_zlib_gunzip_buf_options_callback">zlib.gunzip(buf[, options], callback)</a></li> <li><a href="#all_zlib_gunzipsync_buf_options">zlib.gunzipSync(buf[, options])</a></li> <li><a href="#all_zlib_gzip_buf_options_callback">zlib.gzip(buf[, options], callback)</a></li> <li><a href="#all_zlib_gzipsync_buf_options">zlib.gzipSync(buf[, options])</a></li> <li><a href="#all_zlib_inflate_buf_options_callback">zlib.inflate(buf[, options], callback)</a></li> <li><a href="#all_zlib_inflateraw_buf_options_callback">zlib.inflateRaw(buf[, options], callback)</a></li> <li><a href="#all_zlib_inflaterawsync_buf_options">zlib.inflateRawSync(buf[, options])</a></li> <li><a href="#all_zlib_inflatesync_buf_options">zlib.inflateSync(buf[, options])</a></li> <li><a href="#all_zlib_unzip_buf_options_callback">zlib.unzip(buf[, options], callback)</a></li> <li><a href="#all_zlib_unzipsync_buf_options">zlib.unzipSync(buf[, options])</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.js'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 stability indices are as follows: </p> <pre class="api_stability_0">Stability: 0 - Deprecated 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.</pre><pre class="api_stability_1">Stability: 1 - Experimental This feature is subject to change, and is gated by a command line flag. It may change or be removed in future versions.</pre><pre class="api_stability_2">Stability: 2 - Stable The API has proven satisfactory. Compatibility with the npm ecosystem is a high priority, and will not be broken unless absolutely necessary.</pre><pre class="api_stability_3">Stability: 3 - Locked Only fixes related to security, performance, or bug fixes will be accepted. Please do not suggest API changes in this area; they will be refused.</pre><h2>JSON Output<span><a class="mark" href="#all_json_output" id="all_json_output">#</a></span></h2> <pre class="api_stability_1">Stability: 1 - Experimental</pre><p>Every HTML file in the markdown has a corresponding JSON file with the same data. </p> <p>This feature was added in Node.js 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.js which responds with <code>'Hello World'</code>: </p> <pre><code>const http = require('http'); http.createServer( (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>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.js source tree), which is also available <a href="http://man7.org/linux/man-pages/man3/errno.3.html">online</a>.</p> </li> <li><p><a href="https://github.com/libuv/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 be 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.js libraries. The most important class is <code>node::ObjectWrap</code> 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.js 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> <p>All of the following examples are available for <a href="https://github.com/nodejs/node-addon-examples">download</a> and may be used as a starting-point for your own Addon. </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>module.exports.hello = function() { return 'world'; };</code></pre> <p>First we create a file <code>hello.cc</code>: </p> <pre><code>// hello.cc #include <node.h> namespace demo { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; void Method(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world")); } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "hello", Method); } NODE_MODULE(addon, init) } // namespace demo</code></pre> <p>Note that all Node.js addons must export an initialization function: </p> <pre><code>void Initialize(Local<Object> exports); 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 (excluding the .node suffix). </p> <p>The source code needs to be built into <code>addon.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/nodejs/node-gyp">node-gyp</a>. </p> <pre><code>{ "targets": [ { "target_name": "addon", "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.js project <code>hello.js</code> by pointing <code>require</code> to the recently built <code>hello.node</code> module: </p> <pre><code>// hello.js const addon = require('./build/Release/addon'); 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="https://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. For example: </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>// addon.cc #include <node.h> namespace demo { using v8::Exception; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; using v8::String; using v8::Value; void Add(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); if (args.Length() < 2) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Wrong number of arguments"))); return; } if (!args[0]->IsNumber() || !args[1]->IsNumber()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Wrong arguments"))); return; } double value = args[0]->NumberValue() + args[1]->NumberValue(); Local<Number> num = Number::New(isolate, value); args.GetReturnValue().Set(num); } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "add", Add); } NODE_MODULE(addon, Init) } // namespace demo</code></pre> <p>You can test it with the following JavaScript snippet: </p> <pre><code>// test.js const 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>// addon.cc #include <node.h> namespace demo { using v8::Function; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Null; using v8::Object; using v8::String; using v8::Value; void RunCallback(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Function> cb = Local<Function>::Cast(args[0]); const unsigned argc = 1; Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") }; cb->Call(Null(isolate), argc, argv); } void Init(Local<Object> exports, Local<Object> module) { NODE_SET_METHOD(module, "exports", RunCallback); } NODE_MODULE(addon, Init) } // namespace demo</code></pre> <p>Note that this example uses a two-argument form of <code>Init()</code> that receives the full <code>module</code> object as the second argument. This allows the addon to completely overwrite <code>exports</code> with a single function instead of adding the function as a property of <code>exports</code>. </p> <p>To test it, run the following JavaScript snippet: </p> <pre><code>// test.js const addon = require('./build/Release/addon'); addon(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>// addon.cc #include <node.h> namespace demo { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; void CreateObject(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Object> obj = Object::New(isolate); obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString()); args.GetReturnValue().Set(obj); } void Init(Local<Object> exports, Local<Object> module) { NODE_SET_METHOD(module, "exports", CreateObject); } NODE_MODULE(addon, Init) } // namespace demo</code></pre> <p>To test it in JavaScript: </p> <pre><code>// test.js const addon = require('./build/Release/addon'); var obj1 = addon('hello'); var obj2 = addon('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>// addon.cc #include <node.h> namespace demo { using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; void MyFunction(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world")); } void CreateFunction(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction); Local<Function> fn = tpl->GetFunction(); // omit this to make it anonymous fn->SetName(String::NewFromUtf8(isolate, "theFunction")); args.GetReturnValue().Set(fn); } void Init(Local<Object> exports, Local<Object> module) { NODE_SET_METHOD(module, "exports", CreateFunction); } NODE_MODULE(addon, Init) } // namespace demo</code></pre> <p>To test: </p> <pre><code>// test.js const addon = require('./build/Release/addon'); var fn = addon(); 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>// addon.cc #include <node.h> #include "myobject.h" namespace demo { using v8::Local; using v8::Object; void InitAll(Local<Object> exports) { MyObject::Init(exports); } NODE_MODULE(addon, InitAll) } // namespace demo</code></pre> <p>Then, in <code>myobject.h</code>, make your wrapper inherit from <code>node::ObjectWrap</code>: </p> <pre><code>// myobject.h #ifndef MYOBJECT_H #define MYOBJECT_H #include <node.h> #include <node_object_wrap.h> namespace demo { class MyObject : public node::ObjectWrap { public: static void Init(v8::Local<v8::Object> exports); private: explicit MyObject(double value = 0); ~MyObject(); static void New(const v8::FunctionCallbackInfo<v8::Value>& args); static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args); static v8::Persistent<v8::Function> constructor; double value_; }; } // namespace demo #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>// myobject.cc #include "myobject.h" namespace demo { using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; Persistent<Function> MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init(Local<Object> exports) { Isolate* isolate = exports->GetIsolate(); // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); constructor.Reset(isolate, tpl->GetFunction()); exports->Set(String::NewFromUtf8(isolate, "MyObject"), tpl->GetFunction()); } void MyObject::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); args.GetReturnValue().Set(cons->NewInstance(argc, argv)); } } void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder()); obj->value_ += 1; args.GetReturnValue().Set(Number::New(isolate, obj->value_)); } } // namespace demo</code></pre> <p>Test it with: </p> <pre><code>// test.js const 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. For example: </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>// addon.cc #include <node.h> #include "myobject.h" namespace demo { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; void CreateObject(const FunctionCallbackInfo<Value>& args) { MyObject::NewInstance(args); } void InitAll(Local<Object> exports, Local<Object> module) { MyObject::Init(exports->GetIsolate()); NODE_SET_METHOD(module, "exports", CreateObject); } NODE_MODULE(addon, InitAll) } // namespace demo</code></pre> <p>In <code>myobject.h</code>, we now introduce the static method <code>NewInstance</code> that takes care of instantiating the object. In other words, it does the job of <code>new</code> in JavaScript: </p> <pre><code>// myobject.h #ifndef MYOBJECT_H #define MYOBJECT_H #include <node.h> #include <node_object_wrap.h> namespace demo { class MyObject : public node::ObjectWrap { public: static void Init(v8::Isolate* isolate); static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args); private: explicit MyObject(double value = 0); ~MyObject(); static void New(const v8::FunctionCallbackInfo<v8::Value>& args); static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args); static v8::Persistent<v8::Function> constructor; double value_; }; } // namespace demo #endif</code></pre> <p>The implementation is similar to the above in <code>myobject.cc</code>: </p> <pre><code>// myobject.cc #include <node.h> #include "myobject.h" namespace demo { using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; Persistent<Function> MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init(Isolate* isolate) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); constructor.Reset(isolate, tpl->GetFunction()); } void MyObject::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); args.GetReturnValue().Set(cons->NewInstance(argc, argv)); } } void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); const unsigned argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); Local<Object> instance = cons->NewInstance(argc, argv); args.GetReturnValue().Set(instance); } void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder()); obj->value_ += 1; args.GetReturnValue().Set(Number::New(isolate, obj->value_)); } } // namespace demo</code></pre> <p>Test it with: </p> <pre><code>// test.js const createObject = require('./build/Release/addon'); var obj = createObject(10); console.log( obj.plusOne() ); // 11 console.log( obj.plusOne() ); // 12 console.log( obj.plusOne() ); // 13 var obj2 = 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 the Node.js helper function <code>node::ObjectWrap::Unwrap</code>. 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>// addon.cc #include <node.h> #include <node_object_wrap.h> #include "myobject.h" namespace demo { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; using v8::String; using v8::Value; void CreateObject(const FunctionCallbackInfo<Value>& args) { MyObject::NewInstance(args); } void Add(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>( args[0]->ToObject()); MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>( args[1]->ToObject()); double sum = obj1->value() + obj2->value(); args.GetReturnValue().Set(Number::New(isolate, sum)); } void InitAll(Local<Object> exports) { MyObject::Init(exports->GetIsolate()); NODE_SET_METHOD(exports, "createObject", CreateObject); NODE_SET_METHOD(exports, "add", Add); } NODE_MODULE(addon, InitAll) } // namespace demo</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>// myobject.h #ifndef MYOBJECT_H #define MYOBJECT_H #include <node.h> #include <node_object_wrap.h> namespace demo { class MyObject : public node::ObjectWrap { public: static void Init(v8::Isolate* isolate); static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args); inline double value() const { return value_; } private: explicit MyObject(double value = 0); ~MyObject(); static void New(const v8::FunctionCallbackInfo<v8::Value>& args); static v8::Persistent<v8::Function> constructor; double value_; }; } // namespace demo #endif</code></pre> <p>The implementation of <code>myobject.cc</code> is similar to before: </p> <pre><code>// myobject.cc #include <node.h> #include "myobject.h" namespace demo { using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; Persistent<Function> MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init(Isolate* isolate) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); constructor.Reset(isolate, tpl->GetFunction()); } void MyObject::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); args.GetReturnValue().Set(cons->NewInstance(argc, argv)); } } void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); const unsigned argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); Local<Object> instance = cons->NewInstance(argc, argv); args.GetReturnValue().Set(instance); } } // namespace demo</code></pre> <p>Test it with: </p> <pre><code>// test.js const 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> <h3>AtExit hooks<span><a class="mark" href="#all_atexit_hooks" id="all_atexit_hooks">#</a></span></h3> <h4>void AtExit(callback, args)<span><a class="mark" href="#all_void_atexit_callback_args" id="all_void_atexit_callback_args">#</a></span></h4> <ul> <li><code>callback</code>: <code>void (*)(void*)</code> - A pointer to the function to call at exit.</li> <li><code>args</code>: <code>void*</code> - A pointer to pass to the callback at exit.</li> </ul> <p>Registers exit hooks that run after the event loop has ended but before the VM is killed. </p> <p>Callbacks are run in last-in first-out order. AtExit takes two parameters: a pointer to a callback function to run at exit, and a pointer to untyped context data to be passed to that callback. </p> <p>The file <code>addon.cc</code> implements AtExit below: </p> <pre><code>// addon.cc #undef NDEBUG #include <assert.h> #include <stdlib.h> #include <node.h> namespace demo { using node::AtExit; using v8::HandleScope; using v8::Isolate; using v8::Local; using v8::Object; static char cookie[] = "yum yum"; static int at_exit_cb1_called = 0; static int at_exit_cb2_called = 0; static void at_exit_cb1(void* arg) { Isolate* isolate = static_cast<Isolate*>(arg); HandleScope scope(isolate); Local<Object> obj = Object::New(isolate); assert(!obj.IsEmpty()); // assert VM is still alive assert(obj->IsObject()); at_exit_cb1_called++; } static void at_exit_cb2(void* arg) { assert(arg == static_cast<void*>(cookie)); at_exit_cb2_called++; } static void sanity_check(void*) { assert(at_exit_cb1_called == 1); assert(at_exit_cb2_called == 2); } void init(Local<Object> exports) { AtExit(sanity_check); AtExit(at_exit_cb2, cookie); AtExit(at_exit_cb2, cookie); AtExit(at_exit_cb1, exports->GetIsolate()); } NODE_MODULE(addon, init); } // namespace demo</code></pre> <p>Test in JavaScript by running: </p> <pre><code>// test.js const addon = require('./build/Release/addon');</code></pre> <h1>Assert<span><a class="mark" href="#all_assert" id="all_assert">#</a></span></h1> <pre class="api_stability_3">Stability: 3 - Locked</pre><p>The <code>assert</code> module provides a simple set of assertion tests that can be used to test invariants. The module is intended for internal use by Node.js, but can be used in application code via <code>require('assert')</code>. However, <code>assert</code> is not a testing framework, and is not intended to be used as a general purpose assertion library. </p> <p>The API for the <code>assert</code> module is <a href="documentation.html#documentation_stability_index">Locked</a>. This means that there will be no additions or changes to any of the methods implemented and exposed by the module. </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 <code>value</code> is truthy. It is equivalent to <code>assert.equal(!!value, true, message)</code>. </p> <p>If <code>value</code> is not truthy, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is <code>undefined</code>, a default error message is assigned. </p> <pre><code>const assert = require('assert'); assert(true); // OK assert(1); // OK assert(false); // throws "AssertionError: false == true" assert(0); // throws "AssertionError: 0 == true" assert(false, 'it\'s false'); // throws "AssertionError: it's false" assert.ok(true); // OK assert.ok(1); // OK assert.ok(false); // throws "AssertionError: false == true" assert.ok(0); // throws "AssertionError: 0 == true" assert.ok(false, 'it\'s false'); // throws "AssertionError: it's false"</code></pre> <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 between the <code>actual</code> and <code>expected</code> parameters. Primitive values are compared with the equal comparison operator ( <code>==</code> ). </p> <p>Only enumerable "own" properties are considered. The <code>deepEqual()</code> implementation does not test object prototypes, attached symbols, or non-enumerable properties. This can lead to some potentially surprising results. For example, the following example does not throw an <code>AssertionError</code> because the properties on the <a href="errors.html#errors_class_error"><code>Error</code></a> object are non-enumerable: </p> <pre><code>// WARNING: This does not throw an AssertionError! assert.deepEqual(Error('a'), Error('b'));</code></pre> <p>"Deep" equality means that the enumerable "own" properties of child objects are evaluated also: </p> <pre><code>const assert = require('assert'); const obj1 = { a : { b : 1 } }; const obj2 = { a : { b : 2 } }; const obj3 = { a : { b : 1 } } const obj4 = Object.create(obj1); assert.deepEqual(obj1, obj1); // OK, object is equal to itself assert.deepEqual(obj1, obj2); // AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } } // values of b are different assert.deepEqual(obj1, obj3); // OK, objects are equal assert.deepEqual(obj1, obj4); // AssertionError: { a: { b: 1 } } deepEqual {} // Prototypes are ignored</code></pre> <p>If the values are not equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. </p> <h2>assert.deepStrictEqual(actual, expected[, message])<span><a class="mark" href="#all_assert_deepstrictequal_actual_expected_message" id="all_assert_deepstrictequal_actual_expected_message">#</a></span></h2> <p>Generally identical to <code>assert.deepEqual</code> with the exception that primitive values are compared using the strict equality operator ( <code>===</code> ). </p> <pre><code>const assert = require('assert'); assert.deepEqual({a:1}, {a:'1'}); // OK, because 1 == '1' assert.deepStrictEqual({a:1}, {a:'1'}); // AssertionError: { a: 1 } deepStrictEqual { a: '1' } // because 1 !== '1' using strict equality</code></pre> <p>If the values are not equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. </p> <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>Asserts that the function <code>block</code> does not throw an error. See <a href="#assert_assert_throws_block_error_message"><code>assert.throws()</code></a> for more details. </p> <p>When <code>assert.doesNotThrow()</code> is called, it will immediately call the <code>block</code> function. </p> <p>If an error is thrown and it is the same type as that specified by the <code>error</code> parameter, then an <code>AssertionError</code> is thrown. If the error is of a different type, or if the <code>error</code> parameter is undefined, the error is propagated back to the caller. </p> <p>The following, for instance, will throw the <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> because there is no matching error type in the assertion: </p> <pre><code>assert.doesNotThrow( function() { throw new TypeError('Wrong value'); }, SyntaxError );</code></pre> <p>However, the following will result in an <code>AssertionError</code> with the message 'Got unwanted exception (TypeError)..': </p> <pre><code>assert.doesNotThrow( function() { throw new TypeError('Wrong value'); }, TypeError );</code></pre> <p>If an <code>AssertionError</code> is thrown and a value is provided for the <code>message</code> parameter, the value of <code>message</code> will be appended to the <code>AssertionError</code> message: </p> <pre><code>assert.doesNotThrow( function() { throw new TypeError('Wrong value'); }, TypeError, 'Whoops' ); // Throws: AssertionError: Got unwanted exception (TypeError). Whoops</code></pre> <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 between the <code>actual</code> and <code>expected</code> parameters using the equal comparison operator ( <code>==</code> ). </p> <pre><code>const assert = require('assert'); assert.equal(1, 1); // OK, 1 == 1 assert.equal(1, '1'); // OK, 1 == '1' assert.equal(1, 2); // AssertionError: 1 == 2 assert.equal({a: {b: 1}}, {a: {b: 1}}); //AssertionError: { a: { b: 1 } } == { a: { b: 1 } }</code></pre> <p>If the values are not equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. </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 <code>AssertionError</code>. If <code>message</code> is falsy, the error message is set as the values of <code>actual</code> and <code>expected</code> separated by the provided <code>operator</code>. Otherwise, the error message is the value of <code>message</code>. </p> <pre><code>const assert = require('assert'); assert.fail(1, 2, undefined, '>'); // AssertionError: 1 > 2 assert.fail(1, 2, 'whoops', '>'); // AssertionError: whoops</code></pre> <h2>assert.ifError(value)<span><a class="mark" href="#all_assert_iferror_value" id="all_assert_iferror_value">#</a></span></h2> <p>Throws <code>value</code> if <code>value</code> is truthy. This is useful when testing the <code>error</code> argument in callbacks. </p> <pre><code>const assert = require('assert'); assert.ifError(0); // OK assert.ifError(1); // Throws 1 assert.ifError('error') // Throws 'error' assert.ifError(new Error()); // Throws Error</code></pre> <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. Opposite of <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual</code></a>. </p> <pre><code>const assert = require('assert'); const obj1 = { a : { b : 1 } }; const obj2 = { a : { b : 2 } }; const obj3 = { a : { b : 1 } } const obj4 = Object.create(obj1); assert.deepEqual(obj1, obj1); AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } assert.deepEqual(obj1, obj2); // OK, obj1 and obj2 are not deeply equal assert.deepEqual(obj1, obj3); // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } assert.deepEqual(obj1, obj4); // OK, obj1 and obj2 are not deeply equal</code></pre> <p>If the values are deeply equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. </p> <h2>assert.notDeepStrictEqual(actual, expected[, message])<span><a class="mark" href="#all_assert_notdeepstrictequal_actual_expected_message" id="all_assert_notdeepstrictequal_actual_expected_message">#</a></span></h2> <p>Tests for deep strict inequality. Opposite of <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual</code></a>. </p> <pre><code>const assert = require('assert'); assert.notDeepEqual({a:1}, {a:'1'}); // AssertionError: { a: 1 } notDeepEqual { a: '1' } assert.notDeepStrictEqual({a:1}, {a:'1'}); // OK</code></pre> <p>If the values are deeply and strictly equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. </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 inequality with the not equal comparison operator ( <code>!=</code> ). </p> <pre><code>const assert = require('assert'); assert.notEqual(1, 2); // OK assert.notEqual(1, 1); // AssertionError: 1 != 1 assert.notEqual(1, '1'); // AssertionError: 1 != '1'</code></pre> <p>If the values are equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. </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 inequality as determined by the strict not equal operator ( <code>!==</code> ). </p> <pre><code>const assert = require('assert'); assert.notStrictEqual(1, 2); // OK assert.notStrictEqual(1, 1); // AssertionError: 1 != 1 assert.notStrictEqual(1, '1'); // OK</code></pre> <p>If the values are strictly equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. </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> <pre><code>const assert = require('assert'); assert.strictEqual(1, 2); // AssertionError: 1 === 2 assert.strictEqual(1, 1); // OK assert.strictEqual(1, '1'); // AssertionError: 1 === '1'</code></pre> <p>If the values are not strictly equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. </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 the function <code>block</code> to throw an error. If specified, <code>error</code> can be a constructor, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, 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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>: </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> <h1>Buffer<span><a class="mark" href="#all_buffer" id="all_buffer">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</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.js 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. The different string encodings are: </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.</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 the buffer into a one-byte (<code>latin-1</code>) encoded string. The string <code>'latin-1'</code> is not supported. Instead, pass <code>'binary'</code> to use <code>'latin-1'</code> encoding.</p> </li> <li><p><code>'hex'</code> - Encode each byte as two hexadecimal characters.</p> </li> </ul> <p>Creating a typed array from a <code>Buffer</code> works with the following caveats: </p> <ol> <li><p>The buffer's memory is copied, not shared.</p> </li> <li><p>The buffer's memory is interpreted as an array, not a byte array. That is, <code>new Uint32Array(new Buffer([1,2,3,4]))</code> creates a 4-element <code>Uint32Array</code> with elements <code>[1,2,3,4]</code>, not a <code>Uint32Array</code> with a single element <code>[0x1020304]</code> or <code>[0x4030201]</code>.</p> </li> </ol> <p>NOTE: Node.js v0.8 retained a reference to the buffer in <code>array.buffer</code> instead of cloning it. </p> <p>While more efficient, it introduces subtle incompatibilities with the typed arrays specification. <code>ArrayBuffer#slice()</code> makes a copy of the slice while <a href="#buffer_buf_slice_start_end"><code>Buffer#slice()</code></a> creates a view. </p> <h2>Class: Buffer<span><a class="mark" href="#all_class_buffer" id="all_class_buffer">#</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(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(buffer)<span><a class="mark" href="#all_new_buffer_buffer" id="all_new_buffer_buffer">#</a></span></h3> <div class="signature"><ul> <li><code>buffer</code> <span class="type">Buffer</span></li> </div></ul> <p>Copies the passed <code>buffer</code> data onto a new <code>Buffer</code> instance. </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> bytes. <code>size</code> must be less than 1,073,741,824 bytes (1 GB) on 32-bit architectures or 2,147,483,648 bytes (2 GB) on 64-bit architectures. Otherwise, a <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> is thrown. </p> <p>Unlike <code>ArrayBuffers</code>, the underlying memory for buffers is not initialized. So the contents of a newly created <code>Buffer</code> are unknown and could contain sensitive data. Use <a href="#buffer_buf_fill_value_offset_end"><code>buf.fill(0)</code></a> to initialize a buffer to zeroes. </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>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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length"><code>String.prototype.length</code></a> 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.compare(buf1, buf2)<span><a class="mark" href="#all_class_method_buffer_compare_buf1_buf2" id="all_class_method_buffer_compare_buf1_buf2">#</a></span></h3> <div class="signature"><ul> <li><code>buf1</code> <span class="type">Buffer</span></li> <li><code>buf2</code> <span class="type">Buffer</span></li> </div></ul> <p>The same as <a href="#buffer_buf_compare_otherbuffer"><code>buf1.compare(buf2)</code></a>. Useful for sorting an Array of Buffers: </p> <pre><code>var arr = [Buffer('1234'), Buffer('0123')]; arr.sort(Buffer.compare);</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 in the list 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 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> <p>Example: build a single buffer from a list of three buffers: </p> <pre><code>var buf1 = new Buffer(10); var buf2 = new Buffer(14); var buf3 = new Buffer(18); buf1.fill(0); buf2.fill(0); buf3.fill(0); var buffers = [buf1, buf2, buf3]; var totalLength = 0; for (var i = 0; i < buffers.length; i++) { totalLength += buffers[i].length; } console.log(totalLength); var bufA = Buffer.concat(buffers, totalLength); console.log(bufA); console.log(bufA.length); // 42 // <Buffer 00 00 00 00 ...> // 42</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.isEncoding(encoding)<span><a class="mark" href="#all_class_method_buffer_isencoding_encoding" id="all_class_method_buffer_isencoding_encoding">#</a></span></h3> <div class="signature"><ul> <li><code>encoding</code> <span class="type">String</span> The encoding string to test</li> </div></ul> <p>Returns true if the <code>encoding</code> is a valid encoding argument, or false otherwise. </p> <h3>buffer.entries()<span><a class="mark" href="#all_buffer_entries" id="all_buffer_entries">#</a></span></h3> <p>Creates iterator for <code>[index, byte]</code> arrays. </p> <h3>buffer.keys()<span><a class="mark" href="#all_buffer_keys" id="all_buffer_keys">#</a></span></h3> <p>Creates iterator for buffer keys (indices). </p> <h3>buffer.values()<span><a class="mark" href="#all_buffer_values" id="all_buffer_values">#</a></span></h3> <p>Creates iterator for buffer values (bytes). This function is called automatically when <code>buffer</code> is used in a <code>for..of</code> statement. </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>buf.compare(otherBuffer)<span><a class="mark" href="#all_buf_compare_otherbuffer" id="all_buf_compare_otherbuffer">#</a></span></h3> <div class="signature"><ul> <li><code>otherBuffer</code> <span class="type">Buffer</span></li> </div></ul> <p>Returns a number indicating whether <code>this</code> comes before, after, or is the same as the <code>otherBuffer</code> in sort order. </p> <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>Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If <code>undefined</code>, the <code>targetStart</code> and <code>sourceStart</code> parameters default to <code>0</code> while <code>sourceEnd</code> defaults to <code>buffer.length</code>. </p> <p>Returns the number of bytes copied. </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> <p>Example: Build a single buffer, then copy data from one region to an overlapping region in the same buffer </p> <pre><code>buf = new Buffer(26); for (var i = 0 ; i < 26 ; i++) { buf[i] = i + 97; // 97 is ASCII a } buf.copy(buf, 0, 4, 10); console.log(buf.toString()); // efghijghijklmnopqrstuvwxyz</code></pre> <h3>buf.equals(otherBuffer)<span><a class="mark" href="#all_buf_equals_otherbuffer" id="all_buf_equals_otherbuffer">#</a></span></h3> <div class="signature"><ul> <li><code>otherBuffer</code> <span class="type">Buffer</span></li> </div></ul> <p>Returns a boolean indicating whether <code>this</code> and <code>otherBuffer</code> have the same bytes. </p> <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> <h3>buf.indexOf(value[, byteOffset])<span><a class="mark" href="#all_buf_indexof_value_byteoffset" id="all_buf_indexof_value_byteoffset">#</a></span></h3> <div class="signature"><ul> <li><code>value</code> String, Buffer or Number</li> <li><code>byteOffset</code> Number, Optional, Default: 0</li> <li>Return: Number</li> </div></ul> <p>Operates similar to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf"><code>Array#indexOf()</code></a>. Accepts a String, Buffer or Number. Strings are interpreted as UTF8. Buffers will use the entire buffer. So in order to compare a partial Buffer use <a href="#buffer_buf_slice_start_end"><code>Buffer#slice()</code></a>. Numbers can range from 0 to 255. </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> <p>While the <code>length</code> property is not immutable, changing the value of <code>length</code> can result in undefined and inconsistent behavior. Applications that wish to modify the length of a buffer should therefore treat <code>length</code> as read-only and use <a href="#buffer_buf_slice_start_end"><code>buf.slice</code></a> to create a new buffer. </p> <pre><code>buf = new Buffer(10); buf.write('abcdefghj', 0, 'ascii'); console.log(buf.length); // 10 buf = buf.slice(0,5); console.log(buf.length); // 5</code></pre> <h3>buf.readDoubleBE(offset[, noAssert])<span><a class="mark" href="#all_buf_readdoublebe_offset_noassert" id="all_buf_readdoublebe_offset_noassert">#</a></span></h3> <h3>buf.readDoubleLE(offset[, noAssert])<span><a class="mark" href="#all_buf_readdoublele_offset_noassert" id="all_buf_readdoublele_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.readFloatBE(offset[, noAssert])<span><a class="mark" href="#all_buf_readfloatbe_offset_noassert" id="all_buf_readfloatbe_offset_noassert">#</a></span></h3> <h3>buf.readFloatLE(offset[, noAssert])<span><a class="mark" href="#all_buf_readfloatle_offset_noassert" id="all_buf_readfloatle_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.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.readInt16BE(offset[, noAssert])<span><a class="mark" href="#all_buf_readint16be_offset_noassert" id="all_buf_readint16be_offset_noassert">#</a></span></h3> <h3>buf.readInt16LE(offset[, noAssert])<span><a class="mark" href="#all_buf_readint16le_offset_noassert" id="all_buf_readint16le_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.readInt32BE(offset[, noAssert])<span><a class="mark" href="#all_buf_readint32be_offset_noassert" id="all_buf_readint32be_offset_noassert">#</a></span></h3> <h3>buf.readInt32LE(offset[, noAssert])<span><a class="mark" href="#all_buf_readint32le_offset_noassert" id="all_buf_readint32le_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.readIntBE(offset, byteLength[, noAssert])<span><a class="mark" href="#all_buf_readintbe_offset_bytelength_noassert" id="all_buf_readintbe_offset_bytelength_noassert">#</a></span></h3> <h3>buf.readIntLE(offset, byteLength[, noAssert])<span><a class="mark" href="#all_buf_readintle_offset_bytelength_noassert" id="all_buf_readintle_offset_bytelength_noassert">#</a></span></h3> <ul> <li><code>offset</code> {Number} <code>0 <= offset <= buf.length</code></li> <li><code>byteLength</code> {Number} <code>0 < byteLength <= 6</code></li> <li><code>noAssert</code> {Boolean} Default: false</li> <li>Return: {Number}</li> </ul> <p>A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. For example: </p> <pre><code>var b = new Buffer(6); b.writeUInt16LE(0x90ab, 0); b.writeUInt32LE(0x12345678, 2); b.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) // output: '1234567890ab'</code></pre> <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> <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.readUInt16BE(offset[, noAssert])<span><a class="mark" href="#all_buf_readuint16be_offset_noassert" id="all_buf_readuint16be_offset_noassert">#</a></span></h3> <h3>buf.readUInt16LE(offset[, noAssert])<span><a class="mark" href="#all_buf_readuint16le_offset_noassert" id="all_buf_readuint16le_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.readUInt32BE(offset[, noAssert])<span><a class="mark" href="#all_buf_readuint32be_offset_noassert" id="all_buf_readuint32be_offset_noassert">#</a></span></h3> <h3>buf.readUInt32LE(offset[, noAssert])<span><a class="mark" href="#all_buf_readuint32le_offset_noassert" id="all_buf_readuint32le_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.readUIntBE(offset, byteLength[, noAssert])<span><a class="mark" href="#all_buf_readuintbe_offset_bytelength_noassert" id="all_buf_readuintbe_offset_bytelength_noassert">#</a></span></h3> <h3>buf.readUIntLE(offset, byteLength[, noAssert])<span><a class="mark" href="#all_buf_readuintle_offset_bytelength_noassert" id="all_buf_readuintle_offset_bytelength_noassert">#</a></span></h3> <ul> <li><code>offset</code> {Number} <code>0 <= offset <= buf.length</code></li> <li><code>byteLength</code> {Number} <code>0 < byteLength <= 6</code></li> <li><code>noAssert</code> {Boolean} Default: false</li> <li>Return: {Number}</li> </ul> <p>A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. For example: </p> <pre><code>var b = new Buffer(6); b.writeUInt16LE(0x90ab, 0); b.writeUInt32LE(0x12345678, 2); b.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) // output: '1234567890ab'</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. Negative indexes start from the end of the buffer. </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.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 using the specified character set encoding. If <code>encoding</code> is <code>undefined</code> or <code>null</code>, then <code>encoding</code> defaults to <code>'utf8'</code>. The <code>start</code> and <code>end</code> parameters default to <code>0</code> and <code>buffer.length</code> when <code>undefined</code>. </p> <pre><code>buf = new Buffer(26); for (var i = 0 ; i < 26 ; i++) { buf[i] = i + 97; // 97 is ASCII a } buf.toString('ascii'); // outputs: abcdefghijklmnopqrstuvwxyz buf.toString('ascii',0,5); // outputs: abcde buf.toString('utf8',0,5); // outputs: abcde buf.toString(undefined,0,5); // encoding defaults to 'utf8', outputs abcde</code></pre> <p>See <code>buf.write()</code> example, below. </p> <h3>buf.toJSON()<span><a class="mark" href="#all_buf_tojson" id="all_buf_tojson">#</a></span></h3> <p>Returns a JSON representation of the Buffer instance. <code>JSON.stringify</code> implicitly calls this function when stringifying a Buffer instance. </p> <p>Example: </p> <pre><code>var buf = new Buffer('test'); var json = JSON.stringify(buf); console.log(json); // '{"type":"Buffer","data":[116,101,115,116]}' var copy = JSON.parse(json, function(key, value) { return value && value.type === 'Buffer' ? new Buffer(value.data) : value; }); console.log(copy); // <Buffer 74 65 73 74></code></pre> <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> <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> <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> <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. <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.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> <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> <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. Behavior is unspecified if <code>value</code> is not a 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.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. <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.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> <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> <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. <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.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> <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> <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. <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.writeIntBE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#all_buf_writeintbe_value_offset_bytelength_noassert" id="all_buf_writeintbe_value_offset_bytelength_noassert">#</a></span></h3> <h3>buf.writeIntLE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#all_buf_writeintle_value_offset_bytelength_noassert" id="all_buf_writeintle_value_offset_bytelength_noassert">#</a></span></h3> <ul> <li><code>value</code> {Number} Bytes to be written to buffer</li> <li><code>offset</code> {Number} <code>0 <= offset <= buf.length</code></li> <li><code>byteLength</code> {Number} <code>0 < byteLength <= 6</code></li> <li><code>noAssert</code> {Boolean} Default: false</li> <li>Return: {Number}</li> </ul> <p>Writes <code>value</code> to the buffer at the specified <code>offset</code> and <code>byteLength</code>. Supports up to 48 bits of accuracy. For example: </p> <pre><code>var b = new Buffer(6); b.writeUIntBE(0x1234567890ab, 0, 6); // <Buffer 12 34 56 78 90 ab></code></pre> <p>Set <code>noAssert</code> to <code>true</code> to skip validation of <code>value</code> and <code>offset</code>. Defaults to <code>false</code>. </p> <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. <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.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> <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> <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. <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.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> <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> <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. <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.writeUIntBE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#all_buf_writeuintbe_value_offset_bytelength_noassert" id="all_buf_writeuintbe_value_offset_bytelength_noassert">#</a></span></h3> <h3>buf.writeUIntLE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#all_buf_writeuintle_value_offset_bytelength_noassert" id="all_buf_writeuintle_value_offset_bytelength_noassert">#</a></span></h3> <ul> <li><code>value</code> {Number} Bytes to be written to buffer</li> <li><code>offset</code> {Number} <code>0 <= offset <= buf.length</code></li> <li><code>byteLength</code> {Number} <code>0 < byteLength <= 6</code></li> <li><code>noAssert</code> {Boolean} Default: false</li> <li>Return: {Number}</li> </ul> <p>Writes <code>value</code> to the buffer at the specified <code>offset</code> and <code>byteLength</code>. Supports up to 48 bits of accuracy. For example: </p> <pre><code>var b = new Buffer(6); b.writeUIntBE(0x1234567890ab, 0, 6); // <Buffer 12 34 56 78 90 ab></code></pre> <p>Set <code>noAssert</code> to <code>true</code> to skip validation of <code>value</code> and <code>offset</code>. Defaults to <code>false</code>. </p> <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. See <a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a> for more details on <code>buffer.inspect()</code> behavior. </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>ES6 iteration<span><a class="mark" href="#all_es6_iteration" id="all_es6_iteration">#</a></span></h2> <p>Buffers can be iterated over using <code>for..of</code> syntax: </p> <pre><code>var buf = new Buffer([1, 2, 3]); for (var b of buf) console.log(b) // 1 // 2 // 3</code></pre> <p>Additionally, the <code>buffer.values()</code>, <code>buffer.keys()</code>, and <code>buffer.entries()</code> methods can be used to create iterators. </p> <h2>Class: SlowBuffer<span><a class="mark" href="#all_class_slowbuffer" id="all_class_slowbuffer">#</a></span></h2> <p>Returns an un-pooled <code>Buffer</code>. </p> <p>In order to avoid the garbage collection overhead of creating many individually allocated Buffers, by default allocations under 4KB are sliced from a single larger allocated object. This approach improves both performance and memory usage since v8 does not need to track and cleanup as many <code>Persistent</code> objects. </p> <p>In the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using SlowBuffer and copy out the relevant bits. </p> <pre><code>// need to keep around a few small chunks of memory var store = []; socket.on('readable', function() { var data = socket.read(); // allocate for retained data var sb = new SlowBuffer(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); });</code></pre> <p>This should be used only as a last resort <em>after</em> a developer has observed undue memory retention in their applications. </p> <h1>Child Process<span><a class="mark" href="#all_child_process" id="all_child_process">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>Node.js 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. (Note that some programs use line-buffered I/O internally. That doesn't affect Node.js but it means data you send to the child process may not be immediately consumed.) </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 as explained <a href="#errors_error_propagation_and_interception">below</a>. </p> <p>For scripting purposes you may find the <a href="#child_process_synchronous_process_creation">synchronous counterparts</a> more convenient. </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"><code>EventEmitter</code></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 <code>ChildProcess</code> class is not intended to be used directly. Use the <a href="#child_process_child_process_spawn_command_args_options"><code>spawn()</code></a>, <a href="#child_process_child_process_exec_command_options_callback"><code>exec()</code></a>, <a href="#child_process_child_process_execfile_file_args_options_callback"><code>execFile()</code></a>, or <a href="#child_process_child_process_fork_modulepath_args_options"><code>fork()</code></a> methods to create an instance of <code>ChildProcess</code>. </p> <h3>Event: 'close'<span><a class="mark" href="#all_event_close" id="all_event_close">#</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 when the stdio streams of a child process have all terminated. This is distinct from <code>'exit'</code>, 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 calling the <code>.disconnect()</code> method in the parent or in the child. After disconnecting it is no longer possible to send messages, and the <code>.connected</code> property is false. </p> <h3>Event: 'error'<span><a class="mark" href="#all_event_error" id="all_event_error">#</a></span></h3> <div class="signature"><ul> <li><code>err</code> <span class="type">Error Object</span> the error.</li> </div></ul> <p>Emitted when: </p> <ol> <li>The process could not be spawned, or</li> <li>The process could not be killed, or</li> <li>Sending a message to the child process failed.</li> </ol> <p>Note that the <code>'exit'</code> event may or may not fire after an error has occurred. If you are listening on both events to fire a function, remember to guard against calling your function twice. </p> <p>See also <a href="#child_process_child_kill_signal"><code>ChildProcess#kill()</code></a> and <a href="#child_process_child_send_message_sendhandle_callback"><code>ChildProcess#send()</code></a>. </p> <h3>Event: 'exit'<span><a class="mark" href="#all_event_exit" id="all_event_exit">#</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>Also, note that Node.js establishes signal handlers for <code>SIGINT</code> and <code>SIGTERM</code>. It will not terminate due to receipt of those signals. It will exit. </p> <p>See <code>waitpid(2)</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>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 <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> or <a href="net.html#net_class_net_server"><code>net.Server</code></a> object, or undefined.</li> </div></ul> <p>Messages sent by <code>.send(message, [sendHandle])</code> are obtained using the <code>'message'</code> event. </p> <h3>child.connected<span><a class="mark" href="#all_child_connected" id="all_child_connected">#</a></span></h3> <div class="signature"><ul> <li><span class="type">Boolean</span> Set to false after <code>.disconnect</code> is called</li> </div></ul> <p>If <code>.connected</code> is false, it is no longer possible to send messages. </p> <h3>child.disconnect()<span><a class="mark" href="#all_child_disconnect" id="all_child_disconnect">#</a></span></h3> <p>Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive. After calling this method the <code>.connected</code> flag will be set to <code>false</code> in both the parent and child, and it is no longer possible to send messages. </p> <p>The <code>'disconnect'</code> event will be emitted when there are no messages in the process of being received, most likely immediately. </p> <p>Note that you can also call <code>process.disconnect()</code> in the child process when the child process has any open IPC channels with the parent (i.e <a href="#child_process_child_process_fork_modulepath_args_options"><code>fork()</code></a>). </p> <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>const spawn = require('child_process').spawn; const grep = spawn('grep', ['ssh']); grep.on('close', (code, signal) => { console.log( `child process terminated due to receipt of signal ${signal}`); }); // send SIGHUP to process grep.kill('SIGHUP');</code></pre> <p>May emit an <code>'error'</code> event when the signal cannot be delivered. Sending a signal to a child process that has already exited is not an error but may have unforeseen consequences. Specifically, if the process identifier (PID) has been reassigned to another process, the signal will be delivered to that process instead. What happens next is anyone's guess. </p> <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.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 process identifier (PID) of the child process. </p> <p>Example: </p> <pre><code>const spawn = require('child_process').spawn; const grep = spawn('grep', ['ssh']); console.log(`Spawned child pid: ${grep.pid}`); grep.stdin.end();</code></pre> <h3>child.send(message[, sendHandle][, callback])<span><a class="mark" href="#all_child_send_message_sendhandle_callback" id="all_child_send_message_sendhandle_callback">#</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> <li><code>callback</code> <span class="type">Function</span></li> <li>Return: Boolean</li> </div></ul> <p>When using <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> you can write to the child using <code>child.send(message[, sendHandle][, callback])</code> and messages are received by a <code>'message'</code> event on the child. </p> <p>For example: </p> <pre><code>const cp = require('child_process'); const n = cp.fork(`${__dirname}/sub.js`); n.on('message', (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', (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.js core. Messages containing the prefix are emitted in the <code>'internalMessage'</code> event. 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>The <code>callback</code> option is a function that is invoked after the message is sent but before the target may have received it. It is called with a single argument: <code>null</code> on success, or an <a href="errors.html#errors_class_error"><code>Error</code></a> object on failure. </p> <p><code>child.send()</code> emits an <code>'error'</code> event if no callback was given and the message cannot be sent, for example because the child process has already exited. </p> <p>Returns <code>true</code> under normal circumstances or <code>false</code> when the backlog of unsent messages exceeds a threshold that makes it unwise to send more. Use the callback mechanism to implement flow control. </p> <h4>Example: sending server object<span><a class="mark" href="#all_example_sending_server_object" id="all_example_sending_server_object">#</a></span></h4> <p>Here is an example of sending a server: </p> <pre><code>const child = require('child_process').fork('child.js'); // Open up the server object and send the handle. const server = require('net').createServer(); server.on('connection', (socket) => { socket.end('handled by parent'); }); server.listen(1337, () => { child.send('server', server); });</code></pre> <p>And the child would then receive the server object as: </p> <pre><code>process.on('message', (m, server) => { if (m === 'server') { server.on('connection', (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>For <code>dgram</code> servers the workflow is exactly the same. Here you listen on a <code>'message'</code> event instead of <code>'connection'</code> and use <code>server.bind</code> instead of <code>server.listen</code>. (Currently only supported on UNIX platforms.) </p> <h4>Example: sending socket object<span><a class="mark" href="#all_example_sending_socket_object" id="all_example_sending_socket_object">#</a></span></h4> <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>const normal = require('child_process').fork('child.js', ['normal']); const special = require('child_process').fork('child.js', ['special']); // Open up the server and send sockets to child const server = require('net').createServer(); server.on('connection', (socket) => { // if this is a VIP if (socket.remoteAddress === '74.125.127.100') { special.send('socket', socket); return; } // just the usual... 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', (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.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 was not spawned with <code>stdio[2]</code> set to <code>'pipe'</code>, then this will not be set. </p> <p><code>child.stderr</code> is shorthand for <code>child.stdio[2]</code>. Both properties will refer to the same object, or null. </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>. If the child is waiting to read all its input, it will not continue until this stream has been closed via <code>end()</code>. </p> <p>If the child was not spawned with <code>stdio[0]</code> set to <code>'pipe'</code>, then this will not be set. </p> <p><code>child.stdin</code> is shorthand for <code>child.stdio[0]</code>. Both properties will refer to the same object, or null. </p> <h3>child.stdio<span><a class="mark" href="#all_child_stdio" id="all_child_stdio">#</a></span></h3> <div class="signature"><ul> <li><span class="type">Array</span></li> </div></ul> <p>A sparse array of pipes to the child process, corresponding with positions in the <a href="#child_process_options_stdio"><code>stdio</code></a> option to <a href="#child_process_child_process_spawn_command_args_options"><code>spawn()</code></a> that have been set to <code>'pipe'</code>. Note that streams 0-2 are also available as ChildProcess.stdin, ChildProcess.stdout, and ChildProcess.stderr, respectively. </p> <p>In the following example, only the child's fd <code>1</code> is setup as a pipe, so only the parent's <code>child.stdio[1]</code> is a stream, all other values in the array are <code>null</code>. </p> <pre><code>const assert = require('assert'); const fs = require('fs'); const child_process = require('child_process'); const child = child_process.spawn('ls', { stdio: [ 0, // use parents stdin for child 'pipe', // pipe child's stdout to parent fs.openSync('err.out', 'w') // direct child's stderr to a file ] }); assert.equal(child.stdio[0], null); assert.equal(child.stdio[0], child.stdin); assert(child.stdout); assert.equal(child.stdio[1], child.stdout); assert.equal(child.stdio[2], null); assert.equal(child.stdio[2], child.stderr);</code></pre> <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 was not spawned with <code>stdio[1]</code> set to <code>'pipe'</code>, then this will not be set. </p> <p><code>child.stdout</code> is shorthand for <code>child.stdio[1]</code>. Both properties will refer to the same object, or null. </p> <h2>Asynchronous Process Creation<span><a class="mark" href="#all_asynchronous_process_creation" id="all_asynchronous_process_creation">#</a></span></h2> <p>These methods follow the common async programming patterns (accepting a callback or returning an EventEmitter). </p> <h3>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></h3> <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>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>shell</code> <span class="type">String</span> Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the <code>-c</code> switch on UNIX or <code>/s /c</code> on Windows. On Windows, command line parsing should be compatible with <code>cmd.exe</code>.)</li> <li><code>timeout</code> <span class="type">Number</span> (Default: 0)</li> <li><code>maxBuffer</code> <span class="type">Number</span> largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: <code>200*1024</code>)</li> <li><code>killSignal</code> <span class="type">String</span> (Default: 'SIGTERM')</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><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>const exec = require('child_process').exec; const child = exec('cat *.js bad_file | wc -l', (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 <a href="errors.html#errors_class_error"><code>Error</code></a> and <code>error.code</code> will be the exit code of the child process, and <code>error.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 (in bytes) allowed on stdout or stderr - if this value is exceeded then the child process is killed. </p> <p><em>Note: Unlike the <code>exec()</code> POSIX system call, <code>child_process.exec()</code> does not replace the existing process and uses a shell to execute the command.</em> </p> <h3>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></h3> <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>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> largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: 200*1024)</li> <li><code>killSignal</code> <span class="type">String</span> (Default: 'SIGTERM')</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><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 <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> except it does not execute a subshell but rather the specified file directly. This makes it slightly leaner than <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>. It has the same options. </p> <h3>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></h3> <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>execPath</code> <span class="type">String</span> Executable used to create the child process</li> <li><code>execArgv</code> <span class="type">Array</span> List of string arguments passed to the executable (Default: <code>process.execArgv</code>)</li> <li><code>silent</code> <span class="type">Boolean</span> If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the <code>'pipe'</code> and <code>'inherit'</code> options for <a href="#child_process_child_process_spawn_command_args_options"><code>spawn()</code></a>'s <a href="#child_process_options_stdio"><code>stdio</code></a> for more details (default is false)</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: ChildProcess object</li> </div></ul> <p>This is a special case of the <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> functionality for spawning Node.js processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. See <a href="#child_process_child_send_message_sendhandle_callback"><code>ChildProcess#send()</code></a> for details. </p> <p>These child Node.js processes are still whole new instances of V8. Assume at least 30ms startup and 10mb memory for each new Node.js. That is, you cannot create many thousands of them. </p> <p>The <code>execPath</code> property in the <code>options</code> object allows for a process to be created for the child rather than the current <code>node</code> executable. This should be done with care and by default will talk over the fd represented an environmental variable <code>NODE_CHANNEL_FD</code> on the child process. The input and output on this fd is expected to be line delimited JSON objects. </p> <p><em>Note: Unlike the <code>fork()</code> POSIX system call, <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> does not clone the current process.</em> </p> <h3>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></h3> <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>env</code> <span class="type">Object</span> Environment key-value pairs</li> <li><code>stdio</code> <span class="type">Array|String</span> Child's stdio configuration. (See <a href="#child_process_options_stdio">below</a>)</li> <li><code>detached</code> <span class="type">Boolean</span> Prepare child to run independently of its parent process. Specific behavior depends on the platform, see <a href="#child_process_options_detached">below</a>)</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, with these defaults: </p> <pre><code>{ cwd: undefined, env: process.env }</code></pre> <p>Use <code>cwd</code> to specify the working directory from which the process is spawned. If not given, the default is to inherit the current working directory. </p> <p>Use <code>env</code> to specify environment variables that will be visible to the new process, the default is <code>process.env</code>. </p> <p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the exit code: </p> <pre><code>const spawn = require('child_process').spawn; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); ls.on('close', (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>const spawn = require('child_process').spawn; const ps = spawn('ps', ['ax']); const grep = spawn('grep', ['ssh']); ps.stdout.on('data', (data) => { grep.stdin.write(data); }); ps.stderr.on('data', (data) => { console.log(`ps stderr: ${data}`); }); ps.on('close', (code) => { if (code !== 0) { console.log(`ps process exited with code ${code}`); } grep.stdin.end(); }); grep.stdout.on('data', (data) => { console.log(`${data}`); }); grep.stderr.on('data', (data) => { console.log(`grep stderr: ${data}`); }); grep.on('close', (code) => { if (code !== 0) { console.log(`grep process exited with code ${code}`); } });</code></pre> <p>Example of checking for failed exec: </p> <pre><code>const spawn = require('child_process').spawn; const child = spawn('bad_command'); child.on('error', (err) => { console.log('Failed to start child process.'); });</code></pre> <h4>options.detached<span><a class="mark" href="#all_options_detached" id="all_options_detached">#</a></span></h4> <p>On Windows, this makes it possible for the child to continue running after the parent exits. The child will have a new console window (this cannot be disabled). </p> <p>On non-Windows, if the <code>detached</code> option is set, the child process will be made the leader of a new process group and session. Note that child processes may continue running after the parent exits whether they are detached or not. See <code>setsid(2)</code> for more information. </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> const fs = require('fs'); const spawn = require('child_process').spawn; const out = fs.openSync('./out.log', 'a'); const err = fs.openSync('./out.log', 'a'); const 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 after the parent exits 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> <h4>options.stdio<span><a class="mark" href="#all_options_stdio" id="all_options_stdio">#</a></span></h4> <p>As a shorthand, the <code>stdio</code> argument may be one of the following strings: </p> <ul> <li><code>'pipe'</code> - <code>['pipe', 'pipe', 'pipe']</code>, this is the default value</li> <li><code>'ignore'</code> - <code>['ignore', 'ignore', 'ignore']</code></li> <li><code>'inherit'</code> - <code>[process.stdin, process.stdout, process.stderr]</code> or <code>[0,1,2]</code></li> </ul> <p>Otherwise, the <code>'stdio'</code> option to <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> 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 an 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.js will always open fd 0 - 2 for the processes it spawns. When any of these is ignored Node.js 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. Note that the stream must have an underlying descriptor (file streams do not until the <code>'open'</code> event has occurred).</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>Example: </p> <pre><code>const 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>See also: <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> </p> <h2>Synchronous Process Creation<span><a class="mark" href="#all_synchronous_process_creation" id="all_synchronous_process_creation">#</a></span></h2> <p>These methods are <strong>synchronous</strong>, meaning they <strong>WILL</strong> block the event loop, pausing execution of your code until the spawned process exits. </p> <p>Blocking calls like these are mostly useful for simplifying general purpose scripting tasks and for simplifying the loading/processing of application configuration at startup. </p> <h3>child_process.execFileSync(file[, args][, options])<span><a class="mark" href="#all_child_process_execfilesync_file_args_options" id="all_child_process_execfilesync_file_args_options">#</a></span></h3> <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>input</code> <span class="type">String|Buffer</span> The value which will be passed as stdin to the spawned process<ul> <li>supplying this value will override <code>stdio[0]</code></li> </ul> </li> <li><code>stdio</code> <span class="type">Array</span> Child's stdio configuration. (Default: 'pipe')<ul> <li><code>stderr</code> by default will be output to the parent process' stderr unless <code>stdio</code> is specified</li> </ul> </li> <li><code>env</code> <span class="type">Object</span> Environment key-value pairs</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> <li><code>timeout</code> <span class="type">Number</span> In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)</li> <li><code>killSignal</code> <span class="type">String</span> The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')</li> <li><code>maxBuffer</code> <span class="type">Number</span> largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed</li> <li><code>encoding</code> <span class="type">String</span> The encoding used for all stdio inputs and outputs. (Default: 'buffer')</li> </ul> </li> <li>return: <span class="type">Buffer|String</span> The stdout from the command</li> </div></ul> <p><code>execFileSync</code> will not return until the child process has fully closed. When a timeout has been encountered and <code>killSignal</code> is sent, the method won't return until the process has completely exited. That is to say, if the process handles the <code>SIGTERM</code> signal and doesn't exit, your process will wait until the child process has exited. </p> <p>If the process times out, or has a non-zero exit code, this method <strong><em>will</em></strong> throw. The <a href="errors.html#errors_class_error"><code>Error</code></a> object will contain the entire result from <a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a> </p> <h3>child_process.execSync(command[, options])<span><a class="mark" href="#all_child_process_execsync_command_options" id="all_child_process_execsync_command_options">#</a></span></h3> <div class="signature"><ul> <li><code>command</code> <span class="type">String</span> The command to run</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>input</code> <span class="type">String|Buffer</span> The value which will be passed as stdin to the spawned process<ul> <li>supplying this value will override <code>stdio[0]</code></li> </ul> </li> <li><code>stdio</code> <span class="type">Array</span> Child's stdio configuration. (Default: 'pipe')<ul> <li><code>stderr</code> by default will be output to the parent process' stderr unless <code>stdio</code> is specified</li> </ul> </li> <li><code>env</code> <span class="type">Object</span> Environment key-value pairs</li> <li><code>shell</code> <span class="type">String</span> Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the <code>-c</code> switch on UNIX or <code>/s /c</code> on Windows. On Windows, command line parsing should be compatible with <code>cmd.exe</code>.)</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> <li><code>timeout</code> <span class="type">Number</span> In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)</li> <li><code>killSignal</code> <span class="type">String</span> The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')</li> <li><code>maxBuffer</code> <span class="type">Number</span> largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed</li> <li><code>encoding</code> <span class="type">String</span> The encoding used for all stdio inputs and outputs. (Default: 'buffer')</li> </ul> </li> <li>return: <span class="type">Buffer|String</span> The stdout from the command</li> </div></ul> <p><code>execSync</code> will not return until the child process has fully closed. When a timeout has been encountered and <code>killSignal</code> is sent, the method won't return until the process has completely exited. That is to say, if the process handles the <code>SIGTERM</code> signal and doesn't exit, your process will wait until the child process has exited. </p> <p>If the process times out, or has a non-zero exit code, this method <strong><em>will</em></strong> throw. The <a href="errors.html#errors_class_error"><code>Error</code></a> object will contain the entire result from <a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a> </p> <h3>child_process.spawnSync(command[, args][, options])<span><a class="mark" href="#all_child_process_spawnsync_command_args_options" id="all_child_process_spawnsync_command_args_options">#</a></span></h3> <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>input</code> <span class="type">String|Buffer</span> The value which will be passed as stdin to the spawned process<ul> <li>supplying this value will override <code>stdio[0]</code></li> </ul> </li> <li><code>stdio</code> <span class="type">Array</span> Child's stdio configuration.</li> <li><code>env</code> <span class="type">Object</span> Environment key-value pairs</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> <li><code>timeout</code> <span class="type">Number</span> In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)</li> <li><code>killSignal</code> <span class="type">String</span> The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')</li> <li><code>maxBuffer</code> <span class="type">Number</span> largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed</li> <li><code>encoding</code> <span class="type">String</span> The encoding used for all stdio inputs and outputs. (Default: 'buffer')</li> </ul> </li> <li>return: <span class="type">Object</span><ul> <li><code>pid</code> <span class="type">Number</span> Pid of the child process</li> <li><code>output</code> <span class="type">Array</span> Array of results from stdio output</li> <li><code>stdout</code> <span class="type">Buffer|String</span> The contents of <code>output[1]</code></li> <li><code>stderr</code> <span class="type">Buffer|String</span> The contents of <code>output[2]</code></li> <li><code>status</code> <span class="type">Number</span> The exit code of the child process</li> <li><code>signal</code> <span class="type">String</span> The signal used to kill the child process</li> <li><code>error</code> <span class="type">Error</span> The error object if the child process failed or timed out</li> </ul> </li> </div></ul> <p><code>spawnSync</code> will not return until the child process has fully closed. When a timeout has been encountered and <code>killSignal</code> is sent, the method won't return until the process has completely exited. That is to say, if the process handles the <code>SIGTERM</code> signal and doesn't exit, your process will wait until the child process has exited. </p> <h1>Cluster<span><a class="mark" href="#all_cluster" id="all_cluster">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>A single instance of Node.js runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node.js processes to handle the load. </p> <p>The cluster module allows you to easily create child processes that all share server ports. </p> <pre><code>const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server http.createServer((req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); }</code></pre> <p>Running Node.js will now share port 8000 between the workers: </p> <pre><code>% NODE_DEBUG=cluster node server.js 23521,Master Worker 23524 online 23521,Master Worker 23526 online 23521,Master Worker 23523 online 23521,Master Worker 23528 online</code></pre> <p>Please 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>The cluster module supports two methods of distributing incoming connections. </p> <p>The first one (and the default one on all platforms except Windows), is the round-robin approach, where the master process listens on a port, accepts new connections and distributes them across the workers in a round-robin fashion, with some built-in smarts to avoid overloading a worker process. </p> <p>The second approach is where the master process creates the listen socket and sends it to interested workers. The workers then accept incoming connections directly. </p> <p>The second approach should, in theory, give the best performance. In practice however, distribution tends to be very unbalanced due to operating system scheduler vagaries. Loads have been observed where over 70% of all connections ended up in just two processes, out of a total of eight. </p> <p>Because <code>server.listen()</code> hands off most of the work to the master process, there are three cases where the behavior between a normal Node.js process and a cluster worker differs: </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>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. If no workers are alive, existing connections will be dropped and new connections will be refused. Node.js 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>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>Event: 'disconnect'<span><a class="mark" href="#all_event_disconnect_1" id="all_event_disconnect_1">#</a></span></h3> <p>Similar to the <code>cluster.on('disconnect')</code> event, but specific to this worker. </p> <pre><code>cluster.fork().on('disconnect', () => { // Worker has disconnected });</code></pre> <h3>Event: 'error'<span><a class="mark" href="#all_event_error_1" id="all_event_error_1">#</a></span></h3> <p>This event is the same as the one provided by <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>. </p> <p>In a worker you can also use <code>process.on('error')</code>. </p> <h3>Event: 'exit'<span><a class="mark" href="#all_event_exit_1" id="all_event_exit_1">#</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>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker. </p> <pre><code>const worker = cluster.fork(); worker.on('exit', (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> <h3>Event: 'listening'<span><a class="mark" href="#all_event_listening" id="all_event_listening">#</a></span></h3> <div class="signature"><ul> <li><code>address</code> <span class="type">Object</span></li> </div></ul> <p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker. </p> <pre><code>cluster.fork().on('listening', (address) => { // Worker is listening });</code></pre> <p>It is not emitted in the worker. </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></li> </div></ul> <p>Similar to the <code>cluster.on('message')</code> event, but specific to this worker. </p> <p>This event is the same as the one provided by <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>. </p> <p>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>const cluster = require('cluster'); const http = require('http'); if (cluster.isMaster) { // Keep track of http requests var numReqs = 0; setInterval(() => { console.log('numReqs =', numReqs); }, 1000); // Count requests function messageHandler(msg) { if (msg.cmd && msg.cmd == 'notifyRequest') { numReqs += 1; } } // Start workers and listen for messages containing notifyRequest const numCPUs = require('os').cpus().length; for (var i = 0; i < numCPUs; i++) { cluster.fork(); } Object.keys(cluster.workers).forEach((id) => { cluster.workers[id].on('message', messageHandler); }); } else { // Worker processes have a http server. http.Server((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" id="all_event_online">#</a></span></h3> <p>Similar to the <code>cluster.on('online')</code> event, but specific to this worker. </p> <pre><code>cluster.fork().on('online', () => { // Worker is online });</code></pre> <p>It is not emitted in the worker. </p> <h3>worker.disconnect()<span><a class="mark" href="#all_worker_disconnect" id="all_worker_disconnect">#</a></span></h3> <p>In a worker, this function will close all servers, wait for the <code>'close'</code> event on those servers, and then disconnect the IPC channel. </p> <p>In the master, an internal message is sent to the worker causing it to call <code>.disconnect()</code> on itself. </p> <p>Causes <code>.suicide</code> to be set. </p> <p>Note that after a server is closed, it will no longer accept new connections, but connections may be accepted by any other listening worker. Existing connections will be allowed to close as usual. When no more connections exist, see [server.close()][], the IPC channel to the worker will close allowing it to die gracefully. </p> <p>The above applies <em>only</em> to server connections, client connections are not automatically closed by workers, and disconnect does not wait for them to close before exiting. </p> <p>Note that in a worker, <code>process.disconnect</code> exists, but it is not this function, it is <a href="child_process.html#child_process_child_disconnect"><code>disconnect</code></a>. </p> <p>Because long living server connections may block workers from disconnecting, it may be useful to send a message, so application specific actions may be taken to close them. It also may be useful to implement a timeout, killing a worker if the <code>'disconnect'</code> event has not been emitted after some time. </p> <pre><code>if (cluster.isMaster) { var worker = cluster.fork(); var timeout; worker.on('listening', (address) => { worker.send('shutdown'); worker.disconnect(); timeout = setTimeout(() => { worker.kill(); }, 2000); }); worker.on('disconnect', () => { clearTimeout(timeout); }); } else if (cluster.isWorker) { const net = require('net'); var server = net.createServer((socket) => { // connections never end }); server.listen(8000); process.on('message', (msg) => { if(msg === 'shutdown') { // initiate graceful close of any connections to server } }); }</code></pre> <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">Number</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.isConnected()<span><a class="mark" href="#all_worker_isconnected" id="all_worker_isconnected">#</a></span></h3> <p>This function returns <code>true</code> if the worker is connected to its master via its IPC channel, <code>false</code> otherwise. A worker is connected to its master after it's been created. It is disconnected after the <code>'disconnect'</code> event is emitted. </p> <h3>worker.isDead()<span><a class="mark" href="#all_worker_isdead" id="all_worker_isdead">#</a></span></h3> <p>This function returns <code>true</code> if the worker's process has terminated (either because of exiting or being signaled). Otherwise, it returns <code>false</code>. </p> <h3>worker.kill([signal='SIGTERM'])<span><a class="mark" href="#all_worker_kill_signal_sigterm" id="all_worker_kill_signal_sigterm">#</a></span></h3> <div class="signature"><ul> <li><code>signal</code> <span class="type">String</span> Name of the kill signal to send to the worker process.</li> </div></ul> <p>This function will kill the worker. In the master, it does this by disconnecting the <code>worker.process</code>, and once disconnected, killing with <code>signal</code>. In the worker, it does it by disconnecting the channel, and then exiting with code <code>0</code>. </p> <p>Causes <code>.suicide</code> to be set. </p> <p>This method is aliased as <code>worker.destroy()</code> for backwards compatibility. </p> <p>Note that in a worker, <code>process.kill()</code> exists, but it is not this function, it is <a href="process.html#process_process_kill_pid_signal"><code>kill</code></a>. </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 <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>, the returned object from this function is stored as <code>.process</code>. In a worker, the global <code>process</code> is stored. </p> <p>See: <a href="child_process.html#child_process_child_process_fork_modulepath_args_options">Child Process module</a> </p> <p>Note that workers will call <code>process.exit(0)</code> if the <code>'disconnect'</code> event occurs on <code>process</code> and <code>.suicide</code> is not <code>true</code>. This protects against accidental disconnection. </p> <h3>worker.send(message[, sendHandle][, callback])<span><a class="mark" href="#all_worker_send_message_sendhandle_callback" id="all_worker_send_message_sendhandle_callback">#</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> <li><code>callback</code> <span class="type">Function</span></li> <li>Return: Boolean</li> </div></ul> <p>Send a message to a worker or master, optionally with a handle. </p> <p>In the master this sends a message to a specific worker. It is identical to <a href="child_process.html#child_process_child_send_message_sendhandle_callback"><code>ChildProcess.send()</code></a>. </p> <p>In a worker this sends a message to the master. It is identical to <code>process.send()</code>. </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', (msg) => { process.send(msg); }); }</code></pre> <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>Set by calling <code>.kill()</code> or <code>.disconnect()</code>, until then it is <code>undefined</code>. </p> <p>The boolean <code>worker.suicide</code> lets you distinguish between voluntary and accidental exit, the master may choose not to respawn a worker based on this value. </p> <pre><code>cluster.on('exit', (worker, code, signal) => { if (worker.suicide === true) { console.log('Oh, it was just suicide\' – no need to worry'). } }); // kill worker worker.kill();</code></pre> <h2>Event: 'disconnect'<span><a class="mark" href="#all_event_disconnect_2" id="all_event_disconnect_2">#</a></span></h2> <div class="signature"><ul> <li><code>worker</code> <span class="type">Worker object</span></li> </div></ul> <p>Emitted after the worker IPC channel has disconnected. This can occur when a worker exits gracefully, is killed, or is disconnected manually (such as with worker.disconnect()). </p> <p>There may be a delay between the <code>'disconnect'</code> and <code>'exit'</code> events. These events 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', (worker) => { console.log(`The worker #${worker.id} has disconnected`); });</code></pre> <h2>Event: 'exit'<span><a class="mark" href="#all_event_exit_2" id="all_event_exit_2">#</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 <code>'exit'</code> event. </p> <p>This can be used to restart the worker by calling <code>.fork()</code> again. </p> <pre><code>cluster.on('exit', (worker, code, signal) => { console.log('worker %d died (%s). restarting...', worker.process.pid, signal || code); cluster.fork(); });</code></pre> <p>See <a href="child_process.html#child_process_event_exit">child_process event: 'exit'</a>. </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 <code>'fork'</code> event. This can be used to log worker activity, and create your own timeout. </p> <pre><code>var timeouts = []; function errorMsg() { console.error('Something must be wrong with the connection ...'); } cluster.on('fork', (worker) => { timeouts[worker.id] = setTimeout(errorMsg, 2000); }); cluster.on('listening', (worker, address) => { clearTimeout(timeouts[worker.id]); }); cluster.on('exit', (worker, code, signal) => { clearTimeout(timeouts[worker.id]); errorMsg(); });</code></pre> <h2>Event: 'listening'<span><a class="mark" href="#all_event_listening_1" id="all_event_listening_1">#</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>After calling <code>listen()</code> from a worker, when the <code>'listening'</code> event is emitted on the server, a <code>'listening'</code> event will also be emitted on <code>cluster</code> in the master. </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', (worker, address) => { console.log( `A worker is now connected to ${address.address}:${address.port}`); });</code></pre> <p>The <code>addressType</code> is one of: </p> <ul> <li><code>4</code> (TCPv4)</li> <li><code>6</code> (TCPv6)</li> <li><code>-1</code> (unix domain socket)</li> <li><code>"udp4"</code> or <code>"udp6"</code> (UDP v4 or v6)</li> </ul> <h2>Event: 'message'<span><a class="mark" href="#all_event_message_2" id="all_event_message_2">#</a></span></h2> <div class="signature"><ul> <li><code>worker</code> <span class="type">Worker object</span></li> <li><code>message</code> <span class="type">Object</span></li> </div></ul> <p>Emitted when any worker receives a message. </p> <p>See <a href="child_process.html#child_process_event_message">child_process event: 'message'</a>. </p> <h2>Event: 'online'<span><a class="mark" href="#all_event_online_1" id="all_event_online_1">#</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 an online message. When the master receives an online message it will emit this event. The difference between <code>'fork'</code> and <code>'online'</code> is that fork is emitted when the master forks a worker, and 'online' is emitted when the worker is running. </p> <pre><code>cluster.on('online', (worker) => { console.log('Yay, the worker responded after it was forked'); });</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>settings</code> <span class="type">Object</span></li> </div></ul> <p>Emitted every time <code>.setupMaster()</code> is called. </p> <p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time <code>.setupMaster()</code> was called and is advisory only, since multiple calls to <code>.setupMaster()</code> can be made in a single tick. </p> <p>If accuracy is important, use <code>cluster.settings</code>. </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 handles are closed</li> </div></ul> <p>Calls <code>.disconnect()</code> on each worker in <code>cluster.workers</code>. </p> <p>When they are disconnected all internal handles will be closed, allowing the master process to die gracefully if no other event is waiting. </p> <p>The method takes an optional callback argument which will be called when finished. </p> <p>This can only be called from the master process. </p> <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 worker process environment.</li> <li>return <span class="type">Worker object</span></li> </div></ul> <p>Spawn a new worker process. </p> <p>This can only be called from the master process. </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>True if the process is not a master (it is the negation of <code>cluster.isMaster</code>). </p> <h2>cluster.schedulingPolicy<span><a class="mark" href="#all_cluster_schedulingpolicy" id="all_cluster_schedulingpolicy">#</a></span></h2> <p>The scheduling policy, either <code>cluster.SCHED_RR</code> for round-robin or <code>cluster.SCHED_NONE</code> to leave it to the operating system. This is a global setting and effectively frozen once you spawn the first worker or call <code>cluster.setupMaster()</code>, whatever comes first. </p> <p><code>SCHED_RR</code> is the default on all operating systems except Windows. Windows will change to <code>SCHED_RR</code> once libuv is able to effectively distribute IOCP handles without incurring a large performance hit. </p> <p><code>cluster.schedulingPolicy</code> can also be set through the <code>NODE_CLUSTER_SCHED_POLICY</code> environment variable. Valid values are <code>"rr"</code> and <code>"none"</code>. </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>execArgv</code> <span class="type">Array</span> list of string arguments passed to the Node.js executable. (Default=<code>process.execArgv</code>)</li> <li><code>exec</code> <span class="type">String</span> file path to worker file. (Default=<code>process.argv[1]</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> <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> </div></ul> <p>After calling <code>.setupMaster()</code> (or <code>.fork()</code>) this settings object will contain the settings, including the default values. </p> <p>It is effectively frozen after being set, because <code>.setupMaster()</code> can only be called once. </p> <p>This object is not supposed to be changed or set manually, by you. </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>process.argv[1]</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. Once called, the settings will be present in <code>cluster.settings</code>. </p> <p>Note that: </p> <ul> <li>any settings changes only affect future calls to <code>.fork()</code> and have no effect on workers that are already running</li> <li>The <em>only</em> attribute of a worker that cannot be set via <code>.setupMaster()</code> is the <code>env</code> passed to <code>.fork()</code></li> <li>the defaults above apply to the first call only, the defaults for later calls is the current value at the time of <code>cluster.setupMaster()</code> is called</li> </ul> <p>Example: </p> <pre><code>const cluster = require('cluster'); cluster.setupMaster({ exec: 'worker.js', args: ['--use', 'https'], silent: true }); cluster.fork(); // https worker cluster.setupMaster({ args: ['--use', 'http'] }); cluster.fork(); // http worker</code></pre> <p>This can only be called from the master process. </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>const 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> <p>A worker is removed from cluster.workers after the worker has disconnected <em>and</em> exited. The order between these two events cannot be determined in advance. However, it is guaranteed that the removal from the cluster.workers list happens before last <code>'disconnect'</code> or <code>'exit'</code> event is emitted. </p> <pre><code>// Go through all workers function eachWorker(callback) { for (var id in cluster.workers) { callback(cluster.workers[id]); } } eachWorker((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', (id) => { var worker = cluster.workers[id]; });</code></pre> <h1>Console<span><a class="mark" href="#all_console" id="all_console">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>The <code>console</code> module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. </p> <p>The module exports two specific components: </p> <ul> <li>A <code>Console</code> class with methods such as <code>console.log()</code>, <code>console.error()</code> and <code>console.warn()</code> that can be used to write to any Node.js stream.</li> <li>A global <code>console</code> instance configured to write to <code>stdout</code> and <code>stderr</code>. Because this object is global, it can be used without calling <code>require('console')</code>.</li> </ul> <p>Example using the global <code>console</code>: </p> <pre><code>console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to stderr const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr</code></pre> <p>Example using the <code>Console</code> class: </p> <pre><code>const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err</code></pre> <p>While the API for the <code>Console</code> class is designed fundamentally around the Web browser <code>console</code> object, the <code>Console</code> is Node.js is <em>not</em> intended to duplicate the browsers functionality exactly. </p> <h2>Asynchronous vs Synchronous Consoles<span><a class="mark" href="#all_asynchronous_vs_synchronous_consoles" id="all_asynchronous_vs_synchronous_consoles">#</a></span></h2> <p>The console functions are synchronous when the destination is a terminal or a file (to avoid lost messages in case of premature exit) and asynchronous when the destination is a pipe (to avoid blocking for long periods of time). </p> <p>In the following example, stdout is non-blocking while stderr is blocking: </p> <pre><code>$ node script.js 2> error.log | tee info.log</code></pre> <p>Typically, the distinction between blocking/non-blocking is not important unless an application is logging significant amounts of data. High volume logging <em>should</em> use a <code>Console</code> instance that writes to a pipe. </p> <h2>Class: Console<span><a class="mark" href="#all_class_console" id="all_class_console">#</a></span></h2> <!--type=class--> <p>The <code>Console</code> class can be used to create a simple logger with configurable output streams and can be accessed using either <code>require('console').Console</code> or <code>console.Console</code>: </p> <pre><code>const Console = require('console').Console; const Console = console.Console;</code></pre> <h3>new Console(stdout[, stderr])<span><a class="mark" href="#all_new_console_stdout_stderr" id="all_new_console_stdout_stderr">#</a></span></h3> <p>Creates a new <code>Console</code> by passing one or two writable stream instances. <code>stdout</code> is a writable stream to print log or info output. <code>stderr</code> is used for warning or error output. If <code>stderr</code> isn't passed, the warning and error output will be sent to the <code>stdout</code>. </p> <pre><code>const output = fs.createWriteStream('./stdout.log'); const errorOutput = fs.createWriteStream('./stderr.log'); // custom simple logger const logger = new Console(output, errorOutput); // use it like console var count = 5; logger.log('count: %d', count); // in stdout.log: count 5</code></pre> <p>The global <code>console</code> is a special <code>Console</code> whose output is sent to <code>process.stdout</code> and <code>process.stderr</code>. It is equivalent to calling: </p> <pre><code>new Console(process.stdout, process.stderr);</code></pre> <h3>console.assert(value[, message][, ...])<span><a class="mark" href="#all_console_assert_value_message" id="all_console_assert_value_message">#</a></span></h3> <p>A simple assertion test that verifies whether <code>value</code> is truthy. If it is not, an <code>AssertionError</code> is throw. If provided, the error <code>message</code> is formatted using <a href="util.html#util_util_format_format"><code>util.format()</code></a> and used as the error message. </p> <pre><code>console.assert(true, 'does nothing'); // OK console.assert(false, 'Whoops %s', 'didn\'t work'); // AssertionError: Whoops didn't work</code></pre> <h3>console.dir(obj[, options])<span><a class="mark" href="#all_console_dir_obj_options" id="all_console_dir_obj_options">#</a></span></h3> <p>Uses <a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a> on <code>obj</code> and prints the resulting string to stdout. This function bypasses any custom <code>inspect()</code> function defined on <code>obj</code>. An optional <code>options</code> object may be passed that alters certain aspects of the formatted string: </p> <ul> <li><p><code>showHidden</code> - if <code>true</code> then the object's non-enumerable and symbol properties will be shown too. Defaults to <code>false</code>.</p> </li> <li><p><code>depth</code> - tells <code>inspect</code> how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to <code>2</code>. To make it recurse indefinitely, pass <code>null</code>.</p> </li> <li><p><code>colors</code> - if <code>true</code>, then the output will be styled with ANSI color codes. Defaults to <code>false</code>. Colors are customizable; see [customizing <code>util.inspect()</code> colors][].</p> </li> </ul> <h3>console.error([data][, ...])<span><a class="mark" href="#all_console_error_data" id="all_console_error_data">#</a></span></h3> <p>Prints to stderr with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to <code>printf()</code> (the arguments are all passed to <a href="util.html#util_util_format_format"><code>util.format()</code></a>). </p> <pre><code>const code = 5; console.error('error #%d', code); // Prints: error #5, to stderr console.error('error', code); // Prints: error 5, to stderr</code></pre> <p>If formatting elements (e.g. <code>%d</code>) are not found in the first string then <a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a> is called on each argument and the resulting string values are concatenated. See <a href="util.html#util_util_format_format"><code>util.format()</code></a> for more information. </p> <h3>console.info([data][, ...])<span><a class="mark" href="#all_console_info_data" id="all_console_info_data">#</a></span></h3> <p>The <code>console.info()</code> function is an alias for <a href="#console_console_log_data"><code>console.log()</code></a>. </p> <h3>console.log([data][, ...])<span><a class="mark" href="#all_console_log_data" id="all_console_log_data">#</a></span></h3> <p>Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to <code>printf()</code> (the arguments are all passed to <a href="util.html#util_util_format_format"><code>util.format()</code></a>). </p> <pre><code>var count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count: ', count); // Prints: count: 5, to stdout</code></pre> <p>If formatting elements (e.g. <code>%d</code>) are not found in the first string then <a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a> is called on each argument and the resulting string values are concatenated. See <a href="util.html#util_util_format_format"><code>util.format()</code></a> for more information. </p> <h3>console.time(label)<span><a class="mark" href="#all_console_time_label" id="all_console_time_label">#</a></span></h3> <p>Used to calculate the duration of a specific operation. To start a timer, call the <code>console.time()</code> method, giving it a unique <code>label</code> as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the <a href="#console_console_timeend_label"><code>console.timeEnd()</code></a> method, again passing the timer's unique <code>label</code> as the parameter. </p> <h3>console.timeEnd(label)<span><a class="mark" href="#all_console_timeend_label" id="all_console_timeend_label">#</a></span></h3> <p>Stops a timer that was previously started by calling <a href="#console_console_time_label"><code>console.time()</code></a> and prints the result to stdout: </p> <pre><code>console.time('100-elements'); for (var i = 0; i < 100; i++) { ; } console.timeEnd('100-elements'); // prints 100-elements: 262ms</code></pre> <h3>console.trace(message[, ...])<span><a class="mark" href="#all_console_trace_message" id="all_console_trace_message">#</a></span></h3> <p>Prints to stderr the string <code>'Trace :'</code>, followed by the <a href="util.html#util_util_format_format"><code>util.format()</code></a> formatted message and stack trace to the current position in the code. </p> <pre><code>console.trace('Show me'); // Prints: (stack trace will vary based on where trace is called) // Trace: Show me // at repl:2:9 // at REPLServer.defaultEval (repl.js:248:27) // at bound (domain.js:287:14) // at REPLServer.runBound [as eval] (domain.js:300:12) // at REPLServer.<anonymous> (repl.js:412:12) // at emitOne (events.js:82:20) // at REPLServer.emit (events.js:169:7) // at REPLServer.Interface._onLine (readline.js:210:10) // at REPLServer.Interface._line (readline.js:549:8) // at REPLServer.Interface._ttyWrite (readline.js:826:14)</code></pre> <h3>console.warn([data][, ...])<span><a class="mark" href="#all_console_warn_data" id="all_console_warn_data">#</a></span></h3> <p>The <code>console.warn()</code> function is an alias for <a href="#console_console_error_data"><code>console.error()</code></a>. </p> <h1>Crypto<span><a class="mark" href="#all_crypto" id="all_crypto">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>Use <code>require('crypto')</code> to access this module. </p> <p>The crypto module 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>Class: Certificate<span><a class="mark" href="#all_class_certificate" id="all_class_certificate">#</a></span></h2> <p>The class used for working with signed public key & challenges. The most common usage for this series of functions is when dealing with the <code><keygen></code> element. <a href="https://www.openssl.org/docs/apps/spkac.html">https://www.openssl.org/docs/apps/spkac.html</a> </p> <p>Returned by <code>crypto.Certificate</code>. </p> <h3>Certificate.exportChallenge(spkac)<span><a class="mark" href="#all_certificate_exportchallenge_spkac" id="all_certificate_exportchallenge_spkac">#</a></span></h3> <p>Exports the encoded challenge associated with the SPKAC. </p> <h3>Certificate.exportPublicKey(spkac)<span><a class="mark" href="#all_certificate_exportpublickey_spkac" id="all_certificate_exportpublickey_spkac">#</a></span></h3> <p>Exports the encoded public key from the supplied SPKAC. </p> <h3>Certificate.verifySpkac(spkac)<span><a class="mark" href="#all_certificate_verifyspkac_spkac" id="all_certificate_verifyspkac_spkac">#</a></span></h3> <p>Returns true of false based on the validity of the SPKAC. </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> <p>Cipher objects are <a href="stream.html">streams</a> that are both readable and writable. The written plain text data is used to produce the encrypted data on the readable side. The legacy <code>update</code> and <code>final</code> methods are also supported. </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>. If no encoding is provided, then a buffer is returned. </p> <p>Note: <code>cipher</code> object can not be used after <code>final()</code> method has been called. </p> <h3>cipher.getAuthTag()<span><a class="mark" href="#all_cipher_getauthtag" id="all_cipher_getauthtag">#</a></span></h3> <p>For authenticated encryption modes (currently supported: GCM), this method returns a <code>Buffer</code> that represents the <em>authentication tag</em> that has been computed from the given data. Should be called after encryption has been completed using the <code>final</code> method! </p> <h3>cipher.setAAD(buffer)<span><a class="mark" href="#all_cipher_setaad_buffer" id="all_cipher_setaad_buffer">#</a></span></h3> <p>For authenticated encryption modes (currently supported: GCM), this method sets the value used for the additional authenticated data (AAD) input parameter. </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> <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>. If no encoding is provided, then a buffer is expected. If <code>data</code> is a <code>Buffer</code> then <code>input_encoding</code> is ignored. </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>. If no encoding is provided, then a buffer is returned. </p> <p>Returns the enciphered contents, and can be called many times with new data as it is streamed. </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 <a href="#crypto_crypto_createdecipher_algorithm_password"><code>crypto.createDecipher</code></a> and <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv"><code>crypto.createDecipheriv</code></a>. </p> <p>Decipher objects are <a href="stream.html">streams</a> that are both readable and writable. The written enciphered data is used to produce the plain-text data on the the readable side. The legacy <code>update</code> and <code>final</code> methods are also supported. </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>. If no encoding is provided, then a buffer is returned. </p> <p>Note: <code>decipher</code> object can not be used after <code>final()</code> method has been called. </p> <h3>decipher.setAAD(buffer)<span><a class="mark" href="#all_decipher_setaad_buffer" id="all_decipher_setaad_buffer">#</a></span></h3> <p>For authenticated encryption modes (currently supported: GCM), this method sets the value used for the additional authenticated data (AAD) input parameter. </p> <h3>decipher.setAuthTag(buffer)<span><a class="mark" href="#all_decipher_setauthtag_buffer" id="all_decipher_setauthtag_buffer">#</a></span></h3> <p>For authenticated encryption modes (currently supported: GCM), this method must be used to pass in the received <em>authentication tag</em>. If no tag is provided or if the ciphertext has been tampered with, <code>final</code> will throw, thus indicating that the ciphertext should be discarded due to failed authentication. </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. This will only work if the input data's length is a multiple of the ciphers block size. You must call this before streaming data to <a href="#crypto_decipher_update_data_input_encoding_output_encoding"><code>decipher.update</code></a>. </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>. If no encoding is provided, then a buffer is expected. If <code>data</code> is a <code>Buffer</code> then <code>input_encoding</code> is ignored. </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>. If no encoding is provided, then a buffer is returned. </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.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>. If the input encoding is not provided, then a buffer is expected. </p> <p>If no output encoding is given, then a buffer is returned. </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>. If no encoding is provided, then a buffer is returned. </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 generator in the specified encoding, which can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If no encoding is provided, then a buffer is returned. </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>. If no encoding is provided, then a buffer is returned. </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>. If no encoding is provided, then a buffer is returned. </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>. If no encoding is provided, then a buffer is returned. </p> <h3>diffieHellman.setPrivateKey(private_key[, encoding])<span><a class="mark" href="#all_diffiehellman_setprivatekey_private_key_encoding" id="all_diffiehellman_setprivatekey_private_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>. If no encoding is provided, then a buffer is expected. </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>. If no encoding is provided, then a buffer is expected. </p> <h3>diffieHellman.verifyError<span><a class="mark" href="#all_diffiehellman_verifyerror" id="all_diffiehellman_verifyerror">#</a></span></h3> <p>A bit field containing any warnings and/or errors as a result of a check performed during initialization. The following values are valid for this property (defined in <code>constants</code> module): </p> <ul> <li><code>DH_CHECK_P_NOT_SAFE_PRIME</code></li> <li><code>DH_CHECK_P_NOT_PRIME</code></li> <li><code>DH_UNABLE_TO_CHECK_GENERATOR</code></li> <li><code>DH_NOT_SUITABLE_GENERATOR</code></li> </ul> <h2>Class: ECDH<span><a class="mark" href="#all_class_ecdh" id="all_class_ecdh">#</a></span></h2> <p>The class for creating EC Diffie-Hellman key exchanges. </p> <p>Returned by <code>crypto.createECDH</code>. </p> <h3>ECDH.computeSecret(other_public_key[, input_encoding][, output_encoding])<span><a class="mark" href="#all_ecdh_computesecret_other_public_key_input_encoding_output_encoding" id="all_ecdh_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>. If the input encoding is not provided, then a buffer is expected. </p> <p>If no output encoding is given, then a buffer is returned. </p> <h3>ECDH.generateKeys([encoding[, format]])<span><a class="mark" href="#all_ecdh_generatekeys_encoding_format" id="all_ecdh_generatekeys_encoding_format">#</a></span></h3> <p>Generates private and public EC Diffie-Hellman key values, and returns the public key in the specified format and encoding. This key should be transferred to the other party. </p> <p>Format specifies point encoding and can be <code>'compressed'</code>, <code>'uncompressed'</code>, or <code>'hybrid'</code>. If no format is provided - the point will be returned in <code>'uncompressed'</code> format. </p> <p>Encoding can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If no encoding is provided, then a buffer is returned. </p> <h3>ECDH.getPrivateKey([encoding])<span><a class="mark" href="#all_ecdh_getprivatekey_encoding" id="all_ecdh_getprivatekey_encoding">#</a></span></h3> <p>Returns the EC Diffie-Hellman private key in the specified encoding, which can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If no encoding is provided, then a buffer is returned. </p> <h3>ECDH.getPublicKey([encoding[, format]])<span><a class="mark" href="#all_ecdh_getpublickey_encoding_format" id="all_ecdh_getpublickey_encoding_format">#</a></span></h3> <p>Returns the EC Diffie-Hellman public key in the specified encoding and format. </p> <p>Format specifies point encoding and can be <code>'compressed'</code>, <code>'uncompressed'</code>, or <code>'hybrid'</code>. If no format is provided - the point will be returned in <code>'uncompressed'</code> format. </p> <p>Encoding can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If no encoding is provided, then a buffer is returned. </p> <h3>ECDH.setPrivateKey(private_key[, encoding])<span><a class="mark" href="#all_ecdh_setprivatekey_private_key_encoding" id="all_ecdh_setprivatekey_private_key_encoding">#</a></span></h3> <p>Sets the EC Diffie-Hellman private key. Key encoding can be <code>'binary'</code>, <code>'hex'</code> or <code>'base64'</code>. If no encoding is provided, then a buffer is expected. </p> <p>Example (obtaining a shared secret): </p> <pre><code>const crypto = require('crypto'); const alice = crypto.createECDH('secp256k1'); const bob = crypto.createECDH('secp256k1'); alice.generateKeys(); bob.generateKeys(); const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); /* alice_secret and bob_secret should be the same */ console.log(alice_secret == bob_secret);</code></pre> <h3>ECDH.setPublicKey(public_key[, encoding])<span><a class="mark" href="#all_ecdh_setpublickey_public_key_encoding" id="all_ecdh_setpublickey_public_key_encoding">#</a></span></h3> <p>Sets the EC Diffie-Hellman public key. Key encoding can be <code>'binary'</code>, <code>'hex'</code> or <code>'base64'</code>. If no encoding is provided, then a buffer is expected. </p> <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>It is a <a href="stream.html#stream_stream">stream</a> that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the <code>read()</code> method to get the computed hash digest. The legacy <code>update</code> and <code>digest</code> methods are also supported. </p> <p>Returned by <code>crypto.createHash</code>. </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>. If no encoding is provided, then a buffer is returned. </p> <p>Note: <code>hash</code> object can not be used after <code>digest()</code> method has been called. </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>. If no encoding is provided, and the input is a string, an encoding of <code>'binary'</code> is enforced. If <code>data</code> is a <code>Buffer</code> then <code>input_encoding</code> is ignored. </p> <p>This can be called many times with new data as it is streamed. </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.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>. If no encoding is provided, then a buffer is returned. </p> <p>Note: <code>hmac</code> object can not be used after <code>digest()</code> method has been called. </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> <h2>Class: Sign<span><a class="mark" href="#all_class_sign" id="all_class_sign">#</a></span></h2> <p>Class for generating signatures. </p> <p>Returned by <code>crypto.createSign</code>. </p> <p>Sign objects are writable <a href="stream.html">streams</a>. The written data is used to generate the signature. Once all of the data has been written, the <code>sign</code> method will return the signature. The legacy <code>update</code> method is also supported. </p> <h3>sign.sign(private_key[, output_format])<span><a class="mark" href="#all_sign_sign_private_key_output_format" id="all_sign_sign_private_key_output_format">#</a></span></h3> <p>Calculates the signature on all the updated data passed through the sign. </p> <p><code>private_key</code> can be an object or a string. If <code>private_key</code> is a string, it is treated as the key with no passphrase. </p> <p><code>private_key</code>: </p> <ul> <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</li> </ul> <p>Returns the signature in <code>output_format</code> which can be <code>'binary'</code>, <code>'hex'</code> or <code>'base64'</code>. If no encoding is provided, then a buffer is returned. </p> <p>Note: <code>sign</code> object can not be used after <code>sign()</code> method has been called. </p> <h3>sign.update(data)<span><a class="mark" href="#all_sign_update_data" id="all_sign_update_data">#</a></span></h3> <p>Updates the sign object with data. This can be called many times with new data as it is streamed. </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> <p>Verify objects are writable <a href="stream.html">streams</a>. The written data is used to validate against the supplied signature. Once all of the data has been written, the <code>verify</code> method will return true if the supplied signature is valid. The legacy <code>update</code> method is also supported. </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>. If no encoding is specified, then a buffer is expected. </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 has been called. </p> <h2>crypto.DEFAULT_ENCODING<span><a class="mark" href="#all_crypto_default_encoding" id="all_crypto_default_encoding">#</a></span></h2> <p>The default encoding to use for functions that can take either strings or buffers. The default value is <code>'buffer'</code>, which makes it default to using Buffer objects. This is here to make the crypto module more easily compatible with legacy programs that expected <code>'binary'</code> to be the default encoding. </p> <p>Note that new programs will probably expect buffers, so only use this as a temporary measure. </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> <p>It is a <a href="stream.html#stream_stream">stream</a> that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the <code>read()</code> method to get the enciphered contents. The legacy <code>update</code> and <code>final</code> methods are also supported. </p> <p>Note: <code>createCipher</code> derives keys with the OpenSSL function <a href="https://www.openssl.org/docs/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> with the digest algorithm set to MD5, one iteration, and no salt. The lack of salt allows dictionary attacks as the same password always creates the same key. The low iteration count and non-cryptographically secure hash algorithm allow passwords to be tested very rapidly. </p> <p>In line with OpenSSL's recommendation to use pbkdf2 instead of <a href="https://www.openssl.org/docs/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended you derive a key and iv yourself with <a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2</code></a> and to then use <a href="#crypto_crypto_createcipheriv_algorithm_key_iv"><code>createCipheriv()</code></a> to create the cipher stream. </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="https://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>crypto.createCredentials(details)<span><a class="mark" href="#all_crypto_createcredentials_details" id="all_crypto_createcredentials_details">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <a href="tls.html#tls_tls_createsecurecontext_details"><code>tls.createSecureContext</code></a> instead.</pre><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="https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">https://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.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"><code>createCipher()</code></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"><code>createCipheriv()</code></a> above. </p> <h2>crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])<span><a class="mark" href="#all_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding" id="all_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding">#</a></span></h2> <p>Creates a Diffie-Hellman key exchange object using the supplied <code>prime</code> and an optional specific <code>generator</code>. <code>generator</code> can be a number, string, or Buffer. If no <code>generator</code> is specified, then <code>2</code> is used. <code>prime_encoding</code> and <code>generator_encoding</code> can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If no <code>prime_encoding</code> is specified, then a Buffer is expected for <code>prime</code>. If no <code>generator_encoding</code> is specified, then a Buffer is expected for <code>generator</code>. </p> <h2>crypto.createDiffieHellman(prime_length[, generator])<span><a class="mark" href="#all_crypto_creatediffiehellman_prime_length_generator" id="all_crypto_creatediffiehellman_prime_length_generator">#</a></span></h2> <p>Creates a Diffie-Hellman key exchange object and generates a prime of <code>prime_length</code> bits and using an optional specific numeric <code>generator</code>. If no <code>generator</code> is specified, then <code>2</code> is used. </p> <h2>crypto.createECDH(curve_name)<span><a class="mark" href="#all_crypto_createecdh_curve_name" id="all_crypto_createecdh_curve_name">#</a></span></h2> <p>Creates an Elliptic Curve (EC) Diffie-Hellman key exchange object using a predefined curve specified by the <code>curve_name</code> string. Use <a href="#crypto_crypto_getcurves"><code>getCurves()</code></a> to obtain a list of available curve names. On recent releases, <code>openssl ecparam -list_curves</code> will also display the name and description of each available elliptic curve. </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>'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 sha256 sum of a file </p> <pre><code>const filename = process.argv[2]; const crypto = require('crypto'); const fs = require('fs'); const shasum = crypto.createHash('sha256'); const s = fs.ReadStream(filename); s.on('data', (d) => { shasum.update(d); }); s.on('end', () => { var d = shasum.digest('hex'); console.log(`${d} ${filename}`); });</code></pre> <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>It is a <a href="stream.html#stream_stream">stream</a> that is both readable and writable. The written data is used to compute the hmac. Once the writable side of the stream is ended, use the <code>read()</code> method to get the computed digest. The legacy <code>update</code> and <code>digest</code> methods are also supported. </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>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>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>crypto.getCiphers()<span><a class="mark" href="#all_crypto_getciphers" id="all_crypto_getciphers">#</a></span></h2> <p>Returns an array with the names of the supported ciphers. </p> <p>Example: </p> <pre><code>const ciphers = crypto.getCiphers(); console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]</code></pre> <h2>crypto.getCurves()<span><a class="mark" href="#all_crypto_getcurves" id="all_crypto_getcurves">#</a></span></h2> <p>Returns an array with the names of the supported elliptic curves. </p> <p>Example: </p> <pre><code>const curves = crypto.getCurves(); console.log(curves); // ['secp256k1', 'secp384r1', ...]</code></pre> <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="https://www.rfc-editor.org/rfc/rfc2412.txt">RFC 2412</a>, but see <a href="#crypto_caveats">Caveats</a>) and <code>'modp14'</code>, <code>'modp15'</code>, <code>'modp16'</code>, <code>'modp17'</code>, <code>'modp18'</code> (defined in <a href="https://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_prime_encoding_generator_generator_encoding"><code>crypto.createDiffieHellman()</code></a> above, but will not allow changing the keys (with <a href="#crypto_diffiehellman_setpublickey_public_key_encoding"><code>diffieHellman.setPublicKey()</code></a> for example). The advantage of using this routine is that the parties do not have to generate nor exchange group modulus beforehand, saving both processor and communication time. </p> <p>Example (obtaining a shared secret): </p> <pre><code>const crypto = require('crypto'); const alice = crypto.getDiffieHellman('modp14'); const bob = crypto.getDiffieHellman('modp14'); alice.generateKeys(); bob.generateKeys(); const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); /* alice_secret and bob_secret should be the same */ console.log(alice_secret == bob_secret);</code></pre> <h2>crypto.getHashes()<span><a class="mark" href="#all_crypto_gethashes" id="all_crypto_gethashes">#</a></span></h2> <p>Returns an array with the names of the supported hash algorithms. </p> <p>Example: </p> <pre><code>const hashes = crypto.getHashes(); console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]</code></pre> <h2>crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)<span><a class="mark" href="#all_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback" id="all_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback">#</a></span></h2> <p>Asynchronous PBKDF2 function. Applies the selected HMAC digest function (default: SHA1) to derive a key of the requested byte length from the password, salt and number of iterations. The callback gets two arguments: <code>(err, derivedKey)</code>. </p> <p>The number of iterations passed to pbkdf2 should be as high as possible, the higher the number, the more secure it will be, but will take a longer amount of time to complete. </p> <p>Chosen salts should also be unique. It is recommended that the salts are random and their length is greater than 16 bytes. See <a href="http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf">NIST SP 800-132</a> for details. </p> <p>Example: </p> <pre><code>crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', function(err, key) { if (err) throw err; console.log(key.toString('hex')); // 'c5e478d...1469e50' });</code></pre> <p>You can get a list of supported digest functions with <a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a>. </p> <h2>crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])<span><a class="mark" href="#all_crypto_pbkdf2sync_password_salt_iterations_keylen_digest" id="all_crypto_pbkdf2sync_password_salt_iterations_keylen_digest">#</a></span></h2> <p>Synchronous PBKDF2 function. Returns derivedKey or throws error. </p> <h2>crypto.privateDecrypt(private_key, buffer)<span><a class="mark" href="#all_crypto_privatedecrypt_private_key_buffer" id="all_crypto_privatedecrypt_private_key_buffer">#</a></span></h2> <p>Decrypts <code>buffer</code> with <code>private_key</code>. </p> <p><code>private_key</code> can be an object or a string. If <code>private_key</code> is a string, it is treated as the key with no passphrase and will use <code>RSA_PKCS1_OAEP_PADDING</code>. </p> <p><code>private_key</code>: </p> <ul> <li><code>key</code> : A string holding the PEM encoded private key</li> <li><code>passphrase</code> : An optional string of passphrase for the private key</li> <li><code>padding</code> : An optional padding value, one of the following:<ul> <li><code>constants.RSA_NO_PADDING</code></li> <li><code>constants.RSA_PKCS1_PADDING</code></li> <li><code>constants.RSA_PKCS1_OAEP_PADDING</code></li> </ul> </li> </ul> <p>NOTE: All paddings are defined in <code>constants</code> module. </p> <h2>crypto.privateEncrypt(private_key, buffer)<span><a class="mark" href="#all_crypto_privateencrypt_private_key_buffer" id="all_crypto_privateencrypt_private_key_buffer">#</a></span></h2> <p>See above for details. Has the same API as <code>crypto.privateDecrypt</code>. Default padding is <code>RSA_PKCS1_PADDING</code>. </p> <h2>crypto.publicDecrypt(public_key, buffer)<span><a class="mark" href="#all_crypto_publicdecrypt_public_key_buffer" id="all_crypto_publicdecrypt_public_key_buffer">#</a></span></h2> <p>See above for details. Has the same API as <code>crypto.publicEncrypt</code>. Default padding is <code>RSA_PKCS1_PADDING</code>. </p> <h2>crypto.publicEncrypt(public_key, buffer)<span><a class="mark" href="#all_crypto_publicencrypt_public_key_buffer" id="all_crypto_publicencrypt_public_key_buffer">#</a></span></h2> <p>Encrypts <code>buffer</code> with <code>public_key</code>. Only RSA is currently supported. </p> <p><code>public_key</code> can be an object or a string. If <code>public_key</code> is a string, it is treated as the key with no passphrase and will use <code>RSA_PKCS1_OAEP_PADDING</code>. Since RSA public keys may be derived from private keys you may pass a private key to this method. </p> <p><code>public_key</code>: </p> <ul> <li><code>key</code> : A string holding the PEM encoded private key</li> <li><code>passphrase</code> : An optional string of passphrase for the private key</li> <li><code>padding</code> : An optional padding value, one of the following:<ul> <li><code>constants.RSA_NO_PADDING</code></li> <li><code>constants.RSA_PKCS1_PADDING</code></li> <li><code>constants.RSA_PKCS1_OAEP_PADDING</code></li> </ul> </li> </ul> <p>NOTE: All paddings are defined in <code>constants</code> module. </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, (ex, buf) => { if (ex) throw ex; console.log('Have %d bytes of random data: %s', buf.length, buf); }); // sync const buf = crypto.randomBytes(256); console.log('Have %d bytes of random data: %s', buf.length, buf);</code></pre> <p>NOTE: This will block if there is insufficient entropy, although it should normally never take longer than a few milliseconds. The only time when this may conceivably block is right after boot, when the whole system is still low on entropy. </p> <h2>crypto.setEngine(engine[, flags])<span><a class="mark" href="#all_crypto_setengine_engine_flags" id="all_crypto_setengine_engine_flags">#</a></span></h2> <p>Load and set engine for some/all OpenSSL functions (selected by flags). </p> <p><code>engine</code> could be either an id or a path to the engine's shared library. </p> <p><code>flags</code> is optional and has <code>ENGINE_METHOD_ALL</code> value by default. It could take one of or mix of following flags (defined in <code>constants</code> module): </p> <ul> <li><code>ENGINE_METHOD_RSA</code></li> <li><code>ENGINE_METHOD_DSA</code></li> <li><code>ENGINE_METHOD_DH</code></li> <li><code>ENGINE_METHOD_RAND</code></li> <li><code>ENGINE_METHOD_ECDH</code></li> <li><code>ENGINE_METHOD_ECDSA</code></li> <li><code>ENGINE_METHOD_CIPHERS</code></li> <li><code>ENGINE_METHOD_DIGESTS</code></li> <li><code>ENGINE_METHOD_STORE</code></li> <li><code>ENGINE_METHOD_PKEY_METH</code></li> <li><code>ENGINE_METHOD_PKEY_ASN1_METH</code></li> <li><code>ENGINE_METHOD_ALL</code></li> <li><code>ENGINE_METHOD_NONE</code></li> </ul> <h2>Recent API Changes<span><a class="mark" href="#all_recent_api_changes" id="all_recent_api_changes">#</a></span></h2> <p>The Crypto module was added to Node.js 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.js classes, and many methods accepted and returned Binary-encoded strings by default rather than Buffers. This was changed to use Buffers by default instead. </p> <p>This is 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 once got a binary string and then presented the binary string to the Verify object, you'll now get a Buffer, and present the Buffer to the Verify object. </p> <p>However, if you were 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. To switch to the previous style of using binary strings by default, set the <code>crypto.DEFAULT_ENCODING</code> field to 'binary'. Note that new programs will probably expect buffers, so only use this as a temporary measure. </p> <h2>Caveats<span><a class="mark" href="#all_caveats" id="all_caveats">#</a></span></h2> <p>The crypto module still supports some algorithms which are already compromised. And the API also allows the use of ciphers and hashes with a small key size that are considered to be too weak for safe use. </p> <p>Users should take full responsibility for selecting the crypto algorithm and key size according to their security requirements. </p> <p>Based on the recommendations of <a href="http://csrc.nist.gov/publications/nistpubs/800-131A/sp800-131A.pdf">NIST SP 800-131A</a>: </p> <ul> <li>MD5 and SHA-1 are no longer acceptable where collision resistance is required such as digital signatures.</li> <li>The key used with RSA, DSA and DH algorithms is recommended to have at least 2048 bits and that of the curve of ECDSA and ECDH at least 224 bits, to be safe to use for several years.</li> <li>The DH groups of <code>modp1</code>, <code>modp2</code> and <code>modp5</code> have a key size smaller than 2048 bits and are not recommended.</li> </ul> <p>See the reference for other recommendations and details. </p> <h1>Debugger<span><a class="mark" href="#all_debugger" id="all_debugger">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><!-- type=misc --> <p>Node.js includes a full-featured out-of-process debugging utility accessible via a simple <a href="https://github.com/v8/v8/wiki/Debugging-Protocol">TCP-based protocol</a> and built-in debugging client. To use it, start Node.js with the <code>debug</code> argument followed by the path to the script to debug; a prompt will be displayed indicating successful launch of the debugger: </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.js's debugger client does not yet support the full range of commands, but simple step and inspection are possible. </p> <p>Inserting the statement <code>debugger;</code> into the source code of a script will enable a breakpoint at that position in the code. </p> <p>For example, suppose <code>myscript.js</code> is written as: </p> <pre><code>// myscript.js x = 5; setTimeout(function () { debugger; console.log('world'); }, 1000); console.log('hello');</code></pre> <p>Once the debugger is run, a breakpoint will occur at 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 code to be evaluated remotely. The <code>next</code> command steps over to the next line. Type <code>help</code> to see what other commands are available. </p> <h2>Watchers<span><a class="mark" href="#all_watchers" id="all_watchers">#</a></span></h2> <p>It is possible to watch expression and variable values while debugging. On every breakpoint, each expression from the watchers list will be evaluated in the current context and displayed immediately before the breakpoint's source code listing. </p> <p>To begin watching an expression, type <code>watch('my_expression')</code>. The command <code>watchers</code> will print 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('script.js', 1)</code>, <code>cb(...)</code> - Clear breakpoint in script.js on line 1</li> </div></ul> <p>It is also possible to set a breakpoint in a file (module) that isn't loaded yet: </p> <pre><code>% ./node debug test/fixtures/break-in-module/main.js < debugger listening on port 5858 connecting to port 5858... ok break in test/fixtures/break-in-module/main.js:1 1 var mod = require('./mod.js'); 2 mod.hello(); 3 mod.hello(); debug> setBreakpoint('mod.js', 23) Warning: script 'mod.js' was not loaded yet. 1 var mod = require('./mod.js'); 2 mod.hello(); 3 mod.hello(); debug> c break in test/fixtures/break-in-module/mod.js:23 21 22 exports.hello = function() { 23 return 'hello from module'; 24 }; 25 debug></code></pre> <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>An alternative way of enabling and accessing the debugger is to start Node.js with the <code>--debug</code> command-line flag or by signaling an existing Node.js process with <code>SIGUSR1</code>. </p> <p>Once a process has been set in debug mode this way, it can be connected to using the Node.js debugger by either connecting to the <code>pid</code> of the running process or via URI reference to the listening debugger: </p> <ul> <li><code>node debug -p <pid></code> - Connects to the process via the <code>pid</code></li> <li><code>node debug <URI></code> - Connects to the process via the URI such as localhost:5858</li> </ul> <h1>UDP / Datagram Sockets<span><a class="mark" href="#all_udp_datagram_sockets" id="all_udp_datagram_sockets">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><!-- name=dgram --> <p>The <code>dgram</code> module provides an implementation of UDP Datagram sockets. </p> <pre><code>const dgram = require('dgram'); const server = dgram.createSocket('udp4'); server.on('error', (err) => { console.log(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { var address = server.address(); console.log(`server listening ${address.address}:${address.port}`); }); server.bind(41234); // server listening 0.0.0.0:41234</code></pre> <h2>Class: dgram.Socket<span><a class="mark" href="#all_class_dgram_socket" id="all_class_dgram_socket">#</a></span></h2> <p>The <code>dgram.Socket</code> object is an <a href="events.html#events_class_events_eventemitter"><code>EventEmitter</code></a> that encapsulates the datagram functionality. </p> <p>New instances of <code>dgram.Socket</code> are created using <a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket()</code></a>. The <code>new</code> keyword is not to be used to create <code>dgram.Socket</code> instances. </p> <h3>Event: 'close'<span><a class="mark" href="#all_event_close_1" id="all_event_close_1">#</a></span></h3> <p>The <code>'close'</code> event is emitted after a socket is closed with <a href="#dgram_socket_close_callback"><code>close()</code></a>. Once triggered, no new <code>'message'</code> events will be emitted on this socket. </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>exception</code> Error object</li> </div></ul> <p>The <code>'error'</code> event is emitted whenever any error occurs. The event handler function is passed a single Error object. </p> <h3>Event: 'listening'<span><a class="mark" href="#all_event_listening_2" id="all_event_listening_2">#</a></span></h3> <p>The <code>'listening'</code> event is emitted whenever a socket begins listening for datagram messages. This occurs as soon as UDP sockets are created. </p> <h3>Event: 'message'<span><a class="mark" href="#all_event_message_3" id="all_event_message_3">#</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>The <code>'message'</code> event is emitted when a new datagram is available on a socket. The event handler function is passed two arguments: <code>msg</code> and <code>rinfo</code>. The <code>msg</code> argument is a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> and <code>rinfo</code> is an object with the sender's address information provided by the <code>address</code>, <code>family</code> and <code>port</code> properties: </p> <pre><code>socket.on('message', (msg, rinfo) => { console.log('Received %d bytes from %s:%d\n', msg.length, rinfo.address, rinfo.port); });</code></pre> <h3>socket.addMembership(multicastAddress[, multicastInterface])<span><a class="mark" href="#all_socket_addmembership_multicastaddress_multicastinterface" id="all_socket_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 at the given <code>multicastAddress</code> using the <code>IP_ADD_MEMBERSHIP</code> socket option. If the <code>multicastInterface</code> argument is not specified, the operating system will try to add membership to all valid networking interfaces. </p> <h3>socket.address()<span><a class="mark" href="#all_socket_address" id="all_socket_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> properties. </p> <h3>[socket.bind([port][, address][, callback])]<span><a class="mark" href="#all_socket_bind_port_address_callback" id="all_socket_bind_port_address_callback">#</a></span></h3> <div class="signature"><ul> <li><code>port</code> Integer, Optional</li> <li><code>address</code> String, Optional</li> <li><code>callback</code> Function with no parameters, Optional. Called when binding is complete.</li> </div></ul> <p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram messages on a named <code>port</code> and optional <code>address</code>. If <code>port</code> is not specified, the operating system will attempt to bind to a random port. If <code>address</code> is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a <code>'listening'</code> event is emitted and the optional <code>callback</code> function is called. </p> <p>Note that specifying both a <code>'listening'</code> event listener and passing a <code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very useful. </p> <p>A bound datagram socket keeps the Node.js process running to receive datagram messages. </p> <p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g. attempting to bind with a closed socket), an <a href="errors.html#errors_class_error"><code>Error</code></a> may be thrown. </p> <p>Example of a UDP server listening on port 41234: </p> <pre><code>const dgram = require('dgram'); const server = dgram.createSocket('udp4'); server.on('error', (err) => { console.log(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { 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>socket.bind(options[, callback])<span><a class="mark" href="#all_socket_bind_options_callback" id="all_socket_bind_options_callback">#</a></span></h3> <div class="signature"><ul> <li><code>options</code> <span class="type">Object</span> - Required. Supports the following properties:<ul> <li><code>port</code> <span class="type">Number</span> - Required.</li> <li><code>address</code> <span class="type">String</span> - Optional.</li> <li><code>exclusive</code> <span class="type">Boolean</span> - Optional.</li> </ul> </li> <li><code>callback</code> <span class="type">Function</span> - Optional.</li> </div></ul> <p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram messages on a named <code>port</code> and optional <code>address</code> that are passed as properties of an <code>options</code> object passed as the first argument. If <code>port</code> is not specified, the operating system will attempt to bind to a random port. If <code>address</code> is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a <code>'listening'</code> event is emitted and the optional <code>callback</code> function is called. </p> <p>The <code>options</code> object may contain an additional <code>exclusive</code> property that is use when using <code>dgram.Socket</code> objects with the [<code>cluster</code>] module. When <code>exclusive</code> is set to <code>false</code> (the default), cluster workers will use the same underlying socket handle allowing connection handling duties to be shared. When <code>exclusive</code> is <code>true</code>, however, the handle is not shared and attempted port sharing results in an error. </p> <p>An example socket listening on an exclusive port is shown below. </p> <pre><code>socket.bind({ address: 'localhost', port: 8000, exclusive: true });</code></pre> <h3>socket.close([callback])<span><a class="mark" href="#all_socket_close_callback" id="all_socket_close_callback">#</a></span></h3> <p>Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the <a href="#net_event_close"><code>'close'</code></a> event. </p> <h3>socket.dropMembership(multicastAddress[, multicastInterface])<span><a class="mark" href="#all_socket_dropmembership_multicastaddress_multicastinterface" id="all_socket_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>Instructs the kernel to leave a multicast group at <code>multicastAddress</code> using the <code>IP_DROP_MEMBERSHIP</code> socket option. This method is automatically called by the kernel when the socket is closed or the process terminates, so most apps will never have reason to call this. </p> <p>If <code>multicastInterface</code> is not specified, the operating system will attempt to drop membership on all valid interfaces. </p> <h3>socket.send(buf, offset, length, port, address[, callback])<span><a class="mark" href="#all_socket_send_buf_offset_length_port_address_callback" id="all_socket_send_buf_offset_length_port_address_callback">#</a></span></h3> <div class="signature"><ul> <li><code>buf</code> Buffer object or string. 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 hostname or IP address.</li> <li><code>callback</code> Function. Called when the message has been sent. Optional.</li> </div></ul> <p>Broadcasts a datagram on the socket. The destination <code>port</code> and <code>address</code> must be specified. </p> <p>The <code>buf</code> argument is a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> object containing the message. The <code>offset</code> and <code>length</code> specify the offset within the <code>Buffer</code> where the message begins and the number of bytes in the message, respectively. With messages that contain multi-byte characters, <code>offset</code> and <code>length</code> will be calculated with respect to <a href="buffer.html#buffer_class_method_buffer_bytelength_string_encoding">byte length</a> and not the character position. </p> <p>The <code>address</code> argument is a string. If the value of <code>address</code> is a host name, DNS will be used to resolve the address of the host. If the <code>address</code> is not specified or is an empty string, <code>'0.0.0.0'</code> or <code>'::0'</code> will be used instead. It is possible, depending on the network configuration, that these defaults may not work; accordingly, it is best to be explicit about the destination address. </p> <p>If the socket has not been previously bound with a call to <code>bind</code>, the socket is assigned a random port number and is bound to the "all interfaces" address (<code>'0.0.0.0'</code> for <code>udp4</code> sockets, <code>'::0'</code> for <code>udp6</code> sockets.) </p> <p>An optional <code>callback</code> function may be specified to as a way of reporting DNS errors or for determining when it is safe to reuse the <code>buf</code> object. Note that DNS lookups delay the time to send for at least one tick of the Node.js event loop. </p> <p>The only way to know for sure that the datagram has been sent is by using a <code>callback</code>. If an error occurs and a <code>callback</code> is given, the error will be passed as the first argument to the <code>callback</code>. If a <code>callback</code> is not given, the error is emitted as an <code>'error'</code> event on the <code>socket</code> object. </p> <p>Example of sending a UDP packet to a random port on <code>localhost</code>; </p> <pre><code>const dgram = require('dgram'); const message = new Buffer('Some bytes'); const client = dgram.createSocket('udp4'); client.send(message, 0, message.length, 41234, 'localhost', (err) => { 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 exceed 64K octets <em>including</em> the 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 datagram messages 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 datagram messages. 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, like Ethernet, have a minimum <code>MTU</code> of <code>1500</code>.</p> </li> </ul> <p>It is impossible to know in advance the MTU of each link through which a packet might travel. Sending a datagram greater than the receiver <code>MTU</code> will not work because the packet will get silently dropped without informing the source that the data did not reach its intended recipient. </p> <h3>socket.setBroadcast(flag)<span><a class="mark" href="#all_socket_setbroadcast_flag" id="all_socket_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 set to <code>true</code>, UDP packets may be sent to a local interface's broadcast address. </p> <h3>socket.setMulticastLoopback(flag)<span><a class="mark" href="#all_socket_setmulticastloopback_flag" id="all_socket_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 set to <code>true</code>, multicast packets will also be received on the local interface. </p> <h3>socket.setMulticastTTL(ttl)<span><a class="mark" href="#all_socket_setmulticastttl_ttl" id="all_socket_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. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to travel 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 passed to to <code>socket.setMulticastTTL()</code> is a number of hops between 0 and 255. The default on most systems is <code>1</code> but can vary. </p> <h3>socket.setTTL(ttl)<span><a class="mark" href="#all_socket_setttl_ttl" id="all_socket_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. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to travel 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>socket.setTTL()</code> is a number of hops between 1 and 255. The default on most systems is 64 but can vary. </p> <h3>socket.ref()<span><a class="mark" href="#all_socket_ref" id="all_socket_ref">#</a></span></h3> <p>By default, binding a socket will cause it to block the Node.js process from exiting as long as the socket is open. The <code>socket.unref()</code> method can be used to exclude the socket from the reference counting that keeps the Node.js process active. The <code>socket.ref()</code> method adds the socket back to the reference counting and restores the default behavior. </p> <p>Calling <code>socket.ref()</code> multiples times will have no additional effect. </p> <p>The <code>socket.ref()</code> method returns a reference to the socket so calls can be chained. </p> <h3>socket.unref()<span><a class="mark" href="#all_socket_unref" id="all_socket_unref">#</a></span></h3> <p>By default, binding a socket will cause it to block the Node.js process from exiting as long as the socket is open. The <code>socket.unref()</code> method can be used to exclude the socket from the reference counting that keeps the Node.js process active, allowing the process to exit even if the socket is still listening. </p> <p>Calling <code>socket.unref()</code> multiple times will have no addition effect. </p> <p>The <code>socket.unref()</code> method returns a reference to the socket so calls can be chained. </p> <h3>Change to asynchronous <code>socket.bind()</code> behavior<span><a class="mark" href="#all_change_to_asynchronous_socket_bind_behavior" id="all_change_to_asynchronous_socket_bind_behavior">#</a></span></h3> <p>As of Node.js v0.10, <a href="#dgram_socket_bind_options_callback"><code>dgram.Socket#bind()</code></a> changed to an asynchronous execution model. Legacy code that assumes synchronous behavior, as in the following example: </p> <pre><code>const s = dgram.createSocket('udp4'); s.bind(1234); s.addMembership('224.0.0.114');</code></pre> <p>Must be changed to pass a callback function to the <a href="#dgram_socket_bind_options_callback"><code>dgram.Socket#bind()</code></a> function: </p> <pre><code>const s = dgram.createSocket('udp4'); s.bind(1234, () => { s.addMembership('224.0.0.114'); });</code></pre> <h2><code>dgram</code> module functions<span><a class="mark" href="#all_dgram_module_functions" id="all_dgram_module_functions">#</a></span></h2> <h3>dgram.createSocket(options[, callback])<span><a class="mark" href="#all_dgram_createsocket_options_callback" id="all_dgram_createsocket_options_callback">#</a></span></h3> <ul> <li><code>options</code> Object</li> <li><code>callback</code> Function. Attached as a listener to <code>'message'</code> events.</li> <li>Returns: Socket object</li> </ul> <p>Creates a <code>dgram.Socket</code> object. The <code>options</code> argument is an object that should contain a <code>type</code> field of either <code>udp4</code> or <code>udp6</code> and an optional boolean <code>reuseAddr</code> field. </p> <p>When <code>reuseAddr</code> is <code>true</code> <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will reuse the address, even if another process has already bound a socket on it. <code>reuseAddr</code> defaults to <code>false</code>. An optional <code>callback</code> function can be passed specified which is added as a listener for <code>'message'</code> events. </p> <p>Once the socket is created, calling <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will instruct the socket to begin listening for datagram messages. When <code>address</code> and <code>port</code> are not passed to <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> the method will bind the socket to the "all interfaces" address on a random port (it does the right thing for both <code>udp4</code> and <code>udp6</code> sockets). The bound address and port can be retrieved using <a href="#dgram_socket_address"><code>socket.address().address</code></a> and <a href="#dgram_socket_address"><code>socket.address().port</code></a>. </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 <code>dgram.Socket</code> object of the specified <code>type</code>. The <code>type</code> argument can be either <code>udp4</code> or <code>udp6</code>. An optional <code>callback</code> function can be passed which is added as a listener for <code>'message'</code> events. </p> <p>Once the socket is created, calling <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will instruct the socket to begin listening for datagram messages. When <code>address</code> and <code>port</code> are not passed to <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> the method will bind the socket to the "all interfaces" address on a random port (it does the right thing for both <code>udp4</code> and <code>udp6</code> sockets). The bound address and port can be retrieved using <a href="#dgram_socket_address"><code>socket.address().address</code></a> and <a href="#dgram_socket_address"><code>socket.address().port</code></a>. </p> <h1>DNS<span><a class="mark" href="#all_dns" id="all_dns">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>The <code>dns</code> module contains functions belonging to two different categories: </p> <p>1) Functions that use the underlying operating system facilities to perform name resolution, and that do not necessarily perform any network communication. This category contains only one function: <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. <strong>Developers looking to perform name resolution in the same way that other applications on the same operating system behave should use <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</strong> </p> <p>For example, looking up <code>nodejs.org</code>. </p> <pre><code>const dns = require('dns'); dns.lookup('nodejs.org', (err, addresses, family) => { console.log('addresses:', addresses); });</code></pre> <p>2) Functions that connect to an actual DNS server to perform name resolution, and that <em>always</em> use the network to perform DNS queries. This category contains all functions in the <code>dns</code> module <em>except</em> <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. These functions do not use the same set of configuration files used by <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> (e.g. <code>/etc/hosts</code>). These functions should be used by developers who do not want to use the underlying operating system's facilities for name resolution, and instead want to <em>always</em> perform DNS queries. </p> <p>Below is an example that resolves <code>'nodejs.org'</code> then reverse resolves the IP addresses that are returned. </p> <pre><code>const dns = require('dns'); dns.resolve4('nodejs.org', (err, addresses) => { if (err) throw err; console.log(`addresses: ${JSON.stringify(addresses)}`); addresses.forEach((a) => { dns.reverse(a, (err, hostnames) => { if (err) { throw err; } console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); }); }); });</code></pre> <p>There are subtle consequences in choosing one over the other, please consult the <a href="#dns_implementation_considerations">Implementation considerations section</a> for more information. </p> <h2>dns.getServers()<span><a class="mark" href="#all_dns_getservers" id="all_dns_getservers">#</a></span></h2> <p>Returns an array of IP address strings that are being used for name resolution. </p> <h2>dns.lookup(hostname[, options], callback)<span><a class="mark" href="#all_dns_lookup_hostname_options_callback" id="all_dns_lookup_hostname_options_callback">#</a></span></h2> <p>Resolves a hostname (e.g. <code>'nodejs.org'</code>) into the first found A (IPv4) or AAAA (IPv6) record. <code>options</code> can be an object or integer. If <code>options</code> is not provided, then IPv4 and IPv6 addresses are both valid. If <code>options</code> is an integer, then it must be <code>4</code> or <code>6</code>. </p> <p>Alternatively, <code>options</code> can be an object containing these properties: </p> <ul> <li><code>family</code> {Number} - The record family. If present, must be the integer <code>4</code> or <code>6</code>. If not provided, both IP v4 and v6 addresses are accepted.</li> <li><code>hints</code>: {Number} - If present, it should be one or more of the supported <code>getaddrinfo</code> flags. If <code>hints</code> is not provided, then no flags are passed to <code>getaddrinfo</code>. Multiple flags can be passed through <code>hints</code> by logically <code>OR</code>ing their values. See <a href="#dns_supported_getaddrinfo_flags">supported <code>getaddrinfo</code> flags</a> below for more information on supported flags.</li> <li><code>all</code>: {Boolean} - When <code>true</code>, the callback returns all resolved addresses in an array, otherwise returns a single address. Defaults to <code>false</code>.</li> </ul> <p>All properties are optional. An example usage of options is shown below. </p> <pre><code>{ family: 4, hints: dns.ADDRCONFIG | dns.V4MAPPED, all: false }</code></pre> <p>The <code>callback</code> function has arguments <code>(err, address, family)</code>. <code>address</code> is a string representation of an IPv4 or IPv6 address. <code>family</code> is either the integer <code>4</code> or <code>6</code> and denotes the family of <code>address</code> (not necessarily the value initially passed to <code>lookup</code>). </p> <p>With the <code>all</code> option set to <code>true</code>, the arguments change to <code>(err, addresses)</code>, with <code>addresses</code> being an array of objects with the properties <code>address</code> and <code>family</code>. </p> <p>On error, <code>err</code> is an <a href="errors.html#errors_class_error"><code>Error</code></a> 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 hostname does not exist but also when the lookup fails in other ways such as no available file descriptors. </p> <p><code>dns.lookup()</code> does not necessarily have anything to do with the DNS protocol. The implementation uses an operating system facility that can associate names with addresses, and vice versa. This implementation can have subtle but important consequences on the behavior of any Node.js program. Please take some time to consult the <a href="#dns_implementation_considerations">Implementation considerations section</a> before using <code>dns.lookup()</code>. </p> <h3>Supported getaddrinfo flags<span><a class="mark" href="#all_supported_getaddrinfo_flags" id="all_supported_getaddrinfo_flags">#</a></span></h3> <p>The following flags can be passed as hints to <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. </p> <ul> <li><code>dns.ADDRCONFIG</code>: Returned address types are determined by the types of addresses supported by the current system. For example, IPv4 addresses are only returned if the current system has at least one IPv4 address configured. Loopback addresses are not considered.</li> <li><code>dns.V4MAPPED</code>: If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. Note that it is not supported on some operating systems (e.g FreeBSD 10.1).</li> </ul> <h2>dns.lookupService(address, port, callback)<span><a class="mark" href="#all_dns_lookupservice_address_port_callback" id="all_dns_lookupservice_address_port_callback">#</a></span></h2> <p>Resolves the given <code>address</code> and <code>port</code> into a hostname and service using the operating system's underlying <code>getnameinfo</code> implementation. </p> <p>The callback has arguments <code>(err, hostname, service)</code>. The <code>hostname</code> and <code>service</code> arguments are strings (e.g. <code>'localhost'</code> and <code>'http'</code> respectively). </p> <p>On error, <code>err</code> is an <a href="errors.html#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is the error code. </p> <pre><code>const dns = require('dns'); dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { console.log(hostname, service); // Prints: localhost ssh });</code></pre> <h2>dns.resolve(hostname[, rrtype], callback)<span><a class="mark" href="#all_dns_resolve_hostname_rrtype_callback" id="all_dns_resolve_hostname_rrtype_callback">#</a></span></h2> <p>Uses the DNS protocol to resolve a hostname (e.g. <code>'nodejs.org'</code>) into an array of the record types specified by <code>rrtype</code>. </p> <p>Valid values for <code>rrtype</code> are: </p> <ul> <li><code>'A'</code> - IPV4 addresses, default</li> <li><code>'AAAA'</code> - IPV6 addresses</li> <li><code>'MX'</code> - mail exchange records</li> <li><code>'TXT'</code> - text records</li> <li><code>'SRV'</code> - SRV records</li> <li><code>'PTR'</code> - used for reverse IP lookups</li> <li><code>'NS'</code> - name server records</li> <li><code>'CNAME'</code> - canonical name records</li> <li><code>'SOA'</code> - start of authority record</li> </ul> <p>The <code>callback</code> function has arguments <code>(err, addresses)</code>. When successful, <code>addresses</code> will be an array. 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 <a href="errors.html#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is one of the error codes listed below. </p> <h2>dns.resolve4(hostname, callback)<span><a class="mark" href="#all_dns_resolve4_hostname_callback" id="all_dns_resolve4_hostname_callback">#</a></span></h2> <p>Uses the DNS protocol to resolve a IPv4 addresses (<code>A</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain 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(hostname, callback)<span><a class="mark" href="#all_dns_resolve6_hostname_callback" id="all_dns_resolve6_hostname_callback">#</a></span></h2> <p>Uses the DNS protocol to resolve a IPv6 addresses (<code>AAAA</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an array of IPv6 addresses. </p> <h2>dns.resolveCname(hostname, callback)<span><a class="mark" href="#all_dns_resolvecname_hostname_callback" id="all_dns_resolvecname_hostname_callback">#</a></span></h2> <p>Uses the DNS protocol to resolve <code>CNAME</code> records for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an of canonical name records available for the <code>hostname</code> (e.g. <code>['bar.example.com']</code>). </p> <h2>dns.resolveMx(hostname, callback)<span><a class="mark" href="#all_dns_resolvemx_hostname_callback" id="all_dns_resolvemx_hostname_callback">#</a></span></h2> <p>Uses the DNS protocol to resolve mail exchange records (<code>MX</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an array of objects containing both a <code>priority</code> and <code>exchange</code> property (e.g. <code>[{priority: 10, exchange: 'mx.example.com'}, ...]</code>). </p> <h2>dns.resolveNs(hostname, callback)<span><a class="mark" href="#all_dns_resolvens_hostname_callback" id="all_dns_resolvens_hostname_callback">#</a></span></h2> <p>Uses the DNS protocol to resolve name server records (<code>NS</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an array of name server records available for <code>hostname</code> (e.g., <code>['ns1.example.com', 'ns2.example.com']</code>). </p> <h2>dns.resolveSoa(hostname, callback)<span><a class="mark" href="#all_dns_resolvesoa_hostname_callback" id="all_dns_resolvesoa_hostname_callback">#</a></span></h2> <p>Uses the DNS protocol to resolve a start of authority record (<code>SOA</code> record) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will be an object with the following properties: </p> <ul> <li><code>nsname</code></li> <li><code>hostmaster</code></li> <li><code>serial</code></li> <li><code>refresh</code></li> <li><code>retry</code></li> <li><code>expire</code></li> <li><p><code>minttl</code></p> <p> {</p> <pre><code>nsname: 'ns.example.com', hostmaster: 'root.example.com', serial: 2013101809, refresh: 10000, retry: 2400, expire: 604800, minttl: 3600</code></pre> <p> }</p> </li> </ul> <h2>dns.resolveSrv(hostname, callback)<span><a class="mark" href="#all_dns_resolvesrv_hostname_callback" id="all_dns_resolvesrv_hostname_callback">#</a></span></h2> <p>Uses the DNS protocol to resolve service records (<code>SRV</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will be an array of objects with the following properties: </p> <ul> <li><code>priority</code></li> <li><code>weight</code></li> <li><code>port</code></li> <li><p><code>name</code></p> <p> {</p> <pre><code>priority: 10, weight: 5, port: 21223, name: 'service.example.com'</code></pre> <p> }</p> </li> </ul> <h2>dns.resolveTxt(hostname, callback)<span><a class="mark" href="#all_dns_resolvetxt_hostname_callback" id="all_dns_resolvetxt_hostname_callback">#</a></span></h2> <p>Uses the DNS protocol to resolve text queries (<code>TXT</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function is is a two-dimentional array of the text records available for <code>hostname</code> (e.g., <code>[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]</code>). Each sub-array contains TXT chunks of one record. Depending on the use case, these could be either joined together or treated separately. </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>Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of hostnames. </p> <p>The <code>callback</code> function has arguments <code>(err, hostnames)</code>, where <code>hostnames</code> is an array of resolved hostnames for the given <code>ip</code>. </p> <p>On error, <code>err</code> is an <a href="errors.html#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is one of the error codes listed below. </p> <h2>dns.setServers(servers)<span><a class="mark" href="#all_dns_setservers_servers" id="all_dns_setservers_servers">#</a></span></h2> <p>Sets the IP addresses of the servers to be used when resolving. The <code>servers</code> argument is an array of IPv4 or IPv6 addresses. </p> <p>If a port specified on the address it will be removed. </p> <p>An error will be thrown if an invalid address is provided. </p> <p>The <code>dns.setServers()</code> method must not be called while a DNS query is in progress. </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 hostname.</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> <h2>Implementation considerations<span><a class="mark" href="#all_implementation_considerations" id="all_implementation_considerations">#</a></span></h2> <p>Although <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> and the various <code>dns.resolve*()/dns.reverse()</code> functions have the same goal of associating a network name with a network address (or vice versa), their behavior is quite different. These differences can have subtle but significant consequences on the behavior of Node.js programs. </p> <h3><code>dns.lookup()</code><span><a class="mark" href="#all_dns_lookup" id="all_dns_lookup">#</a></span></h3> <p>Under the hood, <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> uses the same operating system facilities as most other programs. For instance, <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> will almost always resolve a given name the same way as the <code>ping</code> command. On most POSIX-like operating systems, the behavior of the <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> function can be modified by changing settings in <code>nsswitch.conf(5)</code> and/or <code>resolv.conf(5)</code>, but note that changing these files will change the behavior of <em>all other programs running on the same operating system</em>. </p> <p>Though the call to <code>dns.lookup()</code> will be asynchronous from JavaScript's perspective, it is implemented as a synchronous call to <code>getaddrinfo(3)</code> that runs on libuv's threadpool. Because libuv's threadpool has a fixed size, it means that if for whatever reason the call to <code>getaddrinfo(3)</code> takes a long time, other operations that could run on libuv's threadpool (such as filesystem operations) will experience degraded performance. In order to mitigate this issue, one potential solution is to increase the size of libuv's threadpool by setting the <code>'UV_THREADPOOL_SIZE'</code> environment variable to a value greater than <code>4</code> (its current default value). For more information on libuv's threadpool, see <a href="http://docs.libuv.org/en/latest/threadpool.html">the official libuv documentation</a>. </p> <h3><code>dns.resolve()</code>, <code>dns.resolve*()</code> and <code>dns.reverse()</code><span><a class="mark" href="#all_dns_resolve_dns_resolve_and_dns_reverse" id="all_dns_resolve_dns_resolve_and_dns_reverse">#</a></span></h3> <p>These functions are implemented quite differently than <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. They do not use <code>getaddrinfo(3)</code> and they <em>always</em> perform a DNS query on the network. This network communication is always done asynchronously, and does not use libuv's threadpool. </p> <p>As a result, these functions cannot have the same negative impact on other processing that happens on libuv's threadpool that <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> can have. </p> <p>They do not use the same set of configuration files than what <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> uses. For instance, <em>they do not use the configuration from <code>/etc/hosts</code></em>. </p> <h1>Domain<span><a class="mark" href="#all_domain" id="all_domain">#</a></span></h1> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p><strong>This module is pending deprecation</strong>. Once a replacement API has been finalized, this module will be fully deprecated. Most end users should <strong>not</strong> have cause to use this module. Users who absolutely must have the functionality that domains provide may rely on it for the time being but should expect to have to migrate to a different solution in the future. </p> <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 immediately with an error code. </p> <h2>Warning: Don't Ignore Errors!<span><a class="mark" href="#all_warning_don_t_ignore_errors" id="all_warning_don_t_ignore_errors">#</a></span></h2> <!-- type=misc --> <p>Domain error handlers are not a substitute for closing down your process when an error occurs. </p> <p>By the very nature of how <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw"><code>throw</code></a> works in JavaScript, there is almost never any way to safely "pick up where you left off", without leaking references, or creating some other sort of undefined brittle state. </p> <p>The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, you might have many connections open, and it is not reasonable to abruptly shut those down because an error was triggered by someone else. </p> <p>The better approach is to send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker. </p> <p>In this way, <code>domain</code> usage goes hand-in-hand with the cluster module, since the master process can fork a new worker when a worker encounters an error. For Node.js programs that scale to multiple machines, the terminating proxy or service registry can take note of the failure, and react accordingly. </p> <p>For example, this is not a good idea: </p> <pre><code class="javascript">// XXX WARNING! BAD IDEA! var d = require('domain').create(); d.on('error', (er) => { // The error won't crash the process, but what it does is worse! // Though we've prevented abrupt process restarting, we are leaking // resources like crazy if this ever happens. // This is no better than process.on('uncaughtException')! console.log('error, but oh well', er.message); }); d.run(() => { require('http').createServer((req, res) => { handleRequest(req, res); }).listen(PORT); });</code></pre> <p>By using the context of a domain, and the resilience of separating our program into multiple worker processes, we can react more appropriately, and handle errors with much greater safety. </p> <pre><code class="javascript">// Much better! const cluster = require('cluster'); const PORT = +process.env.PORT || 1337; if (cluster.isMaster) { // In real life, you'd probably use more than just 2 workers, // and perhaps not put the master and worker in the same file. // // You can also of course get a bit fancier about logging, and // implement whatever custom logic you need to prevent DoS // attacks and other bad behavior. // // See the options in the cluster documentation. // // The important thing is that the master does very little, // increasing our resilience to unexpected errors. cluster.fork(); cluster.fork(); cluster.on('disconnect', (worker) => { console.error('disconnect!'); cluster.fork(); }); } else { // the worker // // This is where we put our bugs! const domain = require('domain'); // See the cluster documentation for more details about using // worker processes to serve requests. How it works, caveats, etc. const server = require('http').createServer((req, res) => { var d = domain.create(); d.on('error', (er) => { console.error('error', er.stack); // Note: we're in dangerous territory! // By definition, something unexpected occurred, // which we probably didn't want. // Anything can happen now! Be very careful! try { // make sure we close down within 30 seconds var killtimer = setTimeout(() => { process.exit(1); }, 30000); // But don't keep the process open just for that! killtimer.unref(); // stop taking new requests. server.close(); // Let the master know we're dead. This will trigger a // 'disconnect' in the cluster master, and then it will fork // a new worker. cluster.worker.disconnect(); // try to send an error to the request that triggered the problem res.statusCode = 500; res.setHeader('content-type', 'text/plain'); res.end('Oops, there was a problem!\n'); } catch (er2) { // oh well, not much we can do at this point. console.error('Error sending 500!', er2.stack); } }); // Because req and res were created before this domain existed, // we need to explicitly add them. // See the explanation of implicit vs explicit binding below. d.add(req); d.add(res); // Now run the handler function in the domain. d.run(() => { handleRequest(req, res); }); }); server.listen(PORT); } // This part isn't important. Just an example routing thing. // You'd put your fancy application logic here. function handleRequest(req, res) { switch(req.url) { case '/error': // We do some async stuff, and then... setTimeout(() => { // Whoops! flerb.bark(); }); break; default: res.end('ok'); } }</code></pre> <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 <code>Error</code> 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.domainEmitter</code> The event emitter that emitted an <code>'error'</code> event with the error object.</li> <li><code>error.domainBound</code> The callback function which was bound to the domain, and passed an error as its first argument.</li> <li><code>error.domainThrown</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 <strong>new</strong> 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. </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 <a href="#domain_domain_dispose"><code>domain.dispose()</code></a> 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 const domain = require('domain'); const http = require('http'); const serverDomain = domain.create(); serverDomain.run(() => { // server is created in the scope of serverDomain http.createServer((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', (er) => { console.error('Error', er, req.url); try { res.writeHead(500); res.end('Error occurred, sorry.'); } catch (er) { console.error('Error sending 500', er, req.url); } }); }).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"><code>EventEmitter</code></a>. To handle the errors that it catches, listen to its <code>'error'</code> event. </p> <h3>domain.run(fn[, arg][, ...])<span><a class="mark" href="#all_domain_run_fn_arg" id="all_domain_run_fn_arg">#</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. Optionally, arguments can be passed to the function. </p> <p>This is the most basic way to use a domain. </p> <p>Example: </p> <pre><code>const domain = require('domain'); const fs = require('fs'); const d = domain.create(); d.on('error', (er) => { console.error('Caught error!', er); }); d.run(() => { process.nextTick(() => { setTimeout(() => { // simulating some various async stuff fs.open('non-existent file', 'r', (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 <a href="#globals_setinterval_cb_ms"><code>setInterval()</code></a> and <a href="#globals_settimeout_cb_ms"><code>setTimeout()</code></a>. 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 <a href="#domain_domain_add_emitter"><code>domain.add(emitter)</code></a>. 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>const 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', (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 <a href="#domain_domain_bind_callback"><code>domain.bind(callback)</code></a>. However, in addition to catching thrown errors, it will also intercept <a href="errors.html#errors_class_error"><code>Error</code></a> objects sent as the first argument to the function. </p> <p>In this way, the common <code>if (err) return callback(err);</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>const 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', (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.enter()<span><a class="mark" href="#all_domain_enter" id="all_domain_enter">#</a></span></h3> <p>The <code>enter</code> method is plumbing used by the <code>run</code>, <code>bind</code>, and <code>intercept</code> methods to set the active domain. It sets <code>domain.active</code> and <code>process.domain</code> to the domain, and implicitly pushes the domain onto the domain stack managed by the domain module (see <a href="#domain_domain_exit"><code>domain.exit()</code></a> for details on the domain stack). The call to <code>enter</code> delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain. </p> <p>Calling <code>enter</code> changes only the active domain, and does not alter the domain itself. <code>enter</code> and <code>exit</code> can be called an arbitrary number of times on a single domain. </p> <p>If the domain on which <code>enter</code> is called has been disposed, <code>enter</code> will return without setting the domain. </p> <h3>domain.exit()<span><a class="mark" href="#all_domain_exit" id="all_domain_exit">#</a></span></h3> <p>The <code>exit</code> method exits the current domain, popping it off the domain stack. Any time execution is going to switch to the context of a different chain of asynchronous calls, it's important to ensure that the current domain is exited. The call to <code>exit</code> delimits either the end of or an interruption to the chain of asynchronous calls and I/O operations bound to a domain. </p> <p>If there are multiple, nested domains bound to the current execution context, <code>exit</code> will exit any domains nested within this domain. </p> <p>Calling <code>exit</code> changes only the active domain, and does not alter the domain itself. <code>enter</code> and <code>exit</code> can be called an arbitrary number of times on a single domain. </p> <p>If the domain on which <code>exit</code> is called has been disposed, <code>exit</code> will return without exiting the domain. </p> <h3>domain.dispose()<span><a class="mark" href="#all_domain_dispose" id="all_domain_dispose">#</a></span></h3> <pre class="api_stability_0">Stability: 0 - Deprecated. Please recover from failed IO actions explicitly via error event handlers set on the domain.</pre><p>Once <code>dispose</code> has been called, the domain will no longer be used by callbacks bound into the domain via <code>run</code>, <code>bind</code>, or <code>intercept</code>, and a <code>'dispose'</code> event is emitted. </p> <h1>Errors<span><a class="mark" href="#all_errors" id="all_errors">#</a></span></h1> <!--type=misc--> <p>Applications running in Node.js will generally experience four categories of errors: </p> <ul> <li>Standard JavaScript errors such as:<ul> <li>[<code>EvalError</code>][]: thrown when a call to <code>eval()</code> fails.</li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError"><code>SyntaxError</code></a>: thrown in response to improper JavaScript language syntax.</li> <li><a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a>: thrown when a value is not within an expected range</li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError"><code>ReferenceError</code></a>: thrown when using undefined variables</li> <li><a href="errors.html#errors_class_typeerror"><code>TypeError</code></a>: thrown when passing arguments of the wrong type</li> <li>[<code>URIError</code>][]: thrown when a global URI handling function is misused.</li> </ul> </li> <li>System errors triggered by underlying operating system constraints such as attempting to open a file that does not exist, attempting to send data over a closed socket, etc;</li> <li>And User-specified errors triggered by application code.</li> <li>Assertion Errors are a special class of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically by the <code>assert</code> module.</li> </ul> <p>All JavaScript and System errors raised by Node.js inherit from, or are instances of, the standard JavaScript <a href="errors.html#errors_class_error"><code>Error</code></a> class and are guaranteed to provide <em>at least</em> the properties available on that class. </p> <h2>Error Propagation and Interception<span><a class="mark" href="#all_error_propagation_and_interception" id="all_error_propagation_and_interception">#</a></span></h2> <!--type=misc--> <p>Node.js supports several mechanisms for propagating and handling errors that occur while an application is running. How these errors are reported and handled depends entirely on the type of Error and the style of the API that is called. </p> <p>All JavaScript errors are handled as exceptions that <em>immediately</em> generate and throw an error using the standard JavaScript <code>throw</code> mechanism. These are handled using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>try / catch</code> construct</a> provided by the JavaScript language. </p> <pre><code>// Throws with a ReferenceError because z is undefined try { const m = 1; const n = m + z; } catch (err) { // Handle the error here. }</code></pre> <p>Any use of the JavaScript <code>throw</code> mechanism will raise an exception that <em>must</em> be handled using <code>try / catch</code> or the Node.js process will exit immediately. </p> <p>With few exceptions, <em>Synchronous</em> APIs (any blocking method that does not accept a <code>callback</code> function, such as <a href="fs.html#fs_fs_readfilesync_file_options"><code>fs.readFileSync</code></a>), will use <code>throw</code> to report errors. </p> <p>Errors that occur within <em>Asynchronous APIs</em> may be reported in multiple ways: </p> <ul> <li><p>Most asynchronous methods that accept a <code>callback</code> function will accept an <code>Error</code> object passed as the first argument to that function. If that first argument is not <code>null</code> and is an instance of <code>Error</code>, then an error occurred that should be handled.</p> <pre><code>const fs = require('fs'); fs.readFile('a file that does not exist', (err, data) => { if (err) { console.error('There was an error reading the file!', err); return; } // Otherwise handle the data });</code></pre> </li> <li><p>When an asynchronous method is called on an object that is an <code>EventEmitter</code>, errors can be routed to that object's <code>'error'</code> event.</p> <pre><code>const net = require('net'); const connection = net.connect('localhost'); // Adding an 'error' event handler to a stream: connection.on('error', (err) => { // If the connection is reset by the server, or if it can't // connect at all, or on any sort of error encountered by // the connection, the error will be sent here. console.error(err); }); connection.pipe(process.stdout);</code></pre> </li> <li><p>A handful of typically asynchronous methods in the Node.js API may still use the <code>throw</code> mechanism to raise exceptions that must be handled using <code>try / catch</code>. There is no comprehensive list of such methods; please refer to the documentation of each method to determine the appropriate error handling mechanism required.</p> </li> </ul> <p>The use of the <code>'error'</code> event mechanism is most common for <a href="stream.html">stream-based</a> and <a href="events.html#events_class_events_eventemitter">event emitter-based</a> APIs, which themselves represent a series of asynchronous operations over time (as opposed to a single operation that may pass or fail). </p> <p>For <em>all</em> <code>EventEmitter</code> objects, if an <code>'error'</code> event handler is not provided, the error will be thrown, causing the Node.js process to report an unhandled exception and crash unless either: The <a href="domain.html"><code>domain</code></a> module is used appropriately or a handler has been registered for the <a href="process.html#process_event_uncaughtexception"><code>process.on('uncaughtException')</code></a> event. </p> <pre><code>const EventEmitter = require('events'); const ee = new EventEmitter(); setImmediate(() => { // This will crash the process because no 'error' event // handler has been added. ee.emit('error', new Error('This will crash')); });</code></pre> <p>Errors generated in this way <em>cannot</em> be intercepted using <code>try / catch</code> as they are thrown <em>after</em> the calling code has already exited. </p> <p>Developers must refer to the documentation for each method to determine exactly how errors raised by those methods are propagated. </p> <h3>Node.js style callbacks<span><a class="mark" href="#all_node_js_style_callbacks" id="all_node_js_style_callbacks">#</a></span></h3> <!--type=misc--> <p>Most asynchronous methods exposed by the Node.js core API follow an idiomatic pattern referred to as a "Node.js style callback". With this pattern, a callback function is passed to the method as an argument. When the operation either completes or an error is raised, the callback function is called with the Error object (if any) passed as the first argument. If no error was raised, the first argument will be passed as <code>null</code>. </p> <pre><code>const fs = require('fs'); function nodeStyleCallback(err, data) { if (err) { console.error('There was an error', err); return; } console.log(data); } fs.readFile('/some/file/that/does-not-exist', nodeStyleCallback); fs.readFile('/some/file/that/does-exist', nodeStyleCallback)</code></pre> <p>The JavaScript <code>try / catch</code> mechanism <strong>cannot</strong> be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use <code>throw</code> inside a Node.js style callback: </p> <pre><code>// THIS WILL NOT WORK: const fs = require('fs'); try { fs.readFile('/some/file/that/does-not-exist', (err, data) => { // mistaken assumption: throwing here... if (err) { throw err; } }); } catch(err) { // This will not catch the throw! console.log(err); }</code></pre> <p>This will not work because the callback function passed to <code>fs.readFile()</code> is called asynchronously. By the time the callback has been called, the surrounding code (including the <code>try { } catch(err) { }</code> block will have already exited. Throwing an error inside the callback <strong>can crash the Node.js process</strong> in most cases. If <a href="domain.html">domains</a> are enabled, or a handler has been registered with <code>process.on('uncaughtException')</code>, such errors can be intercepted. </p> <h2>Class: Error<span><a class="mark" href="#all_class_error" id="all_class_error">#</a></span></h2> <!--type=class--> <p>A generic JavaScript <code>Error</code> object that does not denote any specific circumstance of why the error occurred. <code>Error</code> objects capture a "stack trace" detailing the point in the code at which the <code>Error</code> was instantiated, and may provide a text description of the error. </p> <p>All errors generated by Node.js, including all System and JavaScript errors, will either be instances of, or inherit from, the <code>Error</code> class. </p> <h3>new Error(message)<span><a class="mark" href="#all_new_error_message" id="all_new_error_message">#</a></span></h3> <p>Creates a new <code>Error</code> object and sets the <code>error.message</code> property to the provided text message. If an object is passed as <code>message</code>, the text message is generated by calling <code>message.toString()</code>. The <code>error.stack</code> property will represent the point in the code at which <code>new Error()</code> was called. Stack traces are dependent on <a href="https://github.com/v8/v8/wiki/Stack-Trace-API">V8's stack trace API</a>. Stack traces extend only to either (a) the beginning of <em>synchronous code execution</em>, or (b) the number of frames given by the property <code>Error.stackTraceLimit</code>, whichever is smaller. </p> <h3>Error.captureStackTrace(targetObject[, constructorOpt])<span><a class="mark" href="#all_error_capturestacktrace_targetobject_constructoropt" id="all_error_capturestacktrace_targetobject_constructoropt">#</a></span></h3> <p>Creates a <code>.stack</code> property on <code>targetObject</code>, which when accessed returns a string representing the location in the code at which <code>Error.captureStackTrace()</code> was called. </p> <pre><code>const myObject = {}; Error.captureStackTrace(myObject); myObject.stack // similar to `new Error().stack`</code></pre> <p>The first line of the trace, instead of being prefixed with <code>ErrorType: message</code>, will be the result of calling <code>targetObject.toString()</code>. </p> <p>The optional <code>constructorOpt</code> argument accepts a function. If given, all frames above <code>constructorOpt</code>, including <code>constructorOpt</code>, will be omitted from the generated stack trace. </p> <p>The <code>constructorOpt</code> argument is useful for hiding implementation details of error generation from an end user. For instance: </p> <pre><code>function MyError() { Error.captureStackTrace(this, MyError); } // Without passing MyError to captureStackTrace, the MyError // frame would should up in the .stack property. by passing // the constructor, we omit that frame and all frames above it. new MyError().stack</code></pre> <h3>Error.stackTraceLimit<span><a class="mark" href="#all_error_stacktracelimit" id="all_error_stacktracelimit">#</a></span></h3> <p>The <code>Error.stackTraceLimit</code> property specifies the number of stack frames collected by a stack trace (whether generated by <code>new Error().stack</code> or <code>Error.captureStackTrace(obj)</code>). </p> <p>The default value is <code>10</code> but may be set to any valid JavaScript number. Changes will affect any stack trace captured <em>after</em> the value has been changed. </p> <p>If set to a non-number value, or set to a negative number, stack traces will not capture any frames. </p> <h4>error.message<span><a class="mark" href="#all_error_message" id="all_error_message">#</a></span></h4> <p>Returns the string description of error as set by calling <code>new Error(message)</code>. The <code>message</code> passed to the constructor will also appear in the first line of the stack trace of the <code>Error</code>, however changing this property after the <code>Error</code> object is created <em>may not</em> change the first line of the stack trace. </p> <pre><code>const err = new Error('The message'); console.log(err.message); // Prints: The message</code></pre> <h4>error.stack<span><a class="mark" href="#all_error_stack" id="all_error_stack">#</a></span></h4> <p>Returns a string describing the point in the code at which the <code>Error</code> was instantiated. </p> <p>For example: </p> <pre><code>Error: Things keep happening! at /home/gbusey/file.js:525:2 at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21) at Actor.<anonymous> (/home/gbusey/actors.js:400:8) at increaseSynergy (/home/gbusey/actors.js:701:6)</code></pre> <p>The first line is formatted as <code><error class name>: <error message></code>, and is followed by a series of stack frames (each line beginning with "at "). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses. </p> <p>It is important to note that frames are <strong>only</strong> generated for JavaScript functions. If, for example, execution synchronously passes through a C++ addon function called <code>cheetahify</code>, which itself calls a JavaScript function, the frame representing the <code>cheetahify</code> call will <strong>not</strong> be present in the stack traces: </p> <pre><code>const cheetahify = require('./native-binding.node'); function makeFaster() { // cheetahify *synchronously* calls speedy. cheetahify(function speedy() { throw new Error('oh no!'); }); } makeFaster(); // will throw: // /home/gbusey/file.js:6 // throw new Error('oh no!'); // ^ // Error: oh no! // at speedy (/home/gbusey/file.js:6:11) // at makeFaster (/home/gbusey/file.js:5:3) // at Object.<anonymous> (/home/gbusey/file.js:10:1) // at Module._compile (module.js:456:26) // at Object.Module._extensions..js (module.js:474:10) // at Module.load (module.js:356:32) // at Function.Module._load (module.js:312:12) // at Function.Module.runMain (module.js:497:10) // at startup (node.js:119:16) // at node.js:906:3</code></pre> <p>The location information will be one of: </p> <ul> <li><code>native</code>, if the frame represents a call internal to V8 (as in <code>[].forEach</code>).</li> <li><code>plain-filename.js:line:column</code>, if the frame represents a call internal to Node.js.</li> <li><code>/absolute/path/to/file.js:line:column</code>, if the frame represents a call in a user program, or its dependencies.</li> </ul> <p>The string representing the stack trace is lazily generated when the <code>error.stack</code> property is <strong>accessed</strong>. </p> <p>The number of frames captured by the stack trace is bounded by the smaller of <code>Error.stackTraceLimit</code> or the number of available frames on the current event loop tick. </p> <p>System-level errors are generated as augmented <code>Error</code> instances, which are detailed <a href="#errors_system_errors">below</a>. </p> <h2>Class: RangeError<span><a class="mark" href="#all_class_rangeerror" id="all_class_rangeerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates that a provided argument was not within the set or range of acceptable values for a function; whether that is a numeric range, or outside the set of options for a given function parameter. </p> <p>For example: </p> <pre><code>require('net').connect(-1); // throws RangeError, port should be > 0 && < 65536</code></pre> <p>Node.js will generate and throw <code>RangeError</code> instances <em>immediately</em> as a form of argument validation. </p> <h2>Class: ReferenceError<span><a class="mark" href="#all_class_referenceerror" id="all_class_referenceerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates that an attempt is being made to access a variable that is not defined. Such errors commonly indicate typos in code, or an otherwise broken program. </p> <p>While client code may generate and propagate these errors, in practice, only V8 will do so. </p> <pre><code>doesNotExist; // throws ReferenceError, doesNotExist is not a variable in this program.</code></pre> <p><code>ReferenceError</code> instances will have an <code>error.arguments</code> property whose value is an array containing a single element: a string representing the variable that was not defined. </p> <pre><code>const assert = require('assert'); try { doesNotExist; } catch(err) { assert(err.arguments[0], 'doesNotExist'); }</code></pre> <p>Unless an application is dynamically generating and running code, <code>ReferenceError</code> instances should always be considered a bug in the code or its dependencies. </p> <h2>Class: SyntaxError<span><a class="mark" href="#all_class_syntaxerror" id="all_class_syntaxerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates that a program is not valid JavaScript. These errors may only be generated and propagated as a result of code evaluation. Code evaluation may happen as a result of <code>eval</code>, <code>Function</code>, <code>require</code>, or <a href="vm.html">vm</a>. These errors are almost always indicative of a broken program. </p> <pre><code>try { require('vm').runInThisContext('binary ! isNotOk'); } catch(err) { // err will be a SyntaxError }</code></pre> <p><code>SyntaxError</code> instances are unrecoverable in the context that created them – they may only be caught by other contexts. </p> <h2>Class: TypeError<span><a class="mark" href="#all_class_typeerror" id="all_class_typeerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates that a provided argument is not an allowable type. For example, passing a function to a parameter which expects a string would be considered a TypeError. </p> <pre><code>require('url').parse(function() { }); // throws TypeError, since it expected a string</code></pre> <p>Node.js will generate and throw <code>TypeError</code> instances <em>immediately</em> as a form of argument validation. </p> <h2>Exceptions vs. Errors<span><a class="mark" href="#all_exceptions_vs_errors" id="all_exceptions_vs_errors">#</a></span></h2> <!--type=misc--> <p>A JavaScript exception is a value that is thrown as a result of an invalid operation or as the target of a <code>throw</code> statement. While it is not required that these values are instances of <code>Error</code> or classes which inherit from <code>Error</code>, all exceptions thrown by Node.js or the JavaScript runtime <em>will</em> be instances of Error. </p> <p>Some exceptions are <em>unrecoverable</em> at the JavaScript layer. Such exceptions will <em>always</em> cause the Node.js process to crash. Examples include <code>assert()</code> checks or <code>abort()</code> calls in the C++ layer. </p> <h2>System Errors<span><a class="mark" href="#all_system_errors" id="all_system_errors">#</a></span></h2> <p>System errors are generated when exceptions occur within the program's runtime environment. Typically, these are operational errors that occur when an application violates an operating system constraint such as attempting to read a file that does not exist or when the user does not have sufficient permissions. </p> <p>System errors are typically generated at the syscall level: an exhaustive list of error codes and their meanings is available by running <code>man 2 intro</code> or <code>man 3 errno</code> on most Unices; or <a href="http://man7.org/linux/man-pages/man3/errno.3.html">online</a>. </p> <p>In Node.js, system errors are represented as augmented <code>Error</code> objects with added properties. </p> <h3>Class: System Error<span><a class="mark" href="#all_class_system_error" id="all_class_system_error">#</a></span></h3> <h4>error.code<span><a class="mark" href="#all_error_code" id="all_error_code">#</a></span></h4> <h4>error.errno<span><a class="mark" href="#all_error_errno" id="all_error_errno">#</a></span></h4> <p>Returns a string representing the error code, which is always <code>E</code> followed by a sequence of capital letters, and may be referenced in <code>man 2 intro</code>. </p> <p>The properties <code>error.code</code> and <code>error.errno</code> are aliases of one another and return the same value. </p> <h4>error.syscall<span><a class="mark" href="#all_error_syscall" id="all_error_syscall">#</a></span></h4> <p>Returns a string describing the <a href="http://man7.org/linux/man-pages/man2/syscall.2.html">syscall</a> that failed. </p> <h3>Common System Errors<span><a class="mark" href="#all_common_system_errors" id="all_common_system_errors">#</a></span></h3> <p>This list is <strong>not exhaustive</strong>, but enumerates many of the common system errors encountered when writing a Node.js program. An exhaustive list may be found <a href="http://man7.org/linux/man-pages/man3/errno.3.html">here</a>. </p> <ul> <li><p><code>EACCES</code> (Permission denied): An attempt was made to access a file in a way forbidden by its file access permissions.</p> </li> <li><p><code>EADDRINUSE</code> (Address already in use): An attempt to bind a server (<a href="net.html"><code>net</code></a>, <a href="http.html"><code>http</code></a>, or <a href="https.html"><code>https</code></a>) to a local address failed due to another server on the local system already occupying that address.</p> </li> <li><p><code>ECONNREFUSED</code> (Connection refused): No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host.</p> </li> <li><p><code>ECONNRESET</code> (Connection reset by peer): A connection was forcibly closed by a peer. This normally results from a loss of the connection on the remote socket due to a timeout or reboot. Commonly encountered via the <a href="http.html"><code>http</code></a> and <a href="net.html"><code>net</code></a> modules.</p> </li> <li><p><code>EEXIST</code> (File exists): An existing file was the target of an operation that required that the target not exist.</p> </li> <li><p><code>EISDIR</code> (Is a directory): An operation expected a file, but the given pathname was a directory.</p> </li> <li><p><code>EMFILE</code> (Too many open files in system): Maximum number of <a href="https://en.wikipedia.org/wiki/File_descriptor">file descriptors</a> allowable on the system has been reached, and requests for another descriptor cannot be fulfilled until at least one has been closed. This is encountered when opening many files at once in parallel, especially on systems (in particular, OS X) where there is a low file descriptor limit for processes. To remedy a low limit, run <code>ulimit -n 2048</code> in the same shell that will run the Node.js process.</p> </li> <li><p><code>ENOENT</code> (No such file or directory): Commonly raised by <a href="fs.html"><code>fs</code></a> operations to indicate that a component of the specified pathname does not exist -- no entity (file or directory) could be found by the given path.</p> </li> <li><p><code>ENOTDIR</code> (Not a directory): A component of the given pathname existed, but was not a directory as expected. Commonly raised by <a href="fs.html#fs_fs_readdir_path_callback"><code>fs.readdir</code></a>.</p> </li> <li><p><code>ENOTEMPTY</code> (Directory not empty): A directory with entries was the target of an operation that requires an empty directory -- usually <a href="fs.html#fs_fs_unlink_path_callback"><code>fs.unlink</code></a>.</p> </li> <li><p><code>EPERM</code> (Operation not permitted): An attempt was made to perform an operation that requires elevated privileges.</p> </li> <li><p><code>EPIPE</code> (Broken pipe): A write on a pipe, socket, or FIFO for which there is no process to read the data. Commonly encountered at the <a href="net.html"><code>net</code></a> and <a href="http.html"><code>http</code></a> layers, indicative that the remote side of the stream being written to has been closed.</p> </li> <li><p><code>ETIMEDOUT</code> (Operation timed out): A connect or send request failed because the connected party did not properly respond after a period of time. Usually encountered by <a href="http.html"><code>http</code></a> or <a href="net.html"><code>net</code></a> -- often a sign that a <code>socket.end()</code> was not properly called.</p> </li> </ul> <h1>Events<span><a class="mark" href="#all_events" id="all_events">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><!--type=module--> <p>Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") periodically emit named events that cause Function objects ("listeners") to be called. </p> <p>For instance: a <a href="net.html#net_class_net_server"><code>net.Server</code></a> object emits an event each time a peer connects to it; a <a href="fs.html#fs_class_fs_readstream"><code>fs.ReadStream</code></a> emits an event when the file is opened; a <a href="stream.html#stream_stream">stream</a> emits an event whenever data is available to be read. </p> <p>All objects that emit events are instances of the <code>EventEmitter</code> class. These objects expose an <code>eventEmitter.on()</code> function that allows one or more Functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used. </p> <p>When the <code>EventEmitter</code> object emits an event, all of the Functions attached to that specific event are called <em>synchronously</em>. Any values returned by the called listeners are <em>ignored</em> and will be discarded. </p> <p>The following example shows a simple <code>EventEmitter</code> instance with a single listener. The <code>eventEmitter.on()</code> method is used to register listeners, while the <code>eventEmitter.emit()</code> method is used to trigger the event. </p> <pre><code>const EventEmitter = require('events'); const util = require('util'); function MyEmitter() { EventEmitter.call(this); } util.inherits(MyEmitter, EventEmitter); const myEmitter = new MyEmitter(); myEmitter.on('event', function() { console.log('an event occurred!'); }); myEmitter.emit('event');</code></pre> <p>Any object can become an <code>EventEmitter</code> through inheritance. The example above uses the traditional Node.js style prototypical inheritance using the <code>util.inherits()</code> method. It is, however, possible to use ES6 classes as well: </p> <pre><code>const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', function() { console.log('an event occurred!'); }); myEmitter.emit('event');</code></pre> <h2>Passing arguments and <code>this</code> to listeners<span><a class="mark" href="#all_passing_arguments_and_this_to_listeners" id="all_passing_arguments_and_this_to_listeners">#</a></span></h2> <p>The <code>eventEmitter.emit()</code> method allows an arbitrary set of arguments to be passed to the listener functions. It is important to keep in mind that when an ordinary listener function is called by the <code>EventEmitter</code>, the standard <code>this</code> keyword is intentionally set to reference the <code>EventEmitter</code> to which the listener is attached. </p> <pre><code>const myEmitter = new MyEmitter(); myEmitter.on('event', function(a, b) { console.log(a, b, this); // Prints: // a b MyEmitter { // domain: null, // _events: { event: [Function] }, // _eventsCount: 1, // _maxListeners: undefined } }); myEmitter.emit('event', 'a', 'b');</code></pre> <p>It is possible to use ES6 Arrow Functions as listeners, however, when doing so, the <code>this</code> keyword will no longer reference the <code>EventEmitter</code> instance: </p> <pre><code>const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { console.log(a, b, this); // Prints: a b {} }); myEmitter.emit('event', 'a', 'b');</code></pre> <h2>Asynchronous vs. Synchronous<span><a class="mark" href="#all_asynchronous_vs_synchronous" id="all_asynchronous_vs_synchronous">#</a></span></h2> <p>The <code>EventListener</code> calls all listeners synchronously in the order in which they were registered. This is important to ensure the proper sequencing of events and to avoid race conditions or logic errors. When appropriate, listener functions can switch to an asynchronous mode of operation using the <code>setImmediate()</code> or <code>process.nextTick()</code> methods: </p> <pre><code>const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { setImmediate(() => { console.log('this happens asynchronously'); }); }); myEmitter.emit('event', 'a', 'b');</code></pre> <h2>Handling events only once<span><a class="mark" href="#all_handling_events_only_once" id="all_handling_events_only_once">#</a></span></h2> <p>When a listener is registered using the <code>eventEmitter.on()</code> method, that listener will be invoked <em>every time</em> the named event is emitted. </p> <pre><code>const myEmitter = new MyEmitter(); var m = 0; myEmitter.on('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Prints: 2</code></pre> <p>Using the <code>eventEmitter.once()</code> method, it is possible to register a listener that is immediately unregistered after it is called. </p> <pre><code>const myEmitter = new MyEmitter(); var m = 0; myEmitter.once('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Ignored</code></pre> <h2>Error events<span><a class="mark" href="#all_error_events" id="all_error_events">#</a></span></h2> <p>When an error occurs within an <code>EventEmitter</code> instance, the typical action is for an <code>'error'</code> event to be emitted. These are treated as a special case within Node.js. </p> <p>If an <code>EventEmitter</code> does <em>not</em> have at least one listener registered for the <code>'error'</code> event, and an <code>'error'</code> event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits. </p> <pre><code>const myEmitter = new MyEmitter(); myEmitter.emit('error', new Error('whoops!')); // Throws and crashes Node.js</code></pre> <p>To guard against crashing the Node.js process, developers can either register a listener for the <code>process.on('uncaughtException')</code> event or use the <a href="domain.html"><code>domain</code></a> module (<em>Note, however, that the <code>domain</code> module has been deprecated</em>). </p> <pre><code>const myEmitter = new MyEmitter(); process.on('uncaughtException', (err) => { console.log('whoops! there was an error'); }); myEmitter.emit('error', new Error('whoops!')); // Prints: whoops! there was an error</code></pre> <p>As a best practice, developers should always register listeners for the <code>'error'</code> event: </p> <pre><code>const myEmitter = new MyEmitter(); myEmitter.on('error', (err) => { console.log('whoops! there was an error'); }); myEmitter.emit('error', new Error('whoops!')); // Prints: whoops! there was an error</code></pre> <h2>Class: EventEmitter<span><a class="mark" href="#all_class_eventemitter" id="all_class_eventemitter">#</a></span></h2> <p>The <code>EventEmitter</code> class is defined and exposed by the <code>events</code> module: </p> <pre><code>const EventEmitter = require('events');</code></pre> <p>All EventEmitters emit the event <code>'newListener'</code> when new listeners are added and <code>'removeListener'</code> when a listener is removed. </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|Symbol</span> The event name</li> <li><code>listener</code> <span class="type">Function</span> The event handler function</li> </div></ul> <p>The <code>EventEmitter</code> instance will emit it's own <code>'newListener'</code> event <em>before</em> a listener is added to it's internal array of listeners. </p> <p>Listeners registered for the <code>'newListener'</code> event will be passed the event name and a reference to the listener being added. </p> <p>The fact that the event is triggered before adding the listener has a subtle but important side effect: any <em>additional</em> listeners registered to the same <code>name</code> <em>within</em> the <code>'newListener'</code> callback will be inserted <em>before</em> the listener that is in the process of being added. </p> <pre><code>const myEmitter = new MyEmitter(); // Only do this once so we don't loop forever myEmitter.once('newListener', (event, listener) => { if (event === 'event') { // Insert a new listener in front myEmitter.on('event', () => { console.log('B'); }); } }); myEmitter.on('event', () => { console.log('A'); }); myEmitter.emit('event'); // Prints: // B // A</code></pre> <h3>Event: 'removeListener'<span><a class="mark" href="#all_event_removelistener" id="all_event_removelistener">#</a></span></h3> <div class="signature"><ul> <li><code>event</code> <span class="type">String|Symbol</span> The event name</li> <li><code>listener</code> <span class="type">Function</span> The event handler function</li> </div></ul> <p>The <code>'removeListener'</code> event is emitted <em>after</em> a listener is removed. </p> <h3>EventEmitter.listenerCount(emitter, event)<span><a class="mark" href="#all_eventemitter_listenercount_emitter_event" id="all_eventemitter_listenercount_emitter_event">#</a></span></h3> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <a href="#events_emitter_listenercount_event"><code>emitter.listenerCount()</code></a> instead.</pre><p>A class method that returns the number of listeners for the given <code>event</code> registered on the given <code>emitter</code>. </p> <pre><code>const myEmitter = new MyEmitter(); myEmitter.on('event', () => {}); myEmitter.on('event', () => {}); console.log(EventEmitter.listenerCount(myEmitter, 'event')); // Prints: 2</code></pre> <h3>EventEmitter.defaultMaxListeners<span><a class="mark" href="#all_eventemitter_defaultmaxlisteners" id="all_eventemitter_defaultmaxlisteners">#</a></span></h3> <p>By default, a maximum of <code>10</code> listeners can be registered for any single event. This limit can be changed for individual <code>EventEmitter</code> instances using the <a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> method. To change the default for <em>all</em> <code>EventEmitter</code> instances, the <code>EventEmitter.defaultMaxListeners</code> property can be used. </p> <p>Take caution when setting the <code>EventEmitter.defaultMaxListeners</code> because the change effects <em>all</em> <code>EventEmitter</code> instances, including those created before the change is made. However, calling <a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> still has precedence over <code>EventEmitter.defaultMaxListeners</code>. </p> <p>Note that this is not a hard limit. The <code>EventEmitter</code> instance will allow more listeners to be added but will output a trace warning to stderr indicating that a <code>possible EventEmitter memory leak</code> has been detected. For any single <code>EventEmitter</code>, the <code>emitter.getMaxListeners()</code> and <code>emitter.setMaxListeners()</code> methods can be used to temporarily avoid this warning: </p> <pre><code>emitter.setMaxListeners(emitter.getMaxListeners() + 1); emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); });</code></pre> <h3>emitter.addListener(event, listener)<span><a class="mark" href="#all_emitter_addlistener_event_listener" id="all_emitter_addlistener_event_listener">#</a></span></h3> <p>Alias for <code>emitter.on(event, listener)</code>. </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>Synchronously calls each of the listeners registered for <code>event</code>, in the order they were registered, passing the supplied arguments to each. </p> <p>Returns <code>true</code> if event had listeners, <code>false</code> otherwise. </p> <h3>emitter.getMaxListeners()<span><a class="mark" href="#all_emitter_getmaxlisteners" id="all_emitter_getmaxlisteners">#</a></span></h3> <p>Returns the current max listener value for the <code>EventEmitter</code> which is either set by <a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> or defaults to <a href="#events_eventemitter_defaultmaxlisteners"><code>EventEmitter.defaultMaxListeners</code></a>. </p> <h3>emitter.listenerCount(event)<span><a class="mark" href="#all_emitter_listenercount_event" id="all_emitter_listenercount_event">#</a></span></h3> <div class="signature"><ul> <li><code>event</code> <span class="type">Value</span> The type of event</li> </div></ul> <p>Returns the number of listeners listening to the <code>event</code> type. </p> <h3>emitter.listeners(event)<span><a class="mark" href="#all_emitter_listeners_event" id="all_emitter_listeners_event">#</a></span></h3> <p>Returns a copy of the array of listeners for the specified <code>event</code>. </p> <pre><code>server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ]</code></pre> <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 the <code>listener</code> function to the end of the listeners array for the specified <code>event</code>. No checks are made to see if the <code>listener</code> has already been added. Multiple calls passing the same combination of <code>event</code> and <code>listener</code> will result in the <code>listener</code> being added, and called, multiple times. </p> <pre><code>server.on('connection', (stream) => { console.log('someone connected!'); });</code></pre> <p>Returns a reference to the <code>EventEmitter</code> so calls can be chained. </p> <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> <code>listener</code> function for the <code>event</code>. This listener is invoked only the next time <code>event</code> is triggered, after which it is removed. </p> <pre><code>server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });</code></pre> <p>Returns a reference to the <code>EventEmitter</code> so calls can be chained. </p> <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 <code>event</code>. </p> <p>Note that it is bad practice to remove listeners added elsewhere in the code, particularly when the <code>EventEmitter</code> instance was created by some other component or module (e.g. sockets or file streams). </p> <p>Returns a reference to the <code>EventEmitter</code> so calls can be chained. </p> <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>Removes the specified <code>listener</code> from the listener array for the specified <code>event</code>. </p> <pre><code>var callback = function(stream) { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);</code></pre> <p><code>removeListener</code> will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified <code>event</code>, then <code>removeListener</code> must be called multiple times to remove each instance. </p> <p>Because listeners are managed using an internal array, calling this will change the position indices of any listener registered <em>after</em> the listener being removed. This will not impact the order in which listeners are called, but it will means that any copies of the listener array as returned by the <code>emitter.listeners()</code> method will need to be recreated. </p> <p>Returns a reference to the <code>EventEmitter</code> so calls can be chained. </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 <code>10</code> listeners are added for a particular event. This is a useful default that helps finding memory leaks. Obviously, not all events should be limited to just 10 listeners. The <code>emitter.setMaxListeners()</code> method allows the limit to be modified for this specific <code>EventEmitter</code> instance. The value can be set to <code>Infinity</code> (or <code>0</code>) for to indicate an unlimited number of listeners. </p> <p>Returns a reference to the <code>EventEmitter</code> so calls can be chained. </p> <h1>File System<span><a class="mark" href="#all_file_system" id="all_file_system">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</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 takes 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>const fs = require('fs'); fs.unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); });</code></pre> <p>Here is the synchronous version: </p> <pre><code>const 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', (err) => { if (err) throw err; console.log('renamed complete'); }); fs.stat('/tmp/world', (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', (err) => { if (err) throw err; fs.stat('/tmp/world', (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>The relative path to a filename can be used. Remember, however, that this path will be relative to <code>process.cwd()</code>. </p> <p>Most fs functions let you omit the callback argument. If you do, a default callback is used that rethrows errors. To get a trace to the original call site, set the <code>NODE_DEBUG</code> environment variable: </p> <pre><code>$ cat script.js function bad() { require('fs').readFile('/'); } bad(); $ env NODE_DEBUG=fs node script.js fs.js:66 throw err; ^ Error: EISDIR, read at rethrow (fs.js:61:21) at maybeCallback (fs.js:79:42) at Object.fs.readFile (fs.js:153:18) at bad (/path/to/script.js:2:17) at Object.<anonymous> (/path/to/script.js:5:1) <etc.></code></pre> <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>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"><code>fs.watch()</code></a>. </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><code>error</code> <span class="type">Error object</span></li> </div></ul> <p>Emitted when an error occurs. </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> <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_class_stream_readable">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>Class: fs.Stats<span><a class="mark" href="#all_class_fs_stats" id="all_class_fs_stats">#</a></span></h2> <p>Objects returned from <a href="#fs_fs_stat_path_callback"><code>fs.stat()</code></a>, <a href="#fs_fs_lstat_path_callback"><code>fs.lstat()</code></a> and <a href="#fs_fs_fstat_fd_callback"><code>fs.fstat()</code></a> 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 <a href="#fs_fs_lstat_path_callback"><code>fs.lstat()</code></a>)</li> <li><code>stats.isFIFO()</code></li> <li><code>stats.isSocket()</code></li> </ul> <p>For a regular file <a href="util.html#util_util_inspect_object_options"><code>util.inspect(stats)</code></a> 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, birthtime: Mon, 10 Oct 2011 23:24:11 GMT }</code></pre> <p>Please note that <code>atime</code>, <code>mtime</code>, <code>birthtime</code>, and <code>ctime</code> are instances of <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date"><code>Date</code></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"><code>getTime()</code></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 are 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> <h3>Stat Time Values<span><a class="mark" href="#all_stat_time_values" id="all_stat_time_values">#</a></span></h3> <p>The times in the stat object have the following semantics: </p> <ul> <li><code>atime</code> "Access Time" - Time when file data last accessed. Changed by the <code>mknod(2)</code>, <code>utimes(2)</code>, and <code>read(2)</code> system calls.</li> <li><code>mtime</code> "Modified Time" - Time when file data last modified. Changed by the <code>mknod(2)</code>, <code>utimes(2)</code>, and <code>write(2)</code> system calls.</li> <li><code>ctime</code> "Change Time" - Time when file status was last changed (inode data modification). Changed by the <code>chmod(2)</code>, <code>chown(2)</code>, <code>link(2)</code>, <code>mknod(2)</code>, <code>rename(2)</code>, <code>unlink(2)</code>, <code>utimes(2)</code>, <code>read(2)</code>, and <code>write(2)</code> system calls.</li> <li><code>birthtime</code> "Birth Time" - Time of file creation. Set once when the file is created. On filesystems where birthtime is not available, this field may instead hold either the <code>ctime</code> or <code>1970-01-01T00:00Z</code> (ie, unix epoch timestamp <code>0</code>). On Darwin and other FreeBSD variants, also set if the <code>atime</code> is explicitly set to an earlier value than the current <code>birthtime</code> using the <code>utimes(2)</code> system call.</li> </ul> <p>Prior to Node v0.12, the <code>ctime</code> held the <code>birthtime</code> on Windows systems. Note that as of v0.12, <code>ctime</code> is not "creation time", and on Unix systems, it never was. </p> <h2>Class: fs.WriteStream<span><a class="mark" href="#all_class_fs_writestream" id="all_class_fs_writestream">#</a></span></h2> <p><code>WriteStream</code> is a <a href="stream.html#stream_class_stream_writable">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>writeStream.bytesWritten<span><a class="mark" href="#all_writestream_byteswritten" id="all_writestream_byteswritten">#</a></span></h3> <p>The number of bytes written so far. Does not include data that is still queued for writing. </p> <h2>fs.access(path[, mode], callback)<span><a class="mark" href="#all_fs_access_path_mode_callback" id="all_fs_access_path_mode_callback">#</a></span></h2> <p>Tests a user's permissions for the file specified by <code>path</code>. <code>mode</code> is an optional integer that specifies the accessibility checks to be performed. The following constants define the possible values of <code>mode</code>. It is possible to create a mask consisting of the bitwise OR of two or more values. </p> <ul> <li><code>fs.F_OK</code> - File is visible to the calling process. This is useful for determining if a file exists, but says nothing about <code>rwx</code> permissions. Default if no <code>mode</code> is specified.</li> <li><code>fs.R_OK</code> - File can be read by the calling process.</li> <li><code>fs.W_OK</code> - File can be written by the calling process.</li> <li><code>fs.X_OK</code> - File can be executed by the calling process. This has no effect on Windows (will behave like <code>fs.F_OK</code>).</li> </ul> <p>The final argument, <code>callback</code>, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be populated. The following example checks if the file <code>/etc/passwd</code> can be read and written by the current process. </p> <pre><code>fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) { console.log(err ? 'no access!' : 'can read/write'); });</code></pre> <h2>fs.accessSync(path[, mode])<span><a class="mark" href="#all_fs_accesssync_path_mode" id="all_fs_accesssync_path_mode">#</a></span></h2> <p>Synchronous version of <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a>. This throws if any accessibility checks fail, and does nothing otherwise. </p> <h2>fs.appendFile(file, data[, options], callback)<span><a class="mark" href="#all_fs_appendfile_file_data_options_callback" id="all_fs_appendfile_file_data_options_callback">#</a></span></h2> <div class="signature"><ul> <li><code>file</code> <span class="type">String | Integer</span> filename or file descriptor</li> <li><code>data</code> <span class="type">String | Buffer</span></li> <li><code>options</code> <span class="type">Object | String</span><ul> <li><code>encoding</code> <span class="type">String | Null</span> default = <code>'utf8'</code></li> <li><code>mode</code> <span class="type">Number</span> default = <code>0o666</code></li> <li><code>flag</code> <span class="type">String</span> default = <code>'a'</code></li> </ul> </li> <li><code>callback</code> <span class="type">Function</span></li> </div></ul> <p>Asynchronously append data to a file, creating the file if it does not yet exist. <code>data</code> can be a string or a buffer. </p> <p>Example: </p> <pre><code>fs.appendFile('message.txt', 'data to append', (err) => { if (err) throw err; console.log('The "data to append" was appended to file!'); });</code></pre> <p>If <code>options</code> is a string, then it specifies the encoding. Example: </p> <pre><code>fs.appendFile('message.txt', 'data to append', 'utf8', callback);</code></pre> <p>Any specified file descriptor has to have been opened for appending. </p> <p><em>Note: Specified file descriptors will not be closed automatically.</em> </p> <h2>fs.appendFileSync(file, data[, options])<span><a class="mark" href="#all_fs_appendfilesync_file_data_options" id="all_fs_appendfilesync_file_data_options">#</a></span></h2> <p>The synchronous version of <a href="fs.html#fs_fs_appendfile_file_data_options_callback"><code>fs.appendFile()</code></a>. Returns <code>undefined</code>. </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). Returns <code>undefined</code>. </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). Returns <code>undefined</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). Returns <code>undefined</code>. </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 <a href="#fs_class_fs_readstream"><code>ReadStream</code></a> object. (See <a href="stream.html#stream_class_stream_readable">Readable Stream</a>). </p> <p>Be aware that, unlike the default value set for <code>highWaterMark</code> on a readable stream (16 kb), the stream returned by this method has a default value of 64 kb for the same parameter. </p> <p><code>options</code> is an object or string with the following defaults: </p> <pre><code>{ flags: 'r', encoding: null, fd: null, mode: 0o666, autoClose: true }</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 any one of those accepted by <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>. </p> <p>If <code>fd</code> is specified, <code>ReadStream</code> will ignore the <code>path</code> argument and will use the specified file descriptor. This means that no <code>'open'</code> event will be emitted. Note that <code>fd</code> should be blocking; non-blocking <code>fd</code>s should be passed to <a href="net.html#net_class_net_socket"><code>net.Socket</code></a>. </p> <p>If <code>autoClose</code> is false, then the file descriptor won't be closed, even if there's an error. It is your responsibility to close it and make sure there's no file descriptor leak. If <code>autoClose</code> is set to true (default behavior), on <code>error</code> or <code>end</code> the file descriptor will be closed automatically. </p> <p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was created. </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> <p>If <code>options</code> is a string, then it specifies the encoding. </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 <a href="#fs_class_fs_writestream"><code>WriteStream</code></a> object. (See <a href="stream.html#stream_class_stream_writable">Writable Stream</a>). </p> <p><code>options</code> is an object or string with the following defaults: </p> <pre><code>{ flags: 'w', defaultEncoding: 'utf8', fd: null, mode: 0o666 }</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>. The <code>defaultEncoding</code> can be any one of those accepted by <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>. </p> <p>Like <a href="#fs_class_fs_readstream"><code>ReadStream</code></a>, if <code>fd</code> is specified, <code>WriteStream</code> will ignore the <code>path</code> argument and will use the specified file descriptor. This means that no <code>'open'</code> event will be emitted. Note that <code>fd</code> should be blocking; non-blocking <code>fd</code>s should be passed to <a href="net.html#net_class_net_socket"><code>net.Socket</code></a>. </p> <p>If <code>options</code> is a string, then it specifies the encoding. </p> <h2>fs.exists(path, callback)<span><a class="mark" href="#all_fs_exists_path_callback" id="all_fs_exists_path_callback">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <a href="#fs_fs_stat_path_callback"><code>fs.stat()</code></a> or <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a> instead.</pre><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', (exists) => { console.log(exists ? 'it\'s there' : 'no passwd!'); });</code></pre> <p><code>fs.exists()</code> should not be used to check if a file exists before calling <code>fs.open()</code>. Doing so introduces a race condition since other processes may change the file's state between the two calls. Instead, user code should call <code>fs.open()</code> directly and handle the error raised if the file is non-existent. </p> <h2>fs.existsSync(path)<span><a class="mark" href="#all_fs_existssync_path" id="all_fs_existssync_path">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <a href="#fs_fs_statsync_path"><code>fs.statSync()</code></a> or <a href="#fs_fs_accesssync_path_mode"><code>fs.accessSync()</code></a> instead.</pre><p>Synchronous version of <a href="fs.html#fs_fs_exists_path_callback"><code>fs.exists()</code></a>. Returns <code>true</code> if the file exists, <code>false</code> otherwise. </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). Returns <code>undefined</code>. </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). Returns <code>undefined</code>. </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 <a href="fs.html#fs_fs_stat_path_callback"><code>stat()</code></a>, except that the file to be stat-ed is specified by the file descriptor <code>fd</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.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). Returns <code>undefined</code>. </p> <h2>fs.ftruncate(fd, len, callback)<span><a class="mark" href="#all_fs_ftruncate_fd_len_callback" id="all_fs_ftruncate_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.ftruncateSync(fd, len)<span><a class="mark" href="#all_fs_ftruncatesync_fd_len" id="all_fs_ftruncatesync_fd_len">#</a></span></h2> <p>Synchronous ftruncate(2). Returns <code>undefined</code>. </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> <p>Change the file timestamps of a file referenced by the supplied file descriptor. </p> <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>Synchronous version of <a href="#fs_fs_futimes_fd_atime_mtime_callback"><code>fs.futimes()</code></a>. Returns <code>undefined</code>. </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). Returns <code>undefined</code>. </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). Returns <code>undefined</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). Returns <code>undefined</code>. </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.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.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>0o777</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). Returns <code>undefined</code>. </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 flag 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 fails if <code>path</code> exists.</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 fails if <code>path</code> exists.</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 fails if <code>path</code> exists.</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 fails if <code>path</code> exists.</p> </li> </ul> <p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was created. It defaults to <code>0666</code>, readable and writeable. </p> <p>The callback gets two arguments <code>(err, fd)</code>. </p> <p>The exclusive flag <code>'x'</code> (<code>O_EXCL</code> flag in open(2)) ensures that <code>path</code> is newly created. On POSIX systems, <code>path</code> is considered to exist even if it is a symlink to a non-existent file. The exclusive flag may or may not work with network file systems. </p> <p><code>flags</code> can also be a number as documented by open(2); commonly used constants are available from <code>require('constants')</code>. On Windows, flags are translated to their equivalent ones where applicable, e.g. <code>O_WRONLY</code> to <code>FILE_GENERIC_WRITE</code>, or <code>O_EXCL|O_CREAT</code> to <code>CREATE_NEW</code>, as accepted by CreateFileW. </p> <p>On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. </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 version of <a href="#fs_fs_open_path_flags_mode_callback"><code>fs.open()</code></a>. Returns an integer representing the file descriptor. </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 the offset in the buffer to start writing at. </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.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.readFile(file[, options], callback)<span><a class="mark" href="#all_fs_readfile_file_options_callback" id="all_fs_readfile_file_options_callback">#</a></span></h2> <div class="signature"><ul> <li><code>file</code> <span class="type">String | Integer</span> filename or file descriptor</li> <li><code>options</code> <span class="type">Object | String</span><ul> <li><code>encoding</code> <span class="type">String | Null</span> default = <code>null</code></li> <li><code>flag</code> <span class="type">String</span> default = <code>'r'</code></li> </ul> </li> <li><code>callback</code> <span class="type">Function</span></li> </div></ul> <p>Asynchronously reads the entire contents of a file. Example: </p> <pre><code>fs.readFile('/etc/passwd', (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> <p>If <code>options</code> is a string, then it specifies the encoding. Example: </p> <pre><code>fs.readFile('/etc/passwd', 'utf8', callback);</code></pre> <p>Any specified file descriptor has to support reading. </p> <p><em>Note: Specified file descriptors will not be closed automatically.</em> </p> <h2>fs.readFileSync(file[, options])<span><a class="mark" href="#all_fs_readfilesync_file_options" id="all_fs_readfilesync_file_options">#</a></span></h2> <p>Synchronous version of <a href="#fs_fs_readfile_file_options_callback"><code>fs.readFile</code></a>. Returns the contents of the <code>file</code>. </p> <p>If the <code>encoding</code> option is specified then this function returns a string. Otherwise it returns a buffer. </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, (err, resolvedPath) => { if (err) throw err; console.log(resolvedPath); });</code></pre> <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 <a href="#fs_fs_read_fd_buffer_offset_length_position_callback"><code>fs.read()</code></a>. Returns the number of <code>bytesRead</code>. </p> <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. <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> <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). Returns <code>undefined</code>. </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). Returns <code>undefined</code>. </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"><code>fs.Stats</code></a> object. See the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> section below for more information. </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 <a href="#fs_class_fs_stats"><code>fs.Stats</code></a>. </p> <h2>fs.symlink(target, path[, type], callback)<span><a class="mark" href="#all_fs_symlink_target_path_type_callback" id="all_fs_symlink_target_path_type_callback">#</a></span></h2> <p>Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback. The <code>type</code> argument can be set to <code>'dir'</code>, <code>'file'</code>, or <code>'junction'</code> (default is <code>'file'</code>) and is only available 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>target</code> argument will automatically be normalized to absolute path. </p> <p>Here is an example below: </p> <pre><code>fs.symlink('./foo', './new-port');</code></pre> <p>It would create a symlic link named with "new-port" that points to "foo". </p> <h2>fs.symlinkSync(target, path[, type])<span><a class="mark" href="#all_fs_symlinksync_target_path_type" id="all_fs_symlinksync_target_path_type">#</a></span></h2> <p>Synchronous symlink(2). Returns <code>undefined</code>. </p> <h2>fs.truncate(path, len, callback)<span><a class="mark" href="#all_fs_truncate_path_len_callback" id="all_fs_truncate_path_len_callback">#</a></span></h2> <p>Asynchronous truncate(2). No arguments other than a possible exception are given to the completion callback. A file descriptor can also be passed as the first argument. In this case, <code>fs.ftruncate()</code> is called. </p> <h2>fs.truncateSync(path, len)<span><a class="mark" href="#all_fs_truncatesync_path_len" id="all_fs_truncatesync_path_len">#</a></span></h2> <p>Synchronous truncate(2). Returns <code>undefined</code>. </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). Returns <code>undefined</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> <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> <p><em>Note: <a href="#fs_fs_watch_filename_options_listener"><code>fs.watch()</code></a> is more efficient than <code>fs.watchFile()</code> and <code>fs.unwatchFile()</code>. <code>fs.watch()</code> should be used instead of <code>fs.watchFile()</code> and <code>fs.unwatchFile()</code> when possible.</em> </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> <p>Change file timestamps of the file referenced by the supplied path. </p> <p>Note: the arguments <code>atime</code> and <code>mtime</code> of the following related functions does follow the below rules: </p> <ul> <li>If the value is a numberable string like <code>'123456789'</code>, the value would get converted to corresponding number.</li> <li>If the value is <code>NaN</code> or <code>Infinity</code>, the value would get converted to <code>Date.now()</code>.</li> </ul> <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>Synchronous version of <a href="#fs_fs_futimes_fd_atime_mtime_callback"><code>fs.utimes()</code></a>. Returns <code>undefined</code>. </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> <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"><code>fs.FSWatcher</code></a>. </p> <p>The second argument is optional. The <code>options</code> if provided should be an object. The supported boolean members are <code>persistent</code> and <code>recursive</code>. <code>persistent</code> indicates whether the process should continue to run as long as files are being watched. <code>recursive</code> indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See Caveats below). </p> <p>The default is <code>{ persistent: true, recursive: false }</code>. </p> <p>The listener callback gets two arguments <code>(event, filename)</code>. <code>event</code> is either <code>'rename'</code> or <code>'change'</code>, and <code>filename</code> is the name of the file which triggered the event. </p> <h3>Caveats<span><a class="mark" href="#all_caveats_1" id="all_caveats_1">#</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> <p>The recursive option is only supported on OS X and Windows. </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, this uses <code>kqueue</code>.</li> <li>On OS X, this uses <code>kqueue</code> for files and 'FSEvents' for directories.</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 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', (event, filename) => { console.log(`event is: ${event}`); if (filename) { console.log(`filename provided: ${filename}`); } else { console.log('filename not provided'); } });</code></pre> <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> <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 <code>options</code> argument may be omitted. If provided, it should be an object. The <code>options</code> object may contain a boolean named <code>persistent</code> that indicates whether the process should continue to run as long as files are being watched. The <code>options</code> object may specify an <code>interval</code> property indicating 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', (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> <p><em>Note: when an <code>fs.watchFile</code> operation results in an <code>ENOENT</code> error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). In Windows, <code>blksize</code> and <code>blocks</code> fields will be <code>undefined</code>, instead of zero. If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.</em> </p> <p><em>Note: <a href="#fs_fs_watch_filename_options_listener"><code>fs.watch()</code></a> is more efficient than <code>fs.watchFile</code> and <code>fs.unwatchFile</code>. <code>fs.watch</code> should be used instead of <code>fs.watchFile</code> and <code>fs.unwatchFile</code> when possible.</em> </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>typeof position !== 'number'</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> <p>On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. </p> <h2>fs.write(fd, data[, position[, encoding]], callback)<span><a class="mark" href="#all_fs_write_fd_data_position_encoding_callback" id="all_fs_write_fd_data_position_encoding_callback">#</a></span></h2> <p>Write <code>data</code> to the file specified by <code>fd</code>. If <code>data</code> is not a Buffer instance then the value will be coerced to a string. </p> <p><code>position</code> refers to the offset from the beginning of the file where this data should be written. If <code>typeof position !== 'number'</code> the data will be written at the current position. See pwrite(2). </p> <p><code>encoding</code> is the expected string encoding. </p> <p>The callback will receive the arguments <code>(err, written, string)</code> where <code>written</code> specifies how many <em>bytes</em> the passed string required to be written. Note that bytes written is not the same as string characters. See <a href="buffer.html#buffer_class_method_buffer_bytelength_string_encoding"><code>Buffer.byteLength</code></a>. </p> <p>Unlike when writing <code>buffer</code>, the entire string must be written. No substring may be specified. This is because the byte offset of the resulting data may not be the same as the string offset. </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> <p>On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. </p> <h2>fs.writeFile(file, data[, options], callback)<span><a class="mark" href="#all_fs_writefile_file_data_options_callback" id="all_fs_writefile_file_data_options_callback">#</a></span></h2> <div class="signature"><ul> <li><code>file</code> <span class="type">String | Integer</span> filename or file descriptor</li> <li><code>data</code> <span class="type">String | Buffer</span></li> <li><code>options</code> <span class="type">Object | String</span><ul> <li><code>encoding</code> <span class="type">String | Null</span> default = <code>'utf8'</code></li> <li><code>mode</code> <span class="type">Number</span> default = <code>0o666</code></li> <li><code>flag</code> <span class="type">String</span> default = <code>'w'</code></li> </ul> </li> <li><code>callback</code> <span class="type">Function</span></li> </div></ul> <p>Asynchronously writes data to a file, replacing the file if it already exists. <code>data</code> can be a string or a buffer. </p> <p>The <code>encoding</code> option 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.js', (err) => { if (err) throw err; console.log('It\'s saved!'); });</code></pre> <p>If <code>options</code> is a string, then it specifies the encoding. Example: </p> <pre><code>fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);</code></pre> <p>Any specified file descriptor has to support writing. </p> <p>Note that it is unsafe to use <code>fs.writeFile</code> multiple times on the same file without waiting for the callback. For this scenario, <code>fs.createWriteStream</code> is strongly recommended. </p> <p><em>Note: Specified file descriptors will not be closed automatically.</em> </p> <h2>fs.writeFileSync(file, data[, options])<span><a class="mark" href="#all_fs_writefilesync_file_data_options" id="all_fs_writefilesync_file_data_options">#</a></span></h2> <p>The synchronous version of <a href="#fs_fs_writefile_file_data_options_callback"><code>fs.writeFile()</code></a>. Returns <code>undefined</code>. </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> <h2>fs.writeSync(fd, data[, position[, encoding]])<span><a class="mark" href="#all_fs_writesync_fd_data_position_encoding" id="all_fs_writesync_fd_data_position_encoding">#</a></span></h2> <p>Synchronous versions of <a href="#fs_fs_write_fd_buffer_offset_length_position_callback"><code>fs.write()</code></a>. Returns the number of bytes written. </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>Class: Buffer<span><a class="mark" href="#all_class_buffer_1" id="all_class_buffer_1">#</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>__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>__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>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 <a href="#globals_setinterval_cb_ms"><code>setInterval()</code></a>. 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> <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 <a href="#globals_settimeout_cb_ms"><code>setTimeout()</code></a>. The callback will not execute. </p> <h2>console<span><a class="mark" href="#all_console_1" id="all_console_1">#</a></span></h2> <!-- type=global --> <ul> <li>{Object}</li> </ul> <p>Used to print to stdout and stderr. See the <a href="console.html"><code>console</code></a> section. </p> <h2>exports<span><a class="mark" href="#all_exports" id="all_exports">#</a></span></h2> <!-- type=var --> <p>A reference to the <code>module.exports</code> that is shorter to type. See <a href="modules.html">module system documentation</a> for details on when to use <code>exports</code> and when to use <code>module.exports</code>. </p> <p><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> <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.js this is different. The top-level scope is not the global scope; <code>var something</code> inside an Node.js module will be local to that 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 used for defining what a module exports and makes available through <code>require()</code>. </p> <p><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>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"><code>process</code> object</a> section. </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.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> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><div class="signature"><ul> <li><span class="type">Object</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><strong>Deprecated</strong> In the past, this list has been used to load non-JavaScript modules into Node.js by compiling them on-demand. However, in practice, there are much better ways to do this, such as loading modules via some other Node.js program, or compiling them to JavaScript ahead of time. </p> <p>Since the Module system is locked, this feature will probably never go away. However, it may have subtle bugs and complexities that are best left untouched. </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> <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>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> <h1>HTTP<span><a class="mark" href="#all_http" id="all_http">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>To use the HTTP server and client one must <code>require('http')</code>. </p> <p>The HTTP interfaces in Node.js 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', 'host': 'mysite.com', '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.js'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> <p>See <a href="#http_message_headers"><code>message.headers</code></a> for details on how duplicate headers are handled. </p> <p>The raw headers as they were received are retained in the <code>rawHeaders</code> property, which is an array of <code>[key, value, key2, value2, ...]</code>. For example, the previous message header object might have a <code>rawHeaders</code> list like the following: </p> <pre><code>[ 'ConTent-Length', '123456', 'content-LENGTH', '123', 'content-type', 'text/plain', 'CONNECTION', 'keep-alive', 'Host', 'mysite.com', 'accepT', '*/*' ]</code></pre> <h2>Class: http.Agent<span><a class="mark" href="#all_class_http_agent" id="all_class_http_agent">#</a></span></h2> <p>The HTTP Agent is used for pooling sockets used in HTTP client requests. </p> <p>The 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.js's pool has the benefit of keep-alive when under load but still does not require developers to manually close the HTTP clients using KeepAlive. </p> <p>If you opt into using HTTP KeepAlive, you can create an Agent object with that flag set to <code>true</code>. (See the <a href="#http_new_agent_options">constructor options</a> below.) Then, the Agent will keep unused sockets in a pool for later use. They will be explicitly marked so as to not keep the Node.js process running. However, it is still a good idea to explicitly <a href="#net_socket_destroy"><code>destroy()</code></a> KeepAlive agents when they are no longer in use, so that the Sockets will be shut down. </p> <p>Sockets are removed from the agent's pool when the socket emits either a <code>'close'</code> event or a special <code>'agentRemove'</code> 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, (res) => { // Do stuff }).on('socket', (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({ hostname: 'localhost', port: 80, path: '/', agent: false // create a new agent just for this one request }, (res) => { // Do stuff with response })</code></pre> <h3>new Agent(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#all_new_agent_options" id="all_new_agent_options">#</a></span></h3> <div class="signature"><ul> <li><code>options</code> <span class="type">Object</span> Set of configurable options to set on the agent. Can have the following fields:<ul> <li><code>keepAlive</code> <span class="type">Boolean</span> Keep sockets around in a pool to be used by other requests in the future. Default = <code>false</code></li> <li><code>keepAliveMsecs</code> <span class="type">Integer</span> When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = <code>1000</code>. Only relevant if <code>keepAlive</code> is set to <code>true</code>.</li> <li><code>maxSockets</code> <span class="type">Number</span> Maximum number of sockets to allow per host. Default = <code>Infinity</code>.</li> <li><code>maxFreeSockets</code> <span class="type">Number</span> Maximum number of sockets to leave open in a free state. Only relevant if <code>keepAlive</code> is set to <code>true</code>. Default = <code>256</code>.</li> </ul> </li> </div></ul> <p>The default <a href="#http_http_globalagent"><code>http.globalAgent</code></a> that is used by <a href="http.html#http_http_request_options_callback"><code>http.request()</code></a> has all of these values set to their respective defaults. </p> <p>To configure any of them, you must create your own <a href="http.html#http_class_http_agent"><code>http.Agent</code></a> object. </p> <pre><code class="javascript">const http = require('http'); var keepAliveAgent = new http.Agent({ keepAlive: true }); options.agent = keepAliveAgent; http.request(options, onResponseCallback);</code></pre> <h3>agent.destroy()<span><a class="mark" href="#all_agent_destroy" id="all_agent_destroy">#</a></span></h3> <p>Destroy any sockets that are currently in use by the agent. </p> <p>It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, sockets may hang open for quite a long time before the server terminates them. </p> <h3>agent.freeSockets<span><a class="mark" href="#all_agent_freesockets" id="all_agent_freesockets">#</a></span></h3> <p>An object which contains arrays of sockets currently awaiting use by the Agent when HTTP KeepAlive is used. Do not modify. </p> <h3>agent.getName(options)<span><a class="mark" href="#all_agent_getname_options" id="all_agent_getname_options">#</a></span></h3> <p>Get a unique name for a set of request options, to determine whether a connection can be reused. In the http agent, this returns <code>host:port:localAddress</code>. In the https agent, the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability. </p> <h3>agent.maxFreeSockets<span><a class="mark" href="#all_agent_maxfreesockets" id="all_agent_maxfreesockets">#</a></span></h3> <p>By default set to 256. For Agents supporting HTTP KeepAlive, this sets the maximum number of sockets that will be left open in the free state. </p> <h3>agent.maxSockets<span><a class="mark" href="#all_agent_maxsockets" id="all_agent_maxsockets">#</a></span></h3> <p>By default set to Infinity. Determines how many concurrent sockets the agent can have open per origin. Origin is either a 'host:port' or 'host:port:localAddress' combination. </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> <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> <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 <a href="http.html#http_http_request_options_callback"><code>http.request()</code></a>. 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 <a href="#http_http_incomingmessage"><code>http.IncomingMessage</code></a>. </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. </p> <p>If no <code>'response'</code> handler is added, then the response will be entirely discarded. However, if you add a <code>'response'</code> event handler, then you <strong>must</strong> consume the data from the response object, either by calling <code>response.read()</code> whenever there is a <code>'readable'</code> event, or by adding a <code>'data'</code> handler, or by calling the <code>.resume()</code> method. Until the data is consumed, the <code>'end'</code> event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error. </p> <p>Note: Node.js 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_class_stream_writable">Writable Stream</a> interface. This is an <a href="events.html#events_class_events_eventemitter"><code>EventEmitter</code></a> with the following events: </p> <h3>Event: 'abort'<span><a class="mark" href="#all_event_abort" id="all_event_abort">#</a></span></h3> <p><code>function () { }</code> </p> <p>Emitted when the request has been aborted by the client. This event is only emitted on the first call to <code>abort()</code>. </p> <h3>Event: 'connect'<span><a class="mark" href="#all_event_connect" id="all_event_connect">#</a></span></h3> <p><code>function (response, socket, head) { }</code> </p> <p>Emitted each time a server responds to a request with a <code>CONNECT</code> method. If this event isn't being listened for, clients receiving a <code>CONNECT</code> 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>const http = require('http'); const net = require('net'); const url = require('url'); // Create an HTTP tunneling proxy var proxy = http.createServer( (req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('okay'); }); proxy.on('connect', (req, cltSocket, head) => { // connect to an origin server var srvUrl = url.parse(`http://${req.url}`); var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => { cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-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', () => { // make a request to a tunneling proxy var options = { port: 1337, hostname: '127.0.0.1', method: 'CONNECT', path: 'www.google.com:80' }; var req = http.request(options); req.end(); req.on('connect', (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', (chunk) => { console.log(chunk.toString()); }); socket.on('end', () => { proxy.close(); }); }); });</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>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 <a href="#http_http_incomingmessage"><code>http.IncomingMessage</code></a>. </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: 'upgrade'<span><a class="mark" href="#all_event_upgrade" id="all_event_upgrade">#</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>const http = require('http'); // Create an HTTP server var srv = http.createServer( (req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('okay'); }); srv.on('upgrade', (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', () => { // make a request var options = { port: 1337, hostname: '127.0.0.1', headers: { 'Connection': 'Upgrade', 'Upgrade': 'websocket' } }; var req = http.request(options); req.end(); req.on('upgrade', (res, socket, upgradeHead) => { console.log('got upgraded!'); socket.end(); process.exit(0); }); });</code></pre> <h3>request.abort()<span><a class="mark" href="#all_request_abort" id="all_request_abort">#</a></span></h3> <p>Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed. </p> <h3>request.end([data][, encoding][, callback])<span><a class="mark" href="#all_request_end_data_encoding_callback" id="all_request_end_data_encoding_callback">#</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 <a href="#http_response_write_chunk_encoding_callback"><code>response.write(data, encoding)</code></a> followed by <code>request.end(callback)</code>. </p> <p>If <code>callback</code> is specified, it will be called when the request stream is finished. </p> <h3>request.flushHeaders()<span><a class="mark" href="#all_request_flushheaders" id="all_request_flushheaders">#</a></span></h3> <p>Flush the request headers. </p> <p>For efficiency reasons, Node.js normally buffers the request headers until you call <code>request.end()</code> or write the first chunk of request data. It then tries hard to pack the request headers and data into a single TCP packet. </p> <p>That's usually what you want (it saves a TCP round-trip) but not when the first data isn't sent until possibly much later. <code>request.flushHeaders()</code> lets you bypass the optimization and kickstart the request. </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"><code>socket.setNoDelay()</code></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"><code>socket.setKeepAlive()</code></a> will be called. </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_socket_settimeout_timeout_callback"><code>socket.setTimeout()</code></a> will be called. </p> <ul> <li><code>timeout</code> {Number} Milliseconds before a request is considered to be timed out.</li> <li><code>callback</code> {Function} Optional function to be called when a timeout occurs. Same as binding to the <code>timeout</code> event.</li> </ul> <h3>request.write(chunk[, encoding][, callback])<span><a class="mark" href="#all_request_write_chunk_encoding_callback" id="all_request_write_chunk_encoding_callback">#</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"><code>Buffer</code></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> <p>The <code>callback</code> argument is optional and will be called when this chunk of data is flushed. </p> <p>Returns <code>request</code>. </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"><code>EventEmitter</code></a> with the following events: </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 <a href="#http_response_writecontinue"><code>response.writeContinue()</code></a> 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: 'clientError'<span><a class="mark" href="#all_event_clienterror" id="all_event_clienterror">#</a></span></h3> <p><code>function (exception, socket) { }</code> </p> <p>If a client connection emits an <code>'error'</code> event, it will be forwarded here. </p> <p><code>socket</code> is the <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> object that the error originated from. </p> <h3>Event: 'close'<span><a class="mark" href="#all_event_close_2" id="all_event_close_2">#</a></span></h3> <p><code>function () { }</code> </p> <p>Emitted when the server closes. </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 <code>CONNECT</code> method. If this event isn't listened for, then clients requesting a <code>CONNECT</code> 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: 'connection'<span><a class="mark" href="#all_event_connection" id="all_event_connection">#</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 <a href="net.html#net_class_net_socket"><code>net.Socket</code></a>. Usually users will not want to access this event. In particular, the socket will not emit <code>'readable'</code> events because of how the protocol parser attaches to the socket. The <code>socket</code> can also be accessed at <code>request.connection</code>. </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 <a href="#http_http_incomingmessage"><code>http.IncomingMessage</code></a> and <code>response</code> is an instance of <a href="#http_class_http_serverresponse"><code>http.ServerResponse</code></a>. </p> <h3>Event: 'upgrade'<span><a class="mark" href="#all_event_upgrade_1" id="all_event_upgrade_1">#</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>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. See <a href="net.html#net_server_close_callback"><code>net.Server.close()</code></a>. </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. The last parameter <code>callback</code> will be added as a listener for the <code>'listening'</code> event. See also <a href="net.html#net_server_listen_handle_callback"><code>net.Server.listen()</code></a>. </p> <p>Returns <code>server</code>. </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. The last parameter <code>callback</code> will be added as a listener for the <code>'listening'</code> event. See also <a href="net.html#net_server_listen_path_callback"><code>net.Server.listen(path)</code></a>. </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 <code>port</code> and <code>hostname</code>. If the <code>hostname</code> is omitted, the server will accept connections on any IPv6 address (<code>::</code>) when IPv6 is available, or any IPv4 address (<code>0.0.0.0</code>) otherwise. A port value of zero will assign a random port. </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 <code>'listening'</code> event. See also <a href="net.html#net_server_listen_port_hostname_backlog_callback"><code>net.Server.listen(port)</code></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> <h3>server.setTimeout(msecs, callback)<span><a class="mark" href="#all_server_settimeout_msecs_callback" id="all_server_settimeout_msecs_callback">#</a></span></h3> <div class="signature"><ul> <li><code>msecs</code> <span class="type">Number</span></li> <li><code>callback</code> <span class="type">Function</span></li> </div></ul> <p>Sets the timeout value for sockets, and emits a <code>'timeout'</code> event on the Server object, passing the socket as an argument, if a timeout occurs. </p> <p>If there is a <code>'timeout'</code> event listener on the Server object, then it will be called with the timed-out socket as an argument. </p> <p>By default, the Server's timeout value is 2 minutes, and sockets are destroyed automatically if they time out. However, if you assign a callback to the Server's <code>'timeout'</code> event, then you are responsible for handling socket timeouts. </p> <p>Returns <code>server</code>. </p> <h3>server.timeout<span><a class="mark" href="#all_server_timeout" id="all_server_timeout">#</a></span></h3> <div class="signature"><ul> <li><span class="type">Number</span> Default = 120000 (2 minutes)</li> </div></ul> <p>The number of milliseconds of inactivity before a socket is presumed to have timed out. </p> <p>Note that the socket timeout logic is set up on connection, so changing this value only affects <em>new</em> connections to the server, not any existing connections. </p> <p>Set to 0 to disable any kind of automatic timeout behavior on incoming connections. </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_class_stream_writable">Writable Stream</a> interface. This is an <a href="events.html#events_class_events_eventemitter"><code>EventEmitter</code></a> with the following events: </p> <h3>Event: 'close'<span><a class="mark" href="#all_event_close_3" id="all_event_close_3">#</a></span></h3> <p><code>function () { }</code> </p> <p>Indicates that the underlying connection was terminated before <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> was called or able to flush. </p> <h3>Event: 'finish'<span><a class="mark" href="#all_event_finish" id="all_event_finish">#</a></span></h3> <p><code>function () { }</code> </p> <p>Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet. </p> <p>After this event, no more events will be emitted on the response object. </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> <p>Attempting to set a trailer field name that contains invalid characters will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown. </p> <h3>response.end([data][, encoding][, callback])<span><a class="mark" href="#all_response_end_data_encoding_callback" id="all_response_end_data_encoding_callback">#</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 <a href="#http_response_write_chunk_encoding_callback"><code>response.write(data, encoding)</code></a> followed by <code>response.end(callback)</code>. </p> <p>If <code>callback</code> is specified, it will be called when the response stream is finished. </p> <h3>response.finished<span><a class="mark" href="#all_response_finished" id="all_response_finished">#</a></span></h3> <p>Boolean value that indicates whether the response has completed. Starts as <code>false</code>. After <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> executes, the value will be <code>true</code>. </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.headersSent<span><a class="mark" href="#all_response_headerssent" id="all_response_headerssent">#</a></span></h3> <p>Boolean (read-only). True if headers were sent, false otherwise. </p> <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.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.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> <p>Attempting to set a header field name that contains invalid characters will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown. </p> <h3>response.setTimeout(msecs, callback)<span><a class="mark" href="#all_response_settimeout_msecs_callback" id="all_response_settimeout_msecs_callback">#</a></span></h3> <div class="signature"><ul> <li><code>msecs</code> <span class="type">Number</span></li> <li><code>callback</code> <span class="type">Function</span></li> </div></ul> <p>Sets the Socket's timeout value to <code>msecs</code>. If a callback is provided, then it is added as a listener on the <code>'timeout'</code> event on the response object. </p> <p>If no <code>'timeout'</code> listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If you assign a handler on the request, the response, or the server's <code>'timeout'</code> events, then it is your responsibility to handle timed out sockets. </p> <p>Returns <code>response</code>. </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 <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> 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.statusMessage<span><a class="mark" href="#all_response_statusmessage" id="all_response_statusmessage">#</a></span></h3> <p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly), this property controls the status message that will be sent to the client when the headers get flushed. If this is left as <code>undefined</code> then the standard message for the status code will be used. </p> <p>Example: </p> <pre><code>response.statusMessage = 'Not found';</code></pre> <p>After response header was sent to the client, this property indicates the status message which was sent out. </p> <h3>response.write(chunk[, encoding][, callback])<span><a class="mark" href="#all_response_write_chunk_encoding_callback" id="all_response_write_chunk_encoding_callback">#</a></span></h3> <p>If this method is called and <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> 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>. The last parameter <code>callback</code> will be called when this chunk of data is flushed. </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 <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, it will send the buffered header information and the first body to the client. The second time <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, Node.js 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 free again. </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"><code>'checkContinue'</code></a> event on <code>Server</code>. </p> <h3>response.writeHead(statusCode[, statusMessage][, headers])<span><a class="mark" href="#all_response_writehead_statuscode_statusmessage_headers" id="all_response_writehead_statuscode_statusmessage_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>statusMessage</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 <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> is called. </p> <p>If you call <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> or <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> 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.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not. </p> <h2>Class: http.IncomingMessage<span><a class="mark" href="#all_class_http_incomingmessage" id="all_class_http_incomingmessage">#</a></span></h2> <p>An <code>IncomingMessage</code> object is created by <a href="http.html#http_class_http_server"><code>http.Server</code></a> or <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> and passed as the first argument to the <code>'request'</code> and <code>'response'</code> event respectively. It may be used to access response status, headers and data. </p> <p>It implements the <a href="stream.html#stream_class_stream_readable">Readable Stream</a> interface, as well as the following additional events, methods, and properties. </p> <h3>Event: 'close'<span><a class="mark" href="#all_event_close_4" id="all_event_close_4">#</a></span></h3> <p><code>function () { }</code> </p> <p>Indicates that the underlying connection was closed. Just like <code>'end'</code>, this event occurs only once per response. </p> <h3>message.headers<span><a class="mark" href="#all_message_headers" id="all_message_headers">#</a></span></h3> <p>The request/response headers object. </p> <p>Key-value pairs 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> <p>Duplicates in raw headers are handled in the following ways, depending on the header name: </p> <ul> <li>Duplicates of <code>age</code>, <code>authorization</code>, <code>content-length</code>, <code>content-type</code>, <code>etag</code>, <code>expires</code>, <code>from</code>, <code>host</code>, <code>if-modified-since</code>, <code>if-unmodified-since</code>, <code>last-modified</code>, <code>location</code>, <code>max-forwards</code>, <code>proxy-authorization</code>, <code>referer</code>, <code>retry-after</code>, or <code>user-agent</code> are discarded.</li> <li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li> <li>For all other headers, the values are joined together with ', '.</li> </ul> <h3>message.httpVersion<span><a class="mark" href="#all_message_httpversion" id="all_message_httpversion">#</a></span></h3> <p>In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either <code>'1.1'</code> or <code>'1.0'</code>. </p> <p>Also <code>response.httpVersionMajor</code> is the first integer and <code>response.httpVersionMinor</code> is the second. </p> <h3>message.method<span><a class="mark" href="#all_message_method" id="all_message_method">#</a></span></h3> <p><strong>Only valid for request obtained from <a href="http.html#http_class_http_server"><code>http.Server</code></a>.</strong> </p> <p>The request method as a string. Read only. Example: <code>'GET'</code>, <code>'DELETE'</code>. </p> <h3>message.rawHeaders<span><a class="mark" href="#all_message_rawheaders" id="all_message_rawheaders">#</a></span></h3> <p>The raw request/response headers list exactly as they were received. </p> <p>Note that the keys and values are in the same list. It is <em>not</em> a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. </p> <p>Header names are not lowercased, and duplicates are not merged. </p> <pre><code>// Prints something like: // // [ 'user-agent', // 'this is invalid because there can be only one', // 'User-Agent', // 'curl/7.22.0', // 'Host', // '127.0.0.1:8000', // 'ACCEPT', // '*/*' ] console.log(request.rawHeaders);</code></pre> <h3>message.rawTrailers<span><a class="mark" href="#all_message_rawtrailers" id="all_message_rawtrailers">#</a></span></h3> <p>The raw request/response trailer keys and values exactly as they were received. Only populated at the <code>'end'</code> event. </p> <h3>message.setTimeout(msecs, callback)<span><a class="mark" href="#all_message_settimeout_msecs_callback" id="all_message_settimeout_msecs_callback">#</a></span></h3> <div class="signature"><ul> <li><code>msecs</code> <span class="type">Number</span></li> <li><code>callback</code> <span class="type">Function</span></li> </div></ul> <p>Calls <code>message.connection.setTimeout(msecs, callback)</code>. </p> <p>Returns <code>message</code>. </p> <h3>message.statusCode<span><a class="mark" href="#all_message_statuscode" id="all_message_statuscode">#</a></span></h3> <p><strong>Only valid for response obtained from <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a>.</strong> </p> <p>The 3-digit HTTP response status code. E.G. <code>404</code>. </p> <h3>message.statusMessage<span><a class="mark" href="#all_message_statusmessage" id="all_message_statusmessage">#</a></span></h3> <p><strong>Only valid for response obtained from <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a>.</strong> </p> <h3>message.socket<span><a class="mark" href="#all_message_socket" id="all_message_socket">#</a></span></h3> <p>The <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> object associated with the connection. </p> <p>With HTTPS support, use <a href="tls.html#tls_tlssocket_getpeercertificate_detailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the client's authentication details. </p> <p>The HTTP response status message (reason phrase). E.G. <code>OK</code> or <code>Internal Server Error</code>. </p> <h3>message.trailers<span><a class="mark" href="#all_message_trailers" id="all_message_trailers">#</a></span></h3> <p>The request/response trailers object. Only populated at the <code>'end'</code> event. </p> <h3>message.url<span><a class="mark" href="#all_message_url" id="all_message_url">#</a></span></h3> <p><strong>Only valid for request obtained from <a href="http.html#http_class_http_server"><code>http.Server</code></a>.</strong> </p> <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> <h2>http.METHODS<span><a class="mark" href="#all_http_methods" id="all_http_methods">#</a></span></h2> <div class="signature"><ul> <li><span class="type">Array</span></li> </div></ul> <p>A list of the HTTP methods that are supported by the parser. </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.createClient([port][, host])<span><a class="mark" href="#all_http_createclient_port_host" id="all_http_createclient_port_host">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <a href="http.html#http_http_request_options_callback"><code>http.request()</code></a> instead.</pre><p>Constructs a new HTTP client. <code>port</code> and <code>host</code> refer to the server to be connected to. </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 instance of <a href="http.html#http_class_http_server"><code>http.Server</code></a>. </p> <p>The <code>requestListener</code> is a function which is automatically added to the <code>'request'</code> event. </p> <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.js provides this convenience method. The only difference between this method and <a href="http.html#http_http_request_options_callback"><code>http.request()</code></a> 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', (res) => { console.log(`Got response: ${res.statusCode}`); // consume response body res.resume(); }).on('error', (e) => { console.log(`Got error: ${e.message}`); });</code></pre> <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>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.js 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"><code>url.parse()</code></a>. </p> <p>Options: </p> <ul> <li><code>protocol</code>: Protocol to use. Defaults to <code>'http:'</code>.</li> <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>: Alias for <code>host</code>. To support <a href="url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost"><code>url.parse()</code></a> <code>hostname</code> is preferred over <code>host</code>.</li> <li><code>family</code>: IP address family to use when resolving <code>host</code> and <code>hostname</code>. Valid values are <code>4</code> or <code>6</code>. When unspecified, both IP v4 and v6 will be used.</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>. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future.</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"><code>Agent</code></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"><code>http.globalAgent</code></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 optional <code>callback</code> parameter will be added as a one time listener for the <code>'response'</code> event. </p> <p><code>http.request()</code> returns an instance of the <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> 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 postData = querystring.stringify({ 'msg' : 'Hello World!' }); var options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': postData.length } }; var req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.') }) }); req.on('error', (e) => { console.log(`problem with request: ${e.message}`); }); // write data to request body req.write(postData); 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. As with all <code>'error'</code> events, if no listeners are registered the error will be thrown. </p> <p>There are a few special headers that should be noted. </p> <ul> <li><p>Sending a 'Connection: keep-alive' will notify Node.js 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> <h1>HTTPS<span><a class="mark" href="#all_https" id="all_https">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a separate module. </p> <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"><code>http.Agent</code></a>. See <a href="#https_https_request_options_callback"><code>https.request()</code></a> for more information. </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 <a href="http.html#http_class_http_server"><code>http.Server</code></a>. See <a href="http.html#http_class_http_server"><code>http.Server</code></a> for more information. </p> <h3>server.setTimeout(msecs, callback)<span><a class="mark" href="#all_server_settimeout_msecs_callback_1" id="all_server_settimeout_msecs_callback_1">#</a></span></h3> <p>See <a href="http.html#http_server_settimeout_msecs_callback"><code>http.Server#setTimeout()</code></a>. </p> <h3>server.timeout<span><a class="mark" href="#all_server_timeout_1" id="all_server_timeout_1">#</a></span></h3> <p>See <a href="http.html#http_server_timeout"><code>http.Server#timeout</code></a>. </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"><code>tls.createServer()</code></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/ const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; https.createServer(options, (req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000);</code></pre> <p>Or </p> <pre><code>const https = require('https'); const fs = require('fs'); const options = { pfx: fs.readFileSync('server.pfx') }; https.createServer(options, (req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000);</code></pre> <h3>server.close([callback])<span><a class="mark" href="#all_server_close_callback_1" id="all_server_close_callback_1">#</a></span></h3> <p>See <a href="http.html#http_server_close_callback"><code>http.close()</code></a> for details. </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> <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> <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>See <a href="http.html#http_server_listen_port_hostname_backlog_callback"><code>http.listen()</code></a> for details. </p> <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 <a href="http.html#http_http_get_options_callback"><code>http.get()</code></a> 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_url_parse_urlstr_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>. </p> <p>Example: </p> <pre><code>const https = require('https'); https.get('https://encrypted.google.com/', (res) => { console.log('statusCode: ', res.statusCode); console.log('headers: ', res.headers); res.on('data', (d) => { process.stdout.write(d); }); }).on('error', (e) => { console.error(e); });</code></pre> <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"><code>https.Agent</code></a> for all HTTPS client requests. </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_url_parse_urlstr_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>. </p> <p>All options from <a href="http.html#http_http_request_options_callback"><code>http.request()</code></a> are valid. </p> <p>Example: </p> <pre><code>const https = require('https'); var options = { hostname: 'encrypted.google.com', port: 443, path: '/', method: 'GET' }; var req = https.request(options, (res) => { console.log('statusCode: ', res.statusCode); console.log('headers: ', res.headers); res.on('data', (d) => { process.stdout.write(d); }); }); req.end(); req.on('error', (e) => { console.error(e); });</code></pre> <p>The options argument has the following 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>: Alias for <code>host</code>. To support <code>url.parse()</code> <code>hostname</code> is preferred over <code>host</code>.</li> <li><code>family</code>: IP address family to use when resolving <code>host</code> and <code>hostname</code>. Valid values are <code>4</code> or <code>6</code>. When unspecified, both IP v4 and v6 will be used.</li> <li><code>port</code>: Port of remote server. Defaults to 443.</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>. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future.</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"><code>Agent</code></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"><code>globalAgent</code></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_callback"><code>tls.connect()</code></a> can also be specified. However, a <a href="#https_https_globalagent"><code>globalAgent</code></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>: A string, <code>Buffer</code> or array of strings or <code>Buffer</code>s of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.</li> <li><code>ciphers</code>: A string describing the ciphers to use or exclude. Consult <a href="https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">https://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>true</code>.</li> <li><code>secureProtocol</code>: The SSL method to use, e.g. <code>SSLv3_method</code> to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant <a href="https://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS"><code>SSL_METHODS</code></a>.</li> </ul> <p>In order to specify these options, use a custom <a href="#https_class_https_agent"><code>Agent</code></a>. </p> <p>Example: </p> <pre><code>var options = { hostname: '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, (res) => { ... }</code></pre> <p>Alternatively, opt out of connection pooling by not using an <code>Agent</code>. </p> <p>Example: </p> <pre><code>var options = { hostname: '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, (res) => { ... }</code></pre> <h1>Modules<span><a class="mark" href="#all_modules" id="all_modules">#</a></span></h1> <pre class="api_stability_3">Stability: 3 - Locked</pre><!--name=module--> <p>Node.js has a simple module loading system. In Node.js, 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>const 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>const 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 add functions and objects to the root of your module, you can add them to the special <code>exports</code> object. </p> <p>Variables local to the module will be private, as though the module was wrapped in a function. In this example the variable <code>PI</code> is private to <code>circle.js</code>. </p> <p>If you want the root of your module's export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to <code>module.exports</code> instead of <code>exports</code>. </p> <p>Below, <code>bar.js</code> makes use of the <code>square</code> module, which exports a constructor: </p> <pre><code>const square = require('./square.js'); var mySquare = square(2); console.log(`The area of my square is ${mySquare.area()}`);</code></pre> <p>The <code>square</code> module is defined in <code>square.js</code>: </p> <pre><code>// assigning to exports will not modify module, must use module.exports module.exports = function(width) { return { area: function() { return width * width; } }; }</code></pre> <p>The module system is implemented in the <code>require("module")</code> module. </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.js, <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.js's <code>require()</code> function were designed to be general enough to support a number of reasonable 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.js 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.js 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.js 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.js 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> <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.json is a file, parse X.json to a JavaScript Object. STOP 4. 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.json is a file, parse X/index.json to a JavaScript object. STOP 4. 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 I = count of PARTS - 1 3. let DIRS = [] 4. while I >= 0, 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 5. return DIRS</code></pre> <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>Core Modules<span><a class="mark" href="#all_core_modules" id="all_core_modules">#</a></span></h2> <!--type=misc--> <p>Node.js 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 within Node.js's source and are located 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>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 have finished executing 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; const 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; const 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'); const a = require('./a.js'); const 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 <code>exports</code> 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>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.js will attempt to load the required filename with the added extensions: <code>.js</code>, <code>.json</code>, and finally <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 required 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 required 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 must either be 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 <a href="errors.html#errors_class_error"><code>Error</code></a> with its <code>code</code> property set to <code>'MODULE_NOT_FOUND'</code>. </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.js's awareness of package.json files. </p> <p>If there is no package.json file present in the directory, then Node.js 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>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.js starts at the parent directory of the current module, and adds <code>/node_modules</code>, and attempts to load the module from that location. Node will not append <code>node_modules</code> to a path already ending in <code>node_modules</code>. </p> <p>If it is not found there, then it moves to the parent directory, and so on, until the root of the file system 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.js 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> <p>You can require specific files or sub modules distributed with a module by including a path suffix after the module name. For instance <code>require('example-module/path/to/file')</code> would resolve <code>path/to/file</code> relative to where <code>example-module</code> is located. The suffixed path follows the same module resolution semantics. </p> <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.js 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><code>NODE_PATH</code> was originally created to support loading modules from varying paths before the current <a href="#modules_all_together">module resolution</a> algorithm was frozen. </p> <p><code>NODE_PATH</code> is still supported, but is less necessary now that the Node.js ecosystem has settled on a convention for locating dependent modules. Sometimes deployments that rely on <code>NODE_PATH</code> show surprising behavior when people are unaware that <code>NODE_PATH</code> must be set. Sometimes a module's dependencies change, causing a different version (or even a different module) to be loaded as the <code>NODE_PATH</code> is searched. </p> <p>Additionally, Node.js 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.js's configured <code>node_prefix</code>. </p> <p>These are mostly for historic reasons. <strong>You are highly encouraged to place your dependencies locally in <code>node_modules</code> folders.</strong> They will be loaded faster, and more reliably. </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. For convenience, <code>module.exports</code> is also accessible via the <code>exports</code> module-global. <code>module</code> isn't actually a global but rather local to each module. </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> <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>module.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>. Note that assigning the desired object to <code>exports</code> will simply rebind the local <code>exports</code> variable, which is probably not what you want to do. </p> <p>For example suppose we were making a module called <code>a.js</code> </p> <pre><code>const EventEmitter = require('events'); module.exports = new EventEmitter(); // Do some work, and after some time emit // the 'ready' event from the module itself. setTimeout(() => { module.exports.emit('ready'); }, 1000);</code></pre> <p>Then in another file we could do </p> <pre><code>const a = require('./a'); a.on('ready', () => { 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(() => { module.exports = { a: 'hello' }; }, 0);</code></pre> <p>y.js: </p> <pre><code>const x = require('./x'); console.log(x.a);</code></pre> <h4>exports alias<span><a class="mark" href="#all_exports_alias" id="all_exports_alias">#</a></span></h4> <p>The <code>exports</code> variable that is available within a module starts as a reference to <code>module.exports</code>. As with any variable, if you assign a new value to it, it is no longer bound to the previous value. </p> <p>To illustrate the behavior, imagine this hypothetical implementation of <code>require()</code>: </p> <pre><code>function require(...) { // ... function (module, exports) { // Your module code here exports = some_func; // re-assigns exports, exports is no longer // a shortcut, and nothing is exported. module.exports = some_func; // makes your module export 0 } (module, module.exports); return module; }</code></pre> <p>As a guideline, if the relationship between <code>exports</code> and <code>module.exports</code> seems like magic to you, ignore <code>exports</code> and only use <code>module.exports</code>. </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.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.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 first required this one. </p> <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>module.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>module.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> <h1>net<span><a class="mark" href="#all_net" id="all_net">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>The <code>net</code> module provides you with an asynchronous network wrapper. It contains functions for creating both servers and clients (called streams). You can include this module with <code>require('net');</code>. </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 local server. </p> <p><code>net.Server</code> is an <a href="events.html#events_class_events_eventemitter"><code>EventEmitter</code></a> with the following events: </p> <h3>Event: 'close'<span><a class="mark" href="#all_event_close_5" id="all_event_close_5">#</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: 'connection'<span><a class="mark" href="#all_event_connection_1" id="all_event_connection_1">#</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: '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 <a href="#net_event_close"><code>'close'</code></a> event will be called directly following this event. See example in discussion of <code>server.listen</code>. </p> <h3>Event: 'listening'<span><a class="mark" href="#all_event_listening_3" id="all_event_listening_3">#</a></span></h3> <p>Emitted when the server has been bound after calling <code>server.listen</code>. </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. 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((socket) => { socket.end('goodbye\n'); }); // grab a random port. server.listen(() => { 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.close([callback])<span><a class="mark" href="#all_server_close_callback_2" id="all_server_close_callback_2">#</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 <a href="#net_event_close"><code>'close'</code></a> event. The optional <code>callback</code> will be called once the <code>'close'</code> event occurs. Unlike that event, it will be called with an Error as its only argument if the server was not open when it was closed. </p> <h3>server.connections<span><a class="mark" href="#all_server_connections" id="all_server_connections">#</a></span></h3> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <a href="#net_server_getconnections_callback"><code>server.getConnections</code></a> instead.</pre><p>The number of concurrent connections on the server. </p> <p>This becomes <code>null</code> when sending a socket to a child with <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>. To poll forks and get current number of active connections use asynchronous <code>server.getConnections</code> instead. </p> <h3>server.getConnections(callback)<span><a class="mark" href="#all_server_getconnections_callback" id="all_server_getconnections_callback">#</a></span></h3> <p>Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks. </p> <p>Callback should take two arguments <code>err</code> and <code>count</code>. </p> <h3>server.listen(handle[, backlog][, callback])<span><a class="mark" href="#all_server_listen_handle_backlog_callback" id="all_server_listen_handle_backlog_callback">#</a></span></h3> <div class="signature"><ul> <li><code>handle</code> <span class="type">Object</span></li> <li><code>backlog</code> <span class="type">Number</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="#net_event_listening"><code>'listening'</code></a> event will be emitted. The last parameter <code>callback</code> will be added as a listener for the <a href="#net_event_listening"><code>'listening'</code></a> event. </p> <p>The parameter <code>backlog</code> behaves the same as in [<code>server.listen(port, \[host\], \[backlog\], \[callback\])</code>][]. </p> <h3>server.listen(options[, callback])<span><a class="mark" href="#all_server_listen_options_callback" id="all_server_listen_options_callback">#</a></span></h3> <div class="signature"><ul> <li><code>options</code> <span class="type">Object</span> - Required. Supports the following properties:<ul> <li><code>port</code> <span class="type">Number</span> - Optional.</li> <li><code>host</code> <span class="type">String</span> - Optional.</li> <li><code>backlog</code> <span class="type">Number</span> - Optional.</li> <li><code>path</code> <span class="type">String</span> - Optional.</li> <li><code>exclusive</code> <span class="type">Boolean</span> - Optional.</li> </ul> </li> <li><code>callback</code> <span class="type">Function</span> - Optional.</li> </div></ul> <p>The <code>port</code>, <code>host</code>, and <code>backlog</code> properties of <code>options</code>, as well as the optional callback function, behave as they do on a call to [<code>server.listen(port, \[host\], \[backlog\], \[callback\])</code>][]. Alternatively, the <code>path</code> option can be used to specify a UNIX socket. </p> <p>If <code>exclusive</code> is <code>false</code> (default), then cluster workers will use the same underlying handle, allowing connection handling duties to be shared. When <code>exclusive</code> is <code>true</code>, the handle is not shared, and attempted port sharing results in an error. An example which listens on an exclusive port is shown below. </p> <pre><code>server.listen({ host: 'localhost', port: 80, exclusive: true });</code></pre> <h3>server.listen(path[, backlog][, callback])<span><a class="mark" href="#all_server_listen_path_backlog_callback" id="all_server_listen_path_backlog_callback">#</a></span></h3> <div class="signature"><ul> <li><code>path</code> <span class="type">String</span></li> <li><code>backlog</code> <span class="type">Number</span></li> <li><code>callback</code> <span class="type">Function</span></li> </div></ul> <p>Start a local 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_event_listening"><code>'listening'</code></a> event will be emitted. The last parameter <code>callback</code> will be added as a listener for the <a href="#net_event_listening"><code>'listening'</code></a> event. </p> <p>On UNIX, the local domain is usually known as the UNIX domain. The path is a filesystem path name. It is subject to the same naming conventions and permissions checks as would be done on file creation, will be visible in the filesystem, and will <em>persist until unlinked</em>. </p> <p>On Windows, the local domain is implemented using a named pipe. The path <em>must</em> refer to an entry in <code>\\?\pipe\</code> or <code>\\.\pipe\</code>. Any characters are permitted, but the latter may do some processing of pipe names, such as resolving <code>..</code> sequences. Despite appearances, the pipe name space is flat. Pipes will <em>not persist</em>, they are removed when the last reference to them is closed. Do not forget JavaScript string escaping requires paths to be specified with double-backslashes, such as: </p> <pre><code>net.createServer().listen( path.join('\\\\?\\pipe', process.cwd(), 'myctl'))</code></pre> <p>The parameter <code>backlog</code> behaves the same as in [<code>server.listen(port, \[host\], \[backlog\], \[callback\])</code>][]. </p> <h3>server.listen(port[, hostname][, backlog][, callback])<span><a class="mark" href="#all_server_listen_port_hostname_backlog_callback_1" id="all_server_listen_port_hostname_backlog_callback_1">#</a></span></h3> <p>Begin accepting connections on the specified <code>port</code> and <code>hostname</code>. If the <code>hostname</code> is omitted, the server will accept connections on any IPv6 address (<code>::</code>) when IPv6 is available, or any IPv4 address (<code>0.0.0.0</code>) otherwise. 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_event_listening"><code>'listening'</code></a> event will be emitted. The last parameter <code>callback</code> will be added as a listener for the <a href="#net_event_listening"><code>'listening'</code></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', (e) => { if (e.code == 'EADDRINUSE') { console.log('Address in use, retrying...'); setTimeout(() => { server.close(); server.listen(PORT, HOST); }, 1000); } });</code></pre> <p>(Note: All sockets in Node.js set <code>SO_REUSEADDR</code> already) </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> <p>It is not recommended to use this option once a socket has been sent to a child with <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>. </p> <h3>server.ref()<span><a class="mark" href="#all_server_ref" id="all_server_ref">#</a></span></h3> <p>Opposite of <code>unref</code>, calling <code>ref</code> on a previously <code>unref</code>d server will <em>not</em> let the program exit if it's the only server left (the default behavior). If the server is <code>ref</code>d calling <code>ref</code> again will have no effect. </p> <p>Returns <code>server</code>. </p> <h3>server.unref()<span><a class="mark" href="#all_server_unref" id="all_server_unref">#</a></span></h3> <p>Calling <code>unref</code> on a server will allow the program to exit if this is the only active server in the event system. If the server is already <code>unref</code>d calling <code>unref</code> again will have no effect. </p> <p>Returns <code>server</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 local socket. <code>net.Socket</code> instances implement a duplex Stream interface. They can be created by the user and used as a client (with <a href="#net_socket_connect_options_connectlistener"><code>connect()</code></a>) or they can be created by Node.js and passed to the user through the <code>'connection'</code> event of a server. </p> <h3>new net.Socket(<a href="#zlib_class_options">options</a>)<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, allowHalfOpen: false, readable: false, writable: false }</code></pre> <p><code>fd</code> allows you to specify the existing file descriptor of socket. Set <code>readable</code> and/or <code>writable</code> to <code>true</code> to allow reads and/or writes on this socket (NOTE: Works only when <code>fd</code> is passed). About <code>allowHalfOpen</code>, refer to <code>createServer()</code> and <code>'end'</code> event. </p> <p><code>net.Socket</code> instances are <a href="events.html#events_class_events_eventemitter"><code>EventEmitter</code></a> with the following events: </p> <h3>Event: 'close'<span><a class="mark" href="#all_event_close_6" id="all_event_close_6">#</a></span></h3> <div class="signature"><ul> <li><code>had_error</code> <span class="type">Boolean</span> <code>true</code> 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> <h3>Event: 'connect'<span><a class="mark" href="#all_event_connect_2" id="all_event_connect_2">#</a></span></h3> <p>Emitted when a socket connection is successfully established. See <a href="#net_socket_connect_options_connectlistener"><code>connect()</code></a>. </p> <h3>Event: 'data'<span><a class="mark" href="#all_event_data" id="all_event_data">#</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_class_stream_readable">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: 'drain'<span><a class="mark" href="#all_event_drain" id="all_event_drain">#</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: 'end'<span><a class="mark" href="#all_event_end" id="all_event_end">#</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: 'error'<span><a class="mark" href="#all_event_error_5" id="all_event_error_5">#</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: 'lookup'<span><a class="mark" href="#all_event_lookup" id="all_event_lookup">#</a></span></h3> <p>Emitted after resolving the hostname but before connecting. Not applicable to UNIX sockets. </p> <ul> <li><code>err</code> {Error | Null} The error object. See <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li> <li><code>address</code> {String} The IP address.</li> <li><code>family</code> {String | Null} The address type. See <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li> </ul> <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: <a href="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout()</code></a> </p> <h3>socket.address()<span><a class="mark" href="#all_socket_address_1" id="all_socket_address_1">#</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.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.js 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 <a href="#stream_readable_pause"><code>pause()</code></a> and <a href="#stream_readable_resume"><code>resume()</code></a>. </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> <h3>socket.connect(options[, connectListener])<span><a class="mark" href="#all_socket_connect_options_connectlistener" id="all_socket_connect_options_connectlistener">#</a></span></h3> <p>Opens the connection for a given socket. </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> <li><p><code>localPort</code>: Local port to bind to for network connections.</p> </li> <li><p><code>family</code> : Version of IP stack. Defaults to <code>4</code>.</p> </li> <li><p><code>lookup</code> : Custom lookup function. Defaults to <code>dns.lookup</code>.</p> </li> </ul> <p>For local 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>Normally this method is not needed, as <code>net.createConnection</code> opens the socket. Use this only if you are implementing a custom Socket. </p> <p>This function is asynchronous. When the <a href="#net_event_connect"><code>'connect'</code></a> event is emitted the socket is established. If there is a problem connecting, the <code>'connect'</code> event will not be emitted, the <a href="#net_event_error_1"><code>'error'</code></a> event will be emitted with the exception. </p> <p>The <code>connectListener</code> parameter will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event. </p> <h3>socket.connect(path[, connectListener])<span><a class="mark" href="#all_socket_connect_path_connectlistener" id="all_socket_connect_path_connectlistener">#</a></span></h3> <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> <p>As [<code>socket.connect(options\[, connectListener\])</code>][], with options either as either <code>{port: port, host: host}</code> or <code>{path: path}</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.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.localAddress<span><a class="mark" href="#all_socket_localaddress" id="all_socket_localaddress">#</a></span></h3> <p>The string representation of the local IP address the remote client is connecting on. For example, if you are listening on <code>'0.0.0.0'</code> and the client connects on <code>'192.168.1.1'</code>, the value would be <code>'192.168.1.1'</code>. </p> <h3>socket.localPort<span><a class="mark" href="#all_socket_localport" id="all_socket_localport">#</a></span></h3> <p>The numeric representation of the local port. For example, <code>80</code> or <code>21</code>. </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, <a href="#stream_event_data"><code>'data'</code></a> events will not be emitted. Useful to throttle back an upload. </p> <h3>socket.ref()<span><a class="mark" href="#all_socket_ref_1" id="all_socket_ref_1">#</a></span></h3> <p>Opposite of <code>unref</code>, calling <code>ref</code> on a previously <code>unref</code>d socket will <em>not</em> let the program exit if it's the only socket left (the default behavior). If the socket is <code>ref</code>d calling <code>ref</code> again will have no effect. </p> <p>Returns <code>socket</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>. Value may be <code>undefined</code> if the socket is destroyed (for example, if the client disconnected). </p> <h3>socket.remoteFamily<span><a class="mark" href="#all_socket_remotefamily" id="all_socket_remotefamily">#</a></span></h3> <p>The string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</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.resume()<span><a class="mark" href="#all_socket_resume" id="all_socket_resume">#</a></span></h3> <p>Resumes reading after a call to <a href="#stream_readable_pause"><code>pause()</code></a>. </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 <a href="stream.html#stream_class_stream_readable">Readable Stream</a>. See <a href="stream.html#stream_readable_setencoding_encoding"><code>stream.setEncoding()</code></a> for more information. </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> <p>Returns <code>socket</code>. </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> <p>Returns <code>socket</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 <a href="#net_event_timeout"><code>'timeout'</code></a> event but the connection will not be severed. The user must manually <a href="#stream_writable_end_chunk_encoding_callback"><code>end()</code></a> or <a href="#net_socket_destroy"><code>destroy()</code></a> 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 <a href="#net_event_timeout"><code>'timeout'</code></a> event. </p> <p>Returns <code>socket</code>. </p> <h3>socket.unref()<span><a class="mark" href="#all_socket_unref_1" id="all_socket_unref_1">#</a></span></h3> <p>Calling <code>unref</code> on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already <code>unref</code>d calling <code>unref</code> again will have no effect. </p> <p>Returns <code>socket</code>. </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. <a href="#net_event_drain"><code>'drain'</code></a> 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> <h2>net.connect(options[, connectListener])<span><a class="mark" href="#all_net_connect_options_connectlistener" id="all_net_connect_options_connectlistener">#</a></span></h2> <p>A factory function, which returns a new <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically connects with the supplied <code>options</code>. </p> <p>The options are passed to both the <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> constructor and the <a href="#net_socket_connect_options_connectlistener"><code>socket.connect</code></a> method. </p> <p>The <code>connectListener</code> parameter will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once. </p> <p>Here is an example of a client of the previously described echo server: </p> <pre><code>const net = require('net'); const client = net.connect({port: 8124}, () => { //'connect' listener console.log('connected to server!'); client.write('world!\r\n'); }); client.on('data', (data) => { console.log(data.toString()); client.end(); }); client.on('end', () => { console.log('disconnected from server'); });</code></pre> <p>To connect on the socket <code>/tmp/echo.sock</code> the second line would just be changed to </p> <pre><code>const client = net.connect({path: '/tmp/echo.sock'});</code></pre> <h2>net.connect(path[, connectListener])<span><a class="mark" href="#all_net_connect_path_connectlistener" id="all_net_connect_path_connectlistener">#</a></span></h2> <p>A factory function, which returns a new unix <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically connects to the supplied <code>path</code>. </p> <p>The <code>connectListener</code> parameter will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once. </p> <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> <p>A factory function, which returns a new <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically connects to the supplied <code>port</code> and <code>host</code>. </p> <p>If <code>host</code> is omitted, <code>'localhost'</code> will be assumed. </p> <p>The <code>connectListener</code> parameter will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once. </p> <h2>net.createConnection(options[, connectListener])<span><a class="mark" href="#all_net_createconnection_options_connectlistener" id="all_net_createconnection_options_connectlistener">#</a></span></h2> <p>A factory function, which returns a new <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically connects with the supplied <code>options</code>. </p> <p>The options are passed to both the <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> constructor and the <a href="#net_socket_connect_options_connectlistener"><code>socket.connect</code></a> method. </p> <p>The <code>connectListener</code> parameter will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once. </p> <p>Here is an example of a client of the previously described echo server: </p> <pre><code>const net = require('net'); const client = net.connect({port: 8124}, () => { //'connect' listener console.log('connected to server!'); client.write('world!\r\n'); }); client.on('data', (data) => { console.log(data.toString()); client.end(); }); client.on('end', () => { console.log('disconnected from server'); });</code></pre> <p>To connect on the socket <code>/tmp/echo.sock</code> the second line would just be changed to </p> <pre><code>const client = net.connect({path: '/tmp/echo.sock'});</code></pre> <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>A factory function, which returns a new unix <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically connects to the supplied <code>path</code>. </p> <p>The <code>connectListener</code> parameter will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once. </p> <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>A factory function, which returns a new <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically connects to the supplied <code>port</code> and <code>host</code>. </p> <p>If <code>host</code> is omitted, <code>'localhost'</code> will be assumed. </p> <p>The <code>connectListener</code> parameter will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once. </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 server. The <code>connectionListener</code> argument is automatically set as a listener for the <a href="#net_event_connection"><code>'connection'</code></a> event. </p> <p><code>options</code> is an object with the following defaults: </p> <pre><code>{ allowHalfOpen: false, pauseOnConnect: 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 <a href="#stream_writable_end_chunk_encoding_callback"><code>end()</code></a> method explicitly. See <a href="#stream_event_end"><code>'end'</code></a> event for more information. </p> <p>If <code>pauseOnConnect</code> is <code>true</code>, then the socket associated with each incoming connection will be paused, and no data will be read from its handle. This allows connections to be passed between processes without any data being read by the original process. To begin reading data from a paused socket, call <a href="#stream_readable_resume"><code>resume()</code></a>. </p> <p>Here is an example of an echo server which listens for connections on port 8124: </p> <pre><code>const net = require('net'); const server = net.createServer((c) => { //'connection' listener console.log('client connected'); c.on('end', () => { console.log('client disconnected'); }); c.write('hello\r\n'); c.pipe(c); }); server.listen(8124, () => { //'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', () => { //'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.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> <p>[<code>server.listen(port, \[host\], \[backlog\], \[callback\])</code>]: #net_server_listen_port_hostname_backlog_callback [<code>socket.connect(options\[, connectListener\])</code>]: #net_socket_connect_options_connectlistener </p> <h1>OS<span><a class="mark" href="#all_os" id="all_os">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</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.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> <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. Possible values are <code>'x64'</code>, <code>'arm'</code> and <code>'ia32'</code>. Returns the value of <code>process.arch</code>. </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 milliseconds the CPU/core 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> <p>Note that since <code>nice</code> values are UNIX centric in Windows the <code>nice</code> values of all processors are always 0. </p> <h2>os.endianness()<span><a class="mark" href="#all_os_endianness" id="all_os_endianness">#</a></span></h2> <p>Returns the endianness of the CPU. Possible values are <code>'BE'</code> for big endian or <code>'LE'</code> for little endian. </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.homedir()<span><a class="mark" href="#all_os_homedir" id="all_os_homedir">#</a></span></h2> <p>Returns the home directory of the current user. </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.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> <p>The load average is a measure of system activity, calculated by the operating system and expressed as a fractional number. As a rule of thumb, the load average should ideally be less than the number of logical CPUs in the system. </p> <p>The load average is a very UNIX-y concept; there is no real equivalent on Windows platforms. That is why this function always returns <code>[0, 0, 0]</code> on Windows. </p> <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>{ lo: [ { address: '127.0.0.1', netmask: '255.0.0.0', family: 'IPv4', mac: '00:00:00:00:00:00', internal: true }, { address: '::1', netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', family: 'IPv6', mac: '00:00:00:00:00:00', internal: true } ], eth0: [ { address: '192.168.1.108', netmask: '255.255.255.0', family: 'IPv4', mac: '01:02:03:0a:0b:0c', internal: false }, { address: 'fe80::a00:27ff:fe4e:66a1', netmask: 'ffff:ffff:ffff:ffff::', family: 'IPv6', mac: '01:02:03:0a:0b:0c', internal: false } ] }</code></pre> <p>Note that due to the underlying implementation this will only return network interfaces that have been assigned an address. </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. Possible values are <code>'darwin'</code>, <code>'freebsd'</code>, <code>'linux'</code>, <code>'sunos'</code> or <code>'win32'</code>. Returns the value of <code>process.platform</code>. </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.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 temporary files. </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.type()<span><a class="mark" href="#all_os_type" id="all_os_type">#</a></span></h2> <p>Returns the operating system name. For example <code>'Linux'</code> on Linux, <code>'Darwin'</code> on OS X and <code>'Windows_NT'</code> on Windows. </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> <h1>Path<span><a class="mark" href="#all_path" id="all_path">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</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.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.delimiter<span><a class="mark" href="#all_path_delimiter" id="all_path_delimiter">#</a></span></h2> <p>The platform-specific path delimiter, <code>;</code> or <code>':'</code>. </p> <p>An example on *nix: </p> <pre><code>console.log(process.env.PATH) // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' process.env.PATH.split(path.delimiter) // returns ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']</code></pre> <p>An example on Windows: </p> <pre><code>console.log(process.env.PATH) // 'C:\Windows\system32;C:\Windows;C:\Program Files\node\' process.env.PATH.split(path.delimiter) // returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']</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.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.coffee.md') // returns '.md' path.extname('index.') // returns '.' path.extname('index') // returns '' path.extname('.index') // returns ''</code></pre> <h2>path.format(pathObject)<span><a class="mark" href="#all_path_format_pathobject" id="all_path_format_pathobject">#</a></span></h2> <p>Returns a path string from an object, the opposite of <code>path.parse</code> above. </p> <pre><code>path.format({ root : "/", dir : "/home/user/dir", base : "file.txt", ext : ".txt", name : "file" }) // returns '/home/user/dir/file.txt'</code></pre> <h2>path.isAbsolute(path)<span><a class="mark" href="#all_path_isabsolute_path" id="all_path_isabsolute_path">#</a></span></h2> <p>Determines whether <code>path</code> is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. </p> <p>Posix examples: </p> <pre><code>path.isAbsolute('/foo/bar') // true path.isAbsolute('/baz/..') // true path.isAbsolute('qux/') // false path.isAbsolute('.') // false</code></pre> <p>Windows examples: </p> <pre><code>path.isAbsolute('//server') // true path.isAbsolute('C:/foo/..') // true path.isAbsolute('bar\\baz') // false path.isAbsolute('.') // false</code></pre> <p><em>Note:</em> If the path string passed as parameter is a zero-length string, unlike other path module functions, it will be used as-is and <code>false</code> will be returned. </p> <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. </p> <p>Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. </p> <p>Example: </p> <pre><code>path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') // returns '/foo/bar/baz/asdf' path.join('foo', {}, 'bar') // throws exception TypeError: Arguments to path.join must be strings</code></pre> <p><em>Note:</em> If the arguments to <code>join</code> have zero-length strings, unlike other path module functions, they will be ignored. If the joined path string is a zero-length string then <code>'.'</code> will be returned, which represents the current working directory. </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> <p><em>Note:</em> If the path string passed as argument is a zero-length string then <code>'.'</code> will be returned, which represents the current working directory. </p> <h2>path.parse(pathString)<span><a class="mark" href="#all_path_parse_pathstring" id="all_path_parse_pathstring">#</a></span></h2> <p>Returns an object from a path string. </p> <p>An example on *nix: </p> <pre><code>path.parse('/home/user/dir/file.txt') // returns { root : "/", dir : "/home/user/dir", base : "file.txt", ext : ".txt", name : "file" }</code></pre> <p>An example on Windows: </p> <pre><code>path.parse('C:\\path\\dir\\index.html') // returns { root : "C:\\", dir : "C:\\path\\dir", base : "index.html", ext : ".html", name : "index" }</code></pre> <h2>path.posix<span><a class="mark" href="#all_path_posix" id="all_path_posix">#</a></span></h2> <p>Provide access to aforementioned <code>path</code> methods but always interact in a posix compatible way. </p> <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> <p><em>Note:</em> If the arguments to <code>relative</code> have zero-length strings then the current working directory will be used instead of the zero-length strings. If both the paths are the same then a zero-length string will be returned. </p> <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 <code>from</code> 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> <p><em>Note:</em> If the arguments to <code>resolve</code> have zero-length strings then the current working directory will be used instead of them. </p> <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 *nix: </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> <h2>path.win32<span><a class="mark" href="#all_path_win32" id="all_path_win32">#</a></span></h2> <p>Provide access to aforementioned <code>path</code> methods but always interact in a win32 compatible way. </p> <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"><code>EventEmitter</code></a>. </p> <h2>Event: 'beforeExit'<span><a class="mark" href="#all_event_beforeexit" id="all_event_beforeexit">#</a></span></h2> <p>This event is emitted when Node.js empties its event loop and has nothing else to schedule. Normally, Node.js exits when there is no work scheduled, but a listener for <code>'beforeExit'</code> can make asynchronous calls, and cause Node.js to continue. </p> <p><code>'beforeExit'</code> is not emitted for conditions causing explicit termination, such as <a href="#process_process_exit_code"><code>process.exit()</code></a> or uncaught exceptions, and should not be used as an alternative to the <code>'exit'</code> event unless the intention is to schedule more work. </p> <h2>Event: 'exit'<span><a class="mark" href="#all_event_exit_3" id="all_event_exit_3">#</a></span></h2> <p>Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all <code>'exit'</code> listeners have finished running the process will exit. Therefore you <strong>must</strong> only perform <strong>synchronous</strong> operations in this handler. This is a good hook to perform checks on the module's state (like for unit tests). The callback takes one argument, the code the process is exiting with. </p> <p>This event is only emitted when Node.js exits explicitly by process.exit() or implicitly by the event loop draining. </p> <p>Example of listening for <code>'exit'</code>: </p> <pre><code>process.on('exit', (code) => { // do *NOT* do this setTimeout(() => { console.log('This will not run'); }, 0); console.log('About to exit with code:', code); });</code></pre> <h2>Event: 'message'<span><a class="mark" href="#all_event_message_4" id="all_event_message_4">#</a></span></h2> <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 <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> or <a href="net.html#net_class_net_server"><code>net.Server</code></a> object, or undefined.</li> </div></ul> <p>Messages sent by <a href="child_process.html#child_process_child_send_message_sendhandle_callback"><code>ChildProcess.send()</code></a> are obtained using the <code>'message'</code> event on the child's process object. </p> <h2>Event: 'rejectionHandled'<span><a class="mark" href="#all_event_rejectionhandled" id="all_event_rejectionhandled">#</a></span></h2> <p>Emitted whenever a Promise was rejected and an error handler was attached to it (for example with <code>.catch()</code>) later than after an event loop turn. This event is emitted with the following arguments: </p> <ul> <li><code>p</code> the promise that was previously emitted in an <code>'unhandledRejection'</code> event, but which has now gained a rejection handler.</li> </ul> <p>There is no notion of a top level for a promise chain at which rejections can always be handled. Being inherently asynchronous in nature, a promise rejection can be be handled at a future point in time — possibly much later than the event loop turn it takes for the <code>'unhandledRejection'</code> event to be emitted. </p> <p>Another way of stating this is that, unlike in synchronous code where there is an ever-growing list of unhandled exceptions, with promises there is a growing-and-shrinking list of unhandled rejections. In synchronous code, the <code>'uncaughtException'</code> event tells you when the list of unhandled exceptions grows. And in asynchronous code, the <code>'unhandledRejection'</code> event tells you when the list of unhandled rejections grows, while the <code>'rejectionHandled'</code> event tells you when the list of unhandled rejections shrinks. </p> <p>For example using the rejection detection hooks in order to keep a map of all the rejected promise reasons at a given time: </p> <pre><code>const unhandledRejections = new Map(); process.on('unhandledRejection', (reason, p) => { unhandledRejections.set(p, reason); }); process.on('rejectionHandled', (p) => { unhandledRejections.delete(p); });</code></pre> <p>This map will grow and shrink over time, reflecting rejections that start unhandled and then become handled. You could record the errors in some error log, either periodically (probably best for long-running programs, allowing you to clear the map, which in the case of a very buggy program could grow indefinitely) or upon process exit (more convenient for scripts). </p> <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', (err) => { console.log(`Caught exception: ${err}`); }); setTimeout(() => { 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. </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><code>'uncaughtException'</code> should be used to perform synchronous cleanup before shutting down the process. It is not safe to resume normal operation after <code>'uncaughtException'</code>. If you do use it, restart your application after every unhandled exception! </p> <p>You have been warned. </p> <h2>Event: 'unhandledRejection'<span><a class="mark" href="#all_event_unhandledrejection" id="all_event_unhandledrejection">#</a></span></h2> <p>Emitted whenever a <code>Promise</code> is rejected and no error handler is attached to the promise within a turn of the event loop. When programming with promises exceptions are encapsulated as rejected promises. Such promises can be caught and handled using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>promise.catch(...)</code></a> and rejections are propagated through a promise chain. This event is useful for detecting and keeping track of promises that were rejected whose rejections were not handled yet. This event is emitted with the following arguments: </p> <ul> <li><code>reason</code> the object with which the promise was rejected (usually an <a href="errors.html#errors_class_error"><code>Error</code></a> instance).</li> <li><code>p</code> the promise that was rejected.</li> </ul> <p>Here is an example that logs every unhandled rejection to the console </p> <pre><code>process.on('unhandledRejection', (reason, p) => { console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason); // application specific logging, throwing an error, or other logic here });</code></pre> <p>For example, here is a rejection that will trigger the <code>'unhandledRejection'</code> event: </p> <pre><code>somePromise.then((res) => { return reportToUser(JSON.parse(res)); // note the typo }); // no `.catch` or `.then`</code></pre> <p>Here is an example of a coding pattern that will also trigger <code>'unhandledRejection'</code>: </p> <pre><code>function SomeResource() { // Initially set the loaded status to a rejected promise this.loaded = Promise.reject(new Error('Resource not yet loaded!')); } var resource = new SomeResource(); // no .catch or .then on resource.loaded for at least a turn</code></pre> <p>In cases like this, you may not want to track the rejection as a developer error like you would for other <code>'unhandledRejection'</code> events. To address this, you can either attach a dummy <code>.catch(function() { })</code> handler to <code>resource.loaded</code>, preventing the <code>'unhandledRejection'</code> event from being emitted, or you can use the <code>'rejectionHandled'</code> event. Below is an explanation of how to do that. </p> <h2>Exit Codes<span><a class="mark" href="#all_exit_codes" id="all_exit_codes">#</a></span></h2> <p>Node.js will normally exit with a <code>0</code> status code when no more async operations are pending. The following status codes are used in other cases: </p> <ul> <li><code>1</code> <strong>Uncaught Fatal Exception</strong> - There was an uncaught exception, and it was not handled by a domain or an <code>'uncaughtException'</code> event handler.</li> <li><code>2</code> - Unused (reserved by Bash for builtin misuse)</li> <li><code>3</code> <strong>Internal JavaScript Parse Error</strong> - The JavaScript source code internal in Node.js's bootstrapping process caused a parse error. This is extremely rare, and generally can only happen during development of Node.js itself.</li> <li><code>4</code> <strong>Internal JavaScript Evaluation Failure</strong> - The JavaScript source code internal in Node.js's bootstrapping process failed to return a function value when evaluated. This is extremely rare, and generally can only happen during development of Node.js itself.</li> <li><code>5</code> <strong>Fatal Error</strong> - There was a fatal unrecoverable error in V8. Typically a message will be printed to stderr with the prefix <code>FATAL ERROR</code>.</li> <li><code>6</code> <strong>Non-function Internal Exception Handler</strong> - There was an uncaught exception, but the internal fatal exception handler function was somehow set to a non-function, and could not be called.</li> <li><code>7</code> <strong>Internal Exception Handler Run-Time Failure</strong> - There was an uncaught exception, and the internal fatal exception handler function itself threw an error while attempting to handle it. This can happen, for example, if a <code>process.on('uncaughtException')</code> or <code>domain.on('error')</code> handler throws an error.</li> <li><code>8</code> - Unused. In previous versions of Node.js, exit code 8 sometimes indicated an uncaught exception.</li> <li><code>9</code> - <strong>Invalid Argument</strong> - Either an unknown option was specified, or an option requiring a value was provided without a value.</li> <li><code>10</code> <strong>Internal JavaScript Run-Time Failure</strong> - The JavaScript source code internal in Node.js's bootstrapping process threw an error when the bootstrapping function was called. This is extremely rare, and generally can only happen during development of Node.js itself.</li> <li><code>12</code> <strong>Invalid Debug Argument</strong> - The <code>--debug</code> and/or <code>--debug-brk</code> options were set, but an invalid port number was chosen.</li> <li><code>>128</code> <strong>Signal Exits</strong> - If Node.js receives a fatal signal such as <code>SIGKILL</code> or <code>SIGHUP</code>, then its exit code will be <code>128</code> plus the value of the signal code. This is a standard Unix practice, since exit codes are defined to be 7-bit integers, and signal exits set the high-order bit, and then contain the value of the signal code.</li> </ul> <h2>Signal Events<span><a class="mark" href="#all_signal_events" id="all_signal_events">#</a></span></h2> <!--type=event--> <!--name=SIGINT, SIGHUP, etc.--> <p>Emitted when the processes receives a signal. See sigaction(2) for a list of standard POSIX signal names such as <code>SIGINT</code>, <code>SIGHUP</code>, 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', () => { 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> <p>Note: </p> <ul> <li><code>SIGUSR1</code> is reserved by Node.js to start the debugger. It's possible to install a listener but that won't stop the debugger from starting.</li> <li><code>SIGTERM</code> and <code>SIGINT</code> have default handlers on non-Windows platforms that resets the terminal mode before exiting with code <code>128 + signal number</code>. If one of these signals has a listener installed, its default behavior will be removed (Node.js will no longer exit).</li> <li><code>SIGPIPE</code> is ignored by default. It can have a listener installed.</li> <li><code>SIGHUP</code> is generated on Windows when the console window is closed, and on other platforms under various similar conditions, see signal(7). It can have a listener installed, however Node.js will be unconditionally terminated by Windows about 10 seconds later. On non-Windows platforms, the default behavior of <code>SIGHUP</code> is to terminate Node.js, but once a listener has been installed its default behavior will be removed.</li> <li><code>SIGTERM</code> is not supported on Windows, it can be listened on.</li> <li><code>SIGINT</code> from the terminal is supported on all platforms, and can usually be generated with <code>CTRL+C</code> (though this may be configurable). It is not generated when terminal raw mode is enabled.</li> <li><code>SIGBREAK</code> is delivered on Windows when <code>CTRL+BREAK</code> is pressed, on non-Windows platforms it can be listened on, but there is no way to send or generate it.</li> <li><code>SIGWINCH</code> is delivered when the console has been resized. On Windows, this will only happen on write to the console when the cursor is being moved, or when a readable tty is used in raw mode.</li> <li><code>SIGKILL</code> cannot have a listener installed, it will unconditionally terminate Node.js on all platforms.</li> <li><code>SIGSTOP</code> cannot have a listener installed.</li> </ul> <p>Note that Windows does not support sending Signals, but Node.js offers some emulation with <code>process.kill()</code>, and <code>child_process.kill()</code>. Sending signal <code>0</code> can be used to test for the existence of a process. Sending <code>SIGINT</code>, <code>SIGTERM</code>, and <code>SIGKILL</code> cause the unconditional termination of the target process. </p> <h2>process.abort()<span><a class="mark" href="#all_process_abort" id="all_process_abort">#</a></span></h2> <p>This causes Node.js to emit an abort. This will cause Node.js to exit and generate a core file. </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.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((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.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.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.js executable. This is the same as the <code>config.gypi</code> 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_prefix: '', node_shared_cares: 'false', node_shared_http_parser: 'false', node_shared_libuv: '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> <h3>process.connected<span><a class="mark" href="#all_process_connected" id="all_process_connected">#</a></span></h3> <div class="signature"><ul> <li><span class="type">Boolean</span> Set to false after <code>process.disconnect()</code> is called</li> </div></ul> <p>If <code>process.connected</code> is false, it is no longer possible to send messages. </p> <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.disconnect()<span><a class="mark" href="#all_process_disconnect" id="all_process_disconnect">#</a></span></h2> <p>Close the IPC channel to the parent process, allowing this child to exit gracefully once there are no other connections keeping it alive. </p> <p>Identical to the parent process's <a href="child_process.html#child_process_child_disconnect"><code>ChildProcess.disconnect()</code></a>. </p> <p>If Node.js was not spawned with an IPC channel, <code>process.disconnect()</code> will be undefined. </p> <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> <p>An example of this object looks like: </p> <pre><code>{ TERM: 'xterm-256color', SHELL: '/usr/local/bin/bash', USER: 'maciej', PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', PWD: '/Users/maciej', EDITOR: 'vim', SHLVL: '1', HOME: '/Users/maciej', LOGNAME: 'maciej', _: '/usr/local/bin/node' }</code></pre> <p>You can write to this object, but changes won't be reflected outside of your process. That means that the following won't work: </p> <pre><code>$ node -e 'process.env.foo = "bar"' && echo $foo</code></pre> <p>But this will: </p> <pre><code>process.env.foo = 'bar'; console.log(process.env.foo);</code></pre> <h2>process.execArgv<span><a class="mark" href="#all_process_execargv" id="all_process_execargv">#</a></span></h2> <p>This is the set of Node.js-specific command line options from the executable that started the process. These options do not show up in <code>process.argv</code>, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent. </p> <p>Example: </p> <pre><code>$ node --harmony script.js --version</code></pre> <p>results in process.execArgv: </p> <pre><code>['--harmony']</code></pre> <p>and process.argv: </p> <pre><code>['/usr/local/bin/node', 'script.js', '--version']</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.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.js should see the exit code as 1. </p> <h2>process.exitCode<span><a class="mark" href="#all_process_exitcode" id="all_process_exitcode">#</a></span></h2> <p>A number which will be the process exit code, when the process either exits gracefully, or is exited via <a href="#process_process_exit_code"><code>process.exit()</code></a> without specifying a code. </p> <p>Specifying a code to <code>process.exit(code)</code> will override any previous setting of <code>process.exitCode</code>. </p> <h2>process.getegid()<span><a class="mark" href="#all_process_getegid" id="all_process_getegid">#</a></span></h2> <p>Note: this function is only available on POSIX platforms (i.e. not Windows, Android) </p> <p>Gets the effective group identity of the process. (See getegid(2).) This is the numerical group id, not the group name. </p> <pre><code>if (process.getegid) { console.log(`Current gid: ${process.getegid()}`); }</code></pre> <h2>process.geteuid()<span><a class="mark" href="#all_process_geteuid" id="all_process_geteuid">#</a></span></h2> <p>Note: this function is only available on POSIX platforms (i.e. not Windows, Android) </p> <p>Gets the effective user identity of the process. (See geteuid(2).) This is the numerical userid, not the username. </p> <pre><code>if (process.geteuid) { console.log(`Current uid: ${process.geteuid()}`); }</code></pre> <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, Android) </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.getgroups()<span><a class="mark" href="#all_process_getgroups" id="all_process_getgroups">#</a></span></h2> <p>Note: this function is only available on POSIX platforms (i.e. not Windows, Android) </p> <p>Returns an array with the supplementary group IDs. POSIX leaves it unspecified if the effective group ID is included but Node.js ensures it always is. </p> <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, Android) </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.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, 25 ] setTimeout(() => { var diff = process.hrtime(time); // [ 1, 552 ] console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]); // benchmark took 1000000527 nanoseconds }, 1000);</code></pre> <h2>process.initgroups(user, extra_group)<span><a class="mark" href="#all_process_initgroups_user_extra_group" id="all_process_initgroups_user_extra_group">#</a></span></h2> <p>Note: this function is only available on POSIX platforms (i.e. not Windows, Android) </p> <p>Reads /etc/group and initializes the group access list, using all groups of which the user is a member. This is a privileged operation, meaning you need to be root or have the <code>CAP_SETGID</code> capability. </p> <p><code>user</code> is a user name or user ID. <code>extra_group</code> is a group name or group ID. </p> <p>Some care needs to be taken when dropping privileges. Example: </p> <pre><code>console.log(process.getgroups()); // [ 0 ] process.initgroups('bnoordhuis', 1000); // switch user console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ] process.setgid(1000); // drop root gid console.log(process.getgroups()); // [ 27, 30, 46, 1000 ]</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 <code>SIGINT</code> or <code>SIGHUP</code>. If omitted, the signal will be <code>SIGTERM</code>. See <a href="#process_signal_events">Signal Events</a> and kill(2) for more information. </p> <p>Will throw an error if target does not exist, and as a special case, a signal of <code>0</code> can be used to test for the existence of a process. Windows platforms will throw an error if the <code>pid</code> is used to kill a process group. </p> <p>Note that even though 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', () => { console.log('Got SIGHUP signal.'); }); setTimeout(() => { console.log('Exiting.'); process.exit(0); }, 100); process.kill(process.pid, 'SIGHUP');</code></pre> <p>Note: When SIGUSR1 is received by Node.js it starts the debugger, see <a href="#process_signal_events">Signal Events</a>. </p> <h2>process.mainModule<span><a class="mark" href="#all_process_mainmodule" id="all_process_mainmodule">#</a></span></h2> <p>Alternate way to retrieve <a href="modules.html#modules_accessing_the_main_module"><code>require.main</code></a>. The difference is that if the main module changes at runtime, <code>require.main</code> might still refer to the original main module in modules that were required before the change occurred. Generally it's safe to assume that the two refer to the same module. </p> <p>As with <code>require.main</code>, it will be <code>undefined</code> if there was no entry script. </p> <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.js process measured in bytes. </p> <pre><code>const 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[, arg][, ...])<span><a class="mark" href="#all_process_nexttick_callback_arg" id="all_process_nexttick_callback_arg">#</a></span></h2> <div class="signature"><ul> <li><code>callback</code> <span class="type">Function</span></li> </div></ul> <p>Once the current event loop turn runs to completion, call the callback function. </p> <p>This is <em>not</em> a simple alias to <a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout(fn, 0)</code></a>, it's much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop. </p> <pre><code>console.log('start'); process.nextTick(() => { console.log('nextTick callback'); }); console.log('scheduled'); // Output: // start // scheduled // nextTick callback</code></pre> <p>This is important in developing APIs where you want to give the user the chance to assign event handlers after an object has been constructed, but before any I/O has occurred. </p> <pre><code>function MyThing(options) { this.setupOptions(options); process.nextTick(() => { this.startDoingStuff(); }.bind(this)); } var thing = new MyThing(); thing.getReadyForStuff(); // thing.startDoingStuff() gets called now, not before.</code></pre> <p>It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example: </p> <pre><code>// WARNING! DO NOT USE! BAD UNSAFE HAZARD! function maybeSync(arg, cb) { if (arg) { cb(); return; } fs.stat('file', cb); }</code></pre> <p>This API is hazardous. If you do this: </p> <pre><code>maybeSync(true, function() { foo(); }); bar();</code></pre> <p>then it's not clear whether <code>foo()</code> or <code>bar()</code> will be called first. </p> <p>This approach is much better: </p> <pre><code>function definitelyAsync(arg, cb) { if (arg) { process.nextTick(cb); return; } fs.stat('file', cb); }</code></pre> <p>Note: the nextTick queue is completely drained on each pass of the event loop <strong>before</strong> additional I/O is processed. As a result, recursively setting nextTick callbacks will block any I/O from happening, just like a <code>while(true);</code> loop. </p> <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.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.release<span><a class="mark" href="#all_process_release" id="all_process_release">#</a></span></h2> <p>An Object containing metadata related to the current release, including URLs for the source tarball and headers-only tarball. </p> <p><code>process.release</code> contains the following properties: </p> <ul> <li><code>name</code>: a string with a value that will always be <code>'node'</code> for Node.js. For legacy io.js releases, this will be <code>'io.js'</code>.</li> <li><code>sourceUrl</code>: a complete URL pointing to a <em>.tar.gz</em> file containing the source of the current release.</li> <li><code>headersUrl</code>: a complete URL pointing to a <em>.tar.gz</em> file containing only the header files for the current release. This file is significantly smaller than the full source file and can be used for compiling add-ons against Node.js.</li> <li><code>libUrl</code>: a complete URL pointing to an <em>node.lib</em> file matching the architecture and version of the current release. This file is used for compiling add-ons against Node.js. <em>This property is only present on Windows builds of Node.js and will be missing on all other platforms.</em></li> </ul> <p>e.g. </p> <pre><code>{ name: 'node', sourceUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0.tar.gz', headersUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0-headers.tar.gz', libUrl: 'https://nodejs.org/download/release/v4.0.0/win-x64/node.lib' }</code></pre> <p>In custom builds from non-release versions of the source tree, only the <code>name</code> property may be present. The additional properties should not be relied upon to exist. </p> <h2>process.send(message[, sendHandle][, callback])<span><a class="mark" href="#all_process_send_message_sendhandle_callback" id="all_process_send_message_sendhandle_callback">#</a></span></h2> <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 Node.js is spawned with an IPC channel attached, it can send messages to its parent process using <code>process.send()</code>. Each will be received as a <a href="child_process.html#child_process_event_message"><code>'message'</code></a> event on the parent's <code>ChildProcess</code> object. </p> <p>If Node.js was not spawned with an IPC channel, <code>process.send()</code> will be undefined. </p> <h2>process.setegid(id)<span><a class="mark" href="#all_process_setegid_id" id="all_process_setegid_id">#</a></span></h2> <p>Note: this function is only available on POSIX platforms (i.e. not Windows, Android) </p> <p>Sets the effective group identity of the process. (See setegid(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.getegid && process.setegid) { console.log(`Current gid: ${process.getegid()}`); try { process.setegid(501); console.log(`New gid: ${process.getegid()}`); } catch (err) { console.log(`Failed to set gid: ${err}`); } }</code></pre> <h2>process.seteuid(id)<span><a class="mark" href="#all_process_seteuid_id" id="all_process_seteuid_id">#</a></span></h2> <p>Note: this function is only available on POSIX platforms (i.e. not Windows, Android) </p> <p>Sets the effective user identity of the process. (See seteuid(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.geteuid && process.seteuid) { console.log(`Current uid: ${process.geteuid()}`); try { process.seteuid(501); console.log(`New uid: ${process.geteuid()}`); } catch (err) { console.log(`Failed to set uid: ${err}`); } }</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, Android) </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.setgroups(groups)<span><a class="mark" href="#all_process_setgroups_groups" id="all_process_setgroups_groups">#</a></span></h2> <p>Note: this function is only available on POSIX platforms (i.e. not Windows, Android) </p> <p>Sets the supplementary group IDs. This is a privileged operation, meaning you need to be root or have the <code>CAP_SETGID</code> capability. </p> <p>The list can contain group IDs, group names or both. </p> <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, Android) </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.stderr<span><a class="mark" href="#all_process_stderr" id="all_process_stderr">#</a></span></h2> <p>A writable stream to stderr (on fd <code>2</code>). </p> <p><code>process.stderr</code> and <code>process.stdout</code> are unlike other streams in Node.js in that they cannot be closed (<code>end()</code> will throw), they never emit the <code>finish</code> event and that writes can block when output is redirected to a file (although disks are fast and operating systems normally employ write-back caching so it should be a very rare occurrence indeed.) </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 (on fd <code>0</code>). </p> <p>Example of opening standard input and listening for both events: </p> <pre><code>process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { var chunk = process.stdin.read(); if (chunk !== null) { process.stdout.write(`data: ${chunk}`); } }); process.stdin.on('end', () => { process.stdout.write('end'); });</code></pre> <p>As a Stream, <code>process.stdin</code> can also be used in "old" mode that is compatible with scripts written for node.js prior to v0.10. For more information see <a href="stream.html#stream_compatibility_with_older_node_js_versions">Stream compatibility</a>. </p> <p>In "old" Streams mode the stdin stream is paused by default, so one must call <code>process.stdin.resume()</code> to read from it. Note also that calling <code>process.stdin.resume()</code> itself would switch stream to "old" mode. </p> <p>If you are starting a new project you should prefer a more recent "new" Streams mode over "old" one. </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> (on fd <code>1</code>). </p> <p>For example, a <code>console.log</code> equivalent could look like this: </p> <pre><code>console.log = function(msg) { process.stdout.write(`${msg}\n`); };</code></pre> <p><code>process.stderr</code> and <code>process.stdout</code> are unlike other streams in Node.js in that they cannot be closed (<code>end()</code> will throw), they never emit the <code>'finish'</code> event and that writes can block when output is redirected to a file (although disks are fast and operating systems normally employ write-back caching so it should be a very rare occurrence indeed.) </p> <p>To check if Node.js is being run in a TTY context, read the <code>isTTY</code> property on <code>process.stderr</code>, <code>process.stdout</code>, or <code>process.stdin</code>: </p> <pre><code>$ node -p "Boolean(process.stdin.isTTY)" true $ echo "foo" | node -p "Boolean(process.stdin.isTTY)" false $ node -p "Boolean(process.stdout.isTTY)" true $ node -p "Boolean(process.stdout.isTTY)" | cat false</code></pre> <p>See <a href="tty.html#tty_tty">the tty docs</a> for more information. </p> <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 <code>ps</code>. </p> <p>When used as a setter, the maximum length is platform-specific and probably short. </p> <p>On Linux and OS X, it's limited to the size of the binary name plus the length of the command line arguments because it overwrites the argv memory. </p> <p>v0.8 allowed for longer process title strings by also overwriting the environ memory but that was potentially insecure/confusing in some (rather obscure) cases. </p> <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>const newmask = 0o022; const 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.js has been running. </p> <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.js and its dependencies. </p> <pre><code>console.log(process.versions);</code></pre> <p>Will print something like: </p> <pre><code>{ http_parser: '2.3.0', node: '1.1.1', v8: '4.1.0.14', uv: '1.3.0', zlib: '1.2.8', ares: '1.10.0-DEV', modules: '43', icu: '55.1', openssl: '1.0.1k' }</code></pre> <h1>punycode<span><a class="mark" href="#all_punycode" id="all_punycode">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p><a href="https://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-only symbols to a string of Unicode symbols. </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 symbols to a Punycode string of ASCII-only symbols. </p> <pre><code>// encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k'</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.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.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 numeric code point values of each Unicode symbol in the string. While <a href="https://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'); // [0x61, 0x62, 0x63] // 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 numeric code point values. </p> <pre><code>punycode.ucs2.encode([0x61, 0x62, 0x63]); // '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>Query String<span><a class="mark" href="#all_query_string" id="all_query_string">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><!--name=querystring--> <p>This module provides utilities for dealing with query strings. It provides the following methods: </p> <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.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>Options object may contain <code>decodeURIComponent</code> property (<code>querystring.unescape</code> by default), it can be used to decode a <code>non-utf8</code> encoding string if necessary. </p> <p>Example: </p> <pre><code>querystring.parse('foo=bar&baz=qux&baz=quux&corge') // returns { foo: 'bar', baz: ['qux', 'quux'], corge: '' } // Suppose gbkDecodeURIComponent function already exists, // it can decode `gbk` encoding string querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, { decodeURIComponent: gbkDecodeURIComponent }) // returns { w: '䏿–‡', foo: 'bar' }</code></pre> <h2>querystring.stringify(obj[, sep][, eq][, options])<span><a class="mark" href="#all_querystring_stringify_obj_sep_eq_options" id="all_querystring_stringify_obj_sep_eq_options">#</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>Options object may contain <code>encodeURIComponent</code> property (<code>querystring.escape</code> by default), it can be used to encode string with <code>non-utf8</code> encoding if necessary. </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' // Suppose gbkEncodeURIComponent function already exists, // it can encode string with `gbk` encoding querystring.stringify({ w: '䏿–‡', foo: 'bar' }, null, null, { encodeURIComponent: gbkEncodeURIComponent }) // returns 'w=%D6%D0%CE%C4&foo=bar'</code></pre> <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> <p>It will try to use <code>decodeURIComponent</code> in the first place, but if that fails it falls back to a safer equivalent that doesn't throw on malformed URLs. </p> <h1>Readline<span><a class="mark" href="#all_readline" id="all_readline">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>To use this module, do <code>require('readline')</code>. Readline allows reading of a stream (such as <a href="process.html#process_process_stdin"><code>process.stdin</code></a>) on a line-by-line basis. </p> <p>Note that once you've invoked this module, your Node.js program will not terminate until you've closed the interface. Here's how to allow your program to gracefully exit: </p> <pre><code>const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('What do you think of Node.js? ', (answer) => { // TODO: Log the answer in a database console.log('Thank you for your valuable feedback:', answer); rl.close(); });</code></pre> <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.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 <code>'close'</code> event will also be emitted. </p> <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> <p>Note that this doesn't immediately pause the stream of events. Several events may be emitted after calling <code>pause</code>, including <code>line</code>. </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> <p>If <code>output</code> is set to <code>null</code> or <code>undefined</code> when calling <code>createInterface</code>, the prompt is not written. </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>If <code>output</code> is set to <code>null</code> or <code>undefined</code> when calling <code>createInterface</code>, nothing is displayed. </p> <p>Example usage: </p> <pre><code>interface.question('What is your favorite food?', (answer) => { console.log(`Oh, so your favorite food is ${answer}`); });</code></pre> <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.setPrompt(prompt)<span><a class="mark" href="#all_rl_setprompt_prompt" id="all_rl_setprompt_prompt">#</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.js's prompt. </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, unless <code>output</code> is set to <code>null</code> or <code>undefined</code> when calling <code>createInterface</code>. <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: 'close'<span><a class="mark" href="#all_event_close_7" id="all_event_close_7">#</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 <code>'end'</code> 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: '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', (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', () => { 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', () => { console.log('Readline resumed.'); });</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', () => { // `prompt` will automatically resume the stream rl.prompt(); });</code></pre> <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', () => { rl.question('Are you sure you want to exit?', (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', () => { // This will override SIGTSTP and prevent the program from going to the // background. console.log('Caught SIGTSTP.'); });</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>const readline = require('readline'); const rl = readline.createInterface(process.stdin, process.stdout); rl.setPrompt('OHAI> '); rl.prompt(); rl.on('line', (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', () => { console.log('Have a great day!'); process.exit(0); });</code></pre> <h2>Example: Read File Stream Line-by-Line<span><a class="mark" href="#all_example_read_file_stream_line_by_line" id="all_example_read_file_stream_line_by_line">#</a></span></h2> <p>A common case for <code>readline</code>'s <code>input</code> option is to pass a filesystem readable stream to it. This is how one could craft line-by-line parsing of a file: </p> <pre><code>const readline = require('readline'); const fs = require('fs'); const rl = readline.createInterface({ input: fs.createReadStream('sample.txt') }); rl.on('line', function (line) { console.log('Line from file:', line); });</code></pre> <h2>readline.clearLine(stream, dir)<span><a class="mark" href="#all_readline_clearline_stream_dir" id="all_readline_clearline_stream_dir">#</a></span></h2> <p>Clears current line of given TTY stream in a specified direction. <code>dir</code> should have one of following values: </p> <ul> <li><code>-1</code> - to the left from cursor</li> <li><code>1</code> - to the right from cursor</li> <li><code>0</code> - the entire line</li> </ul> <h2>readline.clearScreenDown(stream)<span><a class="mark" href="#all_readline_clearscreendown_stream" id="all_readline_clearscreendown_stream">#</a></span></h2> <p>Clears the screen from the current position of the cursor down. </p> <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 <code>options</code> 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 (Optional).</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> <li><p><code>historySize</code> - maximum number of history lines retained. Defaults to <code>30</code>.</p> </li> </ul> <p>The <code>completer</code> function is given 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((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 <a href="process.html#process_process_stdin"><code>process.stdin</code></a> and <a href="process.html#process_process_stdout"><code>process.stdout</code></a> in order to accept user input: </p> <pre><code>const readline = require('readline'); const 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 (<a href="process.html#process_process_stdout"><code>process.stdout</code></a> does this automatically when it is a TTY). </p> <h2>readline.cursorTo(stream, x, y)<span><a class="mark" href="#all_readline_cursorto_stream_x_y" id="all_readline_cursorto_stream_x_y">#</a></span></h2> <p>Move cursor to the specified position in a given TTY stream. </p> <h2>readline.moveCursor(stream, dx, dy)<span><a class="mark" href="#all_readline_movecursor_stream_dx_dy" id="all_readline_movecursor_stream_dx_dy">#</a></span></h2> <p>Move cursor relative to it's current position in a given TTY stream. </p> <h1>REPL<span><a class="mark" href="#all_repl" id="all_repl">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><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.js 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>Environment Variable Options<span><a class="mark" href="#all_environment_variable_options" id="all_environment_variable_options">#</a></span></h2> <p>The built-in repl (invoked by running <code>node</code> or <code>node -i</code>) may be controlled via the following environment variables: </p> <ul> <li><code>NODE_REPL_HISTORY</code> - When a valid path is given, persistent REPL history will be saved to the specified file rather than <code>.node_repl_history</code> in the user's home directory. Setting this value to <code>""</code> will disable persistent REPL history.</li> <li><code>NODE_REPL_HISTORY_SIZE</code> - defaults to <code>1000</code>. Controls how many lines of history will be persisted if history is available. Must be a positive number.</li> <li><code>NODE_REPL_MODE</code> - may be any of <code>sloppy</code>, <code>strict</code>, or <code>magic</code>. Defaults to <code>magic</code>, which will automatically run "strict mode only" statements in strict mode.</li> </ul> <h2>Persistent History<span><a class="mark" href="#all_persistent_history" id="all_persistent_history">#</a></span></h2> <p>By default, the REPL will persist history between <code>node</code> REPL sessions by saving to a <code>.node_repl_history</code> file in the user's home directory. This can be disabled by setting the environment variable <code>NODE_REPL_HISTORY=""</code>. </p> <h3>NODE_REPL_HISTORY_FILE<span><a class="mark" href="#all_node_repl_history_file" id="all_node_repl_history_file">#</a></span></h3> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <code>NODE_REPL_HISTORY</code> instead.</pre><p>Previously in Node.js/io.js v2.x, REPL history was controlled by using a <code>NODE_REPL_HISTORY_FILE</code> environment variable, and the history was saved in JSON format. This variable has now been deprecated, and your REPL history will automatically be converted to using plain text. The new file will be saved to either your home directory, or a directory defined by the <code>NODE_REPL_HISTORY</code> variable, as documented below. </p> <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>Core modules will be loaded on-demand into the environment. For example, accessing <code>fs</code> will <code>require()</code> the <code>fs</code> module as <code>global.fs</code>. </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 const repl = require('repl'); var 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> <li><code><tab></code> - Show both global and local(scope) variables</li> </ul> <h3>Customizing Object displays in the REPL<span><a class="mark" href="#all_customizing_object_displays_in_the_repl" id="all_customizing_object_displays_in_the_repl">#</a></span></h3> <p>The REPL module internally uses <a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a>, when printing values. However, <code>util.inspect</code> delegates the call to the object's <code>inspect()</code> function, if it has one. You can read more about this delegation <a href="https://github.com/thlorenz/v8-flags/blob/master/flags-0.11.md">here</a>. </p> <p>For example, if you have defined an <code>inspect()</code> function on an object, like this: </p> <pre><code>> var obj = { foo: 'this will not show up in the inspect() output' }; undefined > obj.inspect = function() { ... return { bar: 'baz' }; ... }; [Function]</code></pre> <p>and try to print <code>obj</code> in REPL, it will invoke the custom <code>inspect()</code> function: </p> <pre><code>> obj { bar: 'baz' }</code></pre> <h2>Class: REPLServer<span><a class="mark" href="#all_class_replserver" id="all_class_replserver">#</a></span></h2> <p>This inherits from <a href="readline.html#readline_class_interface">Readline Interface</a> with the following events: </p> <h3>Event: 'exit'<span><a class="mark" href="#all_event_exit_4" id="all_event_exit_4">#</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 <code>SIGINT</code>, or pressing Ctrl+D to signal <code>'end'</code> on the <code>input</code> stream. </p> <p>Example of listening for <code>exit</code>: </p> <pre><code>replServer.on('exit', () => { console.log('Got "exit" event from repl!'); process.exit(); });</code></pre> <h3>Event: 'reset'<span><a class="mark" href="#all_event_reset" id="all_event_reset">#</a></span></h3> <p><code>function (context) {}</code> </p> <p>Emitted when the REPL's context is reset. This happens when you type <code>.clear</code>. If you start the repl with <code>{ useGlobal: true }</code> then this event will never be emitted. </p> <p>Example of listening for <code>reset</code>: </p> <pre><code>// Extend the initial repl context. var replServer = repl.start({ options ... }); someExtension.extend(r.context); // When a new context is created extend it as well. replServer.on('reset', (context) => { console.log('repl has a new context'); someExtension.extend(context); });</code></pre> <h3>replServer.defineCommand(keyword, cmd)<span><a class="mark" href="#all_replserver_definecommand_keyword_cmd" id="all_replserver_definecommand_keyword_cmd">#</a></span></h3> <div class="signature"><ul> <li><code>keyword</code> <span class="type">String</span></li> <li><code>cmd</code> <span class="type">Object|Function</span></li> </div></ul> <p>Makes a command available in the REPL. The command is invoked by typing a <code>.</code> followed by the keyword. The <code>cmd</code> is an object with the following values: </p> <ul> <li><code>help</code> - help text to be displayed when <code>.help</code> is entered (Optional).</li> <li><code>action</code> - a function to execute, potentially taking in a string argument, when the command is invoked, bound to the REPLServer instance (Required).</li> </ul> <p>If a function is provided instead of an object for <code>cmd</code>, it is treated as the <code>action</code>. </p> <p>Example of defining a command: </p> <pre><code>// repl_test.js const repl = require('repl'); var replServer = repl.start(); replServer.defineCommand('sayhello', { help: 'Say hello', action: function(name) { this.write(`Hello, ${name}!\n'); this.displayPrompt(); } });</code></pre> <p>Example of invoking that command from the REPL: </p> <pre><code>> .sayhello Node.js User Hello, Node.js User!</code></pre> <h3>replServer.displayPrompt([preserveCursor])<span><a class="mark" href="#all_replserver_displayprompt_preservecursor" id="all_replserver_displayprompt_preservecursor">#</a></span></h3> <div class="signature"><ul> <li><code>preserveCursor</code> <span class="type">Boolean</span></li> </div></ul> <p>Like <a href="readline.html#readline_rl_prompt_preservecursor"><code>readline.prompt</code></a> except also adding indents with ellipses when inside blocks. The <code>preserveCursor</code> argument is passed to <a href="readline.html#readline_rl_prompt_preservecursor"><code>readline.prompt</code></a>. This is used primarily with <code>defineCommand</code>. It's also used internally to render each prompt line. </p> <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, that inherits from <a href="readline.html#readline_class_interface">Readline Interface</a>. 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> <li><p><code>replMode</code> - controls whether the repl runs all commands in strict mode, default mode, or a hybrid mode ("magic" mode.) Acceptable values are:</p> <ul> <li><code>repl.REPL_MODE_SLOPPY</code> - run commands in sloppy mode.</li> <li><code>repl.REPL_MODE_STRICT</code> - run commands in strict mode. This is equivalent to prefacing every repl statement with <code>'use strict'</code>.</li> <li><code>repl.REPL_MODE_MAGIC</code> - attempt to run commands in default mode. If they fail to parse, re-try in strict mode.</li> </ul> </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>On tab completion - <code>eval</code> will be called with <code>.scope</code> as an input string. It is expected to return an array of scope names to be used for the auto-completion. </p> <p>Multiple REPLs may be started against the same running instance of Node.js. 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>const net = require('net'); const repl = require('repl'); var connections = 0; repl.start({ prompt: 'Node.js via stdin> ', input: process.stdin, output: process.stdout }); net.createServer((socket) => { connections += 1; repl.start({ prompt: 'Node.js via Unix socket> ', input: socket, output: socket }).on('exit', () => { socket.end(); }) }).listen('/tmp/node-repl-sock'); net.createServer((socket) => { connections += 1; repl.start({ prompt: 'Node.js via TCP socket> ', input: socket, output: socket }).on('exit', () => { 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.js 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> <h1>Stream<span><a class="mark" href="#all_stream" id="all_stream">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>A stream is an abstract interface implemented by various objects in Node.js. For example a <a href="http.html#http_http_incomingmessage">request to an HTTP server</a> is a stream, as is <a href="process.html#process_process_stdout"><code>stdout</code></a>. Streams are readable, writable, or both. All streams are instances of <a href="events.html#events_class_events_eventemitter"><code>EventEmitter</code></a>. </p> <p>You can load the Stream base classes by doing <code>require('stream')</code>. There are base classes provided for <a href="#stream_class_stream_readable">Readable</a> streams, <a href="#stream_class_stream_writable">Writable</a> streams, <a href="#stream_class_stream_duplex">Duplex</a> streams, and <a href="#stream_class_stream_transform">Transform</a> streams. </p> <p>This document is split up into 3 sections: </p> <ol> <li>The first section explains the parts of the API that you need to be aware of to use streams in your programs.</li> <li>The second section explains the parts of the API that you need to use if you implement your own custom streams yourself. The API is designed to make this easy for you to do.</li> <li>The third section goes into more depth about how streams work, including some of the internal mechanisms and functions that you should probably not modify unless you definitely know what you are doing.</li> </ol> <h2>API for Stream Consumers<span><a class="mark" href="#all_api_for_stream_consumers" id="all_api_for_stream_consumers">#</a></span></h2> <!--type=misc--> <p>Streams can be either <a href="#stream_class_stream_readable">Readable</a>, <a href="#stream_class_stream_writable">Writable</a>, or both (<a href="#stream_class_stream_duplex">Duplex</a>). </p> <p>All streams are EventEmitters, but they also have other custom methods and properties depending on whether they are Readable, Writable, or Duplex. </p> <p>If a stream is both Readable and Writable, then it implements all of the methods and events below. So, a <a href="#stream_class_stream_duplex">Duplex</a> or <a href="#stream_class_stream_transform">Transform</a> stream is fully described by this API, though their implementation may be somewhat different. </p> <p>It is not necessary to implement Stream interfaces in order to consume streams in your programs. If you <strong>are</strong> implementing streaming interfaces in your own program, please also refer to <a href="#stream_api_for_stream_implementors">API for Stream Implementors</a> below. </p> <p>Almost all Node.js programs, no matter how simple, use Streams in some way. Here is an example of using Streams in an Node.js program: </p> <pre><code class="javascript">const http = require('http'); var server = http.createServer( (req, res) => { // req is an http.IncomingMessage, which is a Readable Stream // res is an http.ServerResponse, which is a Writable Stream var body = ''; // we want to get the data as utf8 strings // If you don't set an encoding, then you'll get Buffer objects req.setEncoding('utf8'); // Readable streams emit 'data' events once a listener is added req.on('data', (chunk) => { body += chunk; }); // the end event tells you that you have entire body req.on('end', () => { try { var data = JSON.parse(body); } catch (er) { // uh oh! bad json! res.statusCode = 400; return res.end(`error: ${er.message}`); } // write back something interesting to the user: res.write(typeof data); res.end(); }); }); server.listen(1337); // $ curl localhost:1337 -d '{}' // object // $ curl localhost:1337 -d '"foo"' // string // $ curl localhost:1337 -d 'not json' // error: Unexpected token o</code></pre> <h3>Class: stream.Duplex<span><a class="mark" href="#all_class_stream_duplex" id="all_class_stream_duplex">#</a></span></h3> <p>Duplex streams are streams that implement both the <a href="#stream_class_stream_readable">Readable</a> and <a href="#stream_class_stream_writable">Writable</a> interfaces. See above for usage. </p> <p>Examples of Duplex streams include: </p> <ul> <li><a href="net.html#net_class_net_socket">tcp sockets</a></li> <li><a href="zlib.html">zlib streams</a></li> <li><a href="crypto.html">crypto streams</a></li> </ul> <h3>Class: stream.Readable<span><a class="mark" href="#all_class_stream_readable" id="all_class_stream_readable">#</a></span></h3> <!--type=class--> <p>The Readable stream interface is the abstraction for a <em>source</em> of data that you are reading from. In other words, data comes <em>out</em> of a Readable stream. </p> <p>A Readable stream will not start emitting data until you indicate that you are ready to receive it. </p> <p>Readable streams have two "modes": a <strong>flowing mode</strong> and a <strong>paused mode</strong>. When in flowing mode, data is read from the underlying system and provided to your program as fast as possible. In paused mode, you must explicitly call <code>stream.read()</code> to get chunks of data out. Streams start out in paused mode. </p> <p><strong>Note</strong>: If no data event handlers are attached, and there are no <a href="#stream_readable_pipe_destination_options"><code>pipe()</code></a> destinations, and the stream is switched into flowing mode, then data will be lost. </p> <p>You can switch to flowing mode by doing any of the following: </p> <ul> <li>Adding a <a href="#stream_event_data"><code>'data'</code></a> event handler to listen for data.</li> <li>Calling the <a href="#stream_readable_resume"><code>resume()</code></a> method to explicitly open the flow.</li> <li>Calling the <a href="#stream_readable_pipe_destination_options"><code>pipe()</code></a> method to send the data to a <a href="#stream_class_stream_writable">Writable</a>.</li> </ul> <p>You can switch back to paused mode by doing either of the following: </p> <ul> <li>If there are no pipe destinations, by calling the <a href="#stream_readable_pause"><code>pause()</code></a> method.</li> <li>If there are pipe destinations, by removing any <a href="#stream_event_data"><code>'data'</code></a> event handlers, and removing all pipe destinations by calling the <a href="#stream_readable_unpipe_destination"><code>unpipe()</code></a> method.</li> </ul> <p>Note that, for backwards compatibility reasons, removing <code>'data'</code> event handlers will <strong>not</strong> automatically pause the stream. Also, if there are piped destinations, then calling <code>pause()</code> will not guarantee that the stream will <em>remain</em> paused once those destinations drain and ask for more data. </p> <p>Examples of readable streams include: </p> <ul> <li><a href="http.html#http_http_incomingmessage">http responses, on the client</a></li> <li><a href="http.html#http_http_incomingmessage">http requests, on the server</a></li> <li><a href="fs.html#fs_class_fs_readstream">fs read streams</a></li> <li><a href="zlib.html">zlib streams</a></li> <li><a href="crypto.html">crypto streams</a></li> <li><a href="net.html#net_class_net_socket">tcp sockets</a></li> <li><a href="child_process.html#child_process_child_stdout">child process stdout and stderr</a></li> <li><a href="process.html#process_process_stdin"><code>process.stdin</code></a></li> </ul> <h4>Event: 'close'<span><a class="mark" href="#all_event_close_8" id="all_event_close_8">#</a></span></h4> <p>Emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur. </p> <p>Not all streams will emit the <code>'close'</code> event. </p> <h4>Event: 'data'<span><a class="mark" href="#all_event_data_1" id="all_event_data_1">#</a></span></h4> <div class="signature"><ul> <li><code>chunk</code> <span class="type">Buffer | String</span> The chunk of data.</li> </div></ul> <p>Attaching a <code>'data'</code> event listener to a stream that has not been explicitly paused will switch the stream into flowing mode. Data will then be passed as soon as it is available. </p> <p>If you just want to get all the data out of the stream as fast as possible, this is the best way to do so. </p> <pre><code class="javascript">var readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log('got %d bytes of data', chunk.length); });</code></pre> <h4>Event: 'end'<span><a class="mark" href="#all_event_end_1" id="all_event_end_1">#</a></span></h4> <p>This event fires when there will be no more data to read. </p> <p>Note that the <code>'end'</code> event <strong>will not fire</strong> unless the data is completely consumed. This can be done by switching into flowing mode, or by calling <code>read()</code> repeatedly until you get to the end. </p> <pre><code class="javascript">var readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log('got %d bytes of data', chunk.length); }); readable.on('end', () => { console.log('there will be no more data.'); });</code></pre> <h4>Event: 'error'<span><a class="mark" href="#all_event_error_6" id="all_event_error_6">#</a></span></h4> <div class="signature"><ul> <li><span class="type">Error Object</span></li> </div></ul> <p>Emitted if there was an error receiving data. </p> <h4>Event: 'readable'<span><a class="mark" href="#all_event_readable" id="all_event_readable">#</a></span></h4> <p>When a chunk of data can be read from the stream, it will emit a <code>'readable'</code> event. </p> <p>In some cases, listening for a <code>'readable'</code> event will cause some data to be read into the internal buffer from the underlying system, if it hadn't already. </p> <pre><code class="javascript">var readable = getReadableStreamSomehow(); readable.on('readable', () => { // there is some data to read now });</code></pre> <p>Once the internal buffer is drained, a <code>'readable'</code> event will fire again when more data is available. </p> <p>The <code>'readable'</code> event is not emitted in the "flowing" mode with the sole exception of the last one, on end-of-stream. </p> <p>The <code>'readable'</code> event indicates that the stream has new information: either new data is available or the end of the stream has been reached. In the former case, <code>.read()</code> will return that data. In the latter case, <code>.read()</code> will return null. For instance, in the following example, <code>foo.txt</code> is an empty file: </p> <pre><code class="javascript">const fs = require('fs'); var rr = fs.createReadStream('foo.txt'); rr.on('readable', () => { console.log('readable:', rr.read()); }); rr.on('end', () => { console.log('end'); });</code></pre> <p>The output of running this script is: </p> <pre><code>bash-3.2$ node test.js readable: null end</code></pre> <h4>readable.isPaused()<span><a class="mark" href="#all_readable_ispaused" id="all_readable_ispaused">#</a></span></h4> <div class="signature"><ul> <li>Return: <code>Boolean</code></li> </div></ul> <p>This method returns whether or not the <code>readable</code> has been <strong>explicitly</strong> paused by client code (using <code>readable.pause()</code> without a corresponding <code>readable.resume()</code>). </p> <pre><code class="javascript">var readable = new stream.Readable readable.isPaused() // === false readable.pause() readable.isPaused() // === true readable.resume() readable.isPaused() // === false</code></pre> <h4>readable.pause()<span><a class="mark" href="#all_readable_pause" id="all_readable_pause">#</a></span></h4> <div class="signature"><ul> <li>Return: <code>this</code></li> </div></ul> <p>This method will cause a stream in flowing mode to stop emitting <code>'data'</code> events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer. </p> <pre><code class="javascript">var readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log('got %d bytes of data', chunk.length); readable.pause(); console.log('there will be no more data for 1 second'); setTimeout(() => { console.log('now data will start flowing again'); readable.resume(); }, 1000); });</code></pre> <h4>readable.pipe(destination[, options])<span><a class="mark" href="#all_readable_pipe_destination_options" id="all_readable_pipe_destination_options">#</a></span></h4> <div class="signature"><ul> <li><code>destination</code> <span class="type"><a href="#stream_class_stream_writable">Writable</a> Stream</span> The destination for writing data</li> <li><code>options</code> <span class="type">Object</span> Pipe options<ul> <li><code>end</code> <span class="type">Boolean</span> End the writer when the reader ends. Default = <code>true</code></li> </ul> </li> </div></ul> <p>This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. </p> <p>Multiple destinations can be piped to safely. </p> <pre><code class="javascript">var readable = getReadableStreamSomehow(); var writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt' readable.pipe(writable);</code></pre> <p>This function returns the destination stream, so you can set up pipe chains like so: </p> <pre><code class="javascript">var r = fs.createReadStream('file.txt'); var z = zlib.createGzip(); var w = fs.createWriteStream('file.txt.gz'); r.pipe(z).pipe(w);</code></pre> <p>For example, emulating the Unix <code>cat</code> command: </p> <pre><code class="javascript">process.stdin.pipe(process.stdout);</code></pre> <p>By default <a href="#stream_writable_end_chunk_encoding_callback"><code>end()</code></a> 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>writer</code> open so that "Goodbye" can be written at the end. </p> <pre><code class="javascript">reader.pipe(writer, { end: false }); reader.on('end', () => { writer.end('Goodbye\n'); });</code></pre> <p>Note that <code>process.stderr</code> and <code>process.stdout</code> are never closed until the process exits, regardless of the specified options. </p> <h4>readable.read([size])<span><a class="mark" href="#all_readable_read_size" id="all_readable_read_size">#</a></span></h4> <div class="signature"><ul> <li><code>size</code> <span class="type">Number</span> Optional argument to specify how much data to read.</li> <li>Return <span class="type">String | Buffer | null</span></li> </div></ul> <p>The <code>read()</code> method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return <code>null</code>. </p> <p>If you pass in a <code>size</code> argument, then it will return that many bytes. If <code>size</code> bytes are not available, then it will return <code>null</code>, unless we've ended, in which case it will return the data remaining in the buffer. </p> <p>If you do not specify a <code>size</code> argument, then it will return all the data in the internal buffer. </p> <p>This method should only be called in paused mode. In flowing mode, this method is called automatically until the internal buffer is drained. </p> <pre><code class="javascript">var readable = getReadableStreamSomehow(); readable.on('readable', () => { var chunk; while (null !== (chunk = readable.read())) { console.log('got %d bytes of data', chunk.length); } });</code></pre> <p>If this method returns a data chunk, then it will also trigger the emission of a <a href="#stream_event_data"><code>'data'</code></a> event. </p> <p>Note that calling <code>readable.read([size])</code> after the <code>'end'</code> event has been triggered will return <code>null</code>. No runtime error will be raised. </p> <h4>readable.resume()<span><a class="mark" href="#all_readable_resume" id="all_readable_resume">#</a></span></h4> <div class="signature"><ul> <li>Return: <code>this</code></li> </div></ul> <p>This method will cause the readable stream to resume emitting <code>data</code> events. </p> <p>This method will switch the stream into flowing mode. If you do <em>not</em> want to consume the data from a stream, but you <em>do</em> want to get to its <code>'end'</code> event, you can call <a href="#stream_readable_resume"><code>readable.resume()</code></a> to open the flow of data. </p> <pre><code class="javascript">var readable = getReadableStreamSomehow(); readable.resume(); readable.on('end', () => { console.log('got to the end, but did not read anything'); });</code></pre> <h4>readable.setEncoding(encoding)<span><a class="mark" href="#all_readable_setencoding_encoding" id="all_readable_setencoding_encoding">#</a></span></h4> <div class="signature"><ul> <li><code>encoding</code> <span class="type">String</span> The encoding to use.</li> <li>Return: <code>this</code></li> </div></ul> <p>Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. For example, if you do <code>readable.setEncoding('utf8')</code>, then the output data will be interpreted as UTF-8 data, and returned as strings. If you do <code>readable.setEncoding('hex')</code>, then the data will be encoded in hexadecimal string format. </p> <p>This properly handles multi-byte characters that would otherwise be potentially mangled if you simply pulled the Buffers directly and called <code>buf.toString(encoding)</code> on them. If you want to read the data as strings, always use this method. </p> <pre><code class="javascript">var readable = getReadableStreamSomehow(); readable.setEncoding('utf8'); readable.on('data', (chunk) => { assert.equal(typeof chunk, 'string'); console.log('got %d characters of string data', chunk.length); });</code></pre> <h4>readable.unpipe([destination])<span><a class="mark" href="#all_readable_unpipe_destination" id="all_readable_unpipe_destination">#</a></span></h4> <div class="signature"><ul> <li><code>destination</code> <span class="type"><a href="#stream_class_stream_writable">Writable</a> Stream</span> Optional specific stream to unpipe</li> </div></ul> <p>This method will remove the hooks set up for a previous <code>pipe()</code> call. </p> <p>If the destination is not specified, then all pipes are removed. </p> <p>If the destination is specified, but no pipe is set up for it, then this is a no-op. </p> <pre><code class="javascript">var readable = getReadableStreamSomehow(); var writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt', // but only for the first second readable.pipe(writable); setTimeout(() => { console.log('stop writing to file.txt'); readable.unpipe(writable); console.log('manually close the file stream'); writable.end(); }, 1000);</code></pre> <h4>readable.unshift(chunk)<span><a class="mark" href="#all_readable_unshift_chunk" id="all_readable_unshift_chunk">#</a></span></h4> <div class="signature"><ul> <li><code>chunk</code> <span class="type">Buffer | String</span> Chunk of data to unshift onto the read queue</li> </div></ul> <p>This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. </p> <p>Note that <code>stream.unshift(chunk)</code> cannot be called after the <code>'end'</code> event has been triggered; a runtime error will be raised. </p> <p>If you find that you must often call <code>stream.unshift(chunk)</code> in your programs, consider implementing a <a href="#stream_class_stream_transform">Transform</a> stream instead. (See API for Stream Implementors, below.) </p> <pre><code class="javascript">// Pull off a header delimited by \n\n // use unshift() if we get too much // Call the callback with (error, header, stream) const StringDecoder = require('string_decoder').StringDecoder; function parseHeader(stream, callback) { stream.on('error', callback); stream.on('readable', onReadable); var decoder = new StringDecoder('utf8'); var header = ''; function onReadable() { var chunk; while (null !== (chunk = stream.read())) { var str = decoder.write(chunk); if (str.match(/\n\n/)) { // found the header boundary var split = str.split(/\n\n/); header += split.shift(); var remaining = split.join('\n\n'); var buf = new Buffer(remaining, 'utf8'); if (buf.length) stream.unshift(buf); stream.removeListener('error', callback); stream.removeListener('readable', onReadable); // now the body of the message can be read from the stream. callback(null, header, stream); } else { // still reading the header. header += str; } } } }</code></pre> <p>Note that, unlike <code>stream.push(chunk)</code>, <code>stream.unshift(chunk)</code> will not end the reading process by resetting the internal reading state of the stream. This can cause unexpected results if <code>unshift</code> is called during a read (i.e. from within a <code>_read</code> implementation on a custom stream). Following the call to <code>unshift</code> with an immediate <code>stream.push('')</code> will reset the reading state appropriately, however it is best to simply avoid calling <code>unshift</code> while in the process of performing a read. </p> <h4>readable.wrap(stream)<span><a class="mark" href="#all_readable_wrap_stream" id="all_readable_wrap_stream">#</a></span></h4> <div class="signature"><ul> <li><code>stream</code> <span class="type">Stream</span> An "old style" readable stream</li> </div></ul> <p>Versions of Node.js prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) </p> <p>If you are using an older Node.js library that emits <code>'data'</code> events and has a <a href="#stream_readable_pause"><code>pause()</code></a> method that is advisory only, then you can use the <code>wrap()</code> method to create a <a href="#stream_class_stream_readable">Readable</a> stream that uses the old stream as its data source. </p> <p>You will very rarely ever need to call this function, but it exists as a convenience for interacting with old Node.js programs and libraries. </p> <p>For example: </p> <pre><code class="javascript">const OldReader = require('./old-api-module.js').OldReader; const Readable = require('stream').Readable; const oreader = new OldReader; const myReader = new Readable().wrap(oreader); myReader.on('readable', () => { myReader.read(); // etc. });</code></pre> <h3>Class: stream.Transform<span><a class="mark" href="#all_class_stream_transform" id="all_class_stream_transform">#</a></span></h3> <p>Transform streams are <a href="#stream_class_stream_duplex">Duplex</a> streams where the output is in some way computed from the input. They implement both the <a href="#stream_class_stream_readable">Readable</a> and <a href="#stream_class_stream_writable">Writable</a> interfaces. See above for usage. </p> <p>Examples of Transform streams include: </p> <ul> <li><a href="zlib.html">zlib streams</a></li> <li><a href="crypto.html">crypto streams</a></li> </ul> <h3>Class: stream.Writable<span><a class="mark" href="#all_class_stream_writable" id="all_class_stream_writable">#</a></span></h3> <!--type=class--> <p>The Writable stream interface is an abstraction for a <em>destination</em> that you are writing data <em>to</em>. </p> <p>Examples of writable streams include: </p> <ul> <li><a href="http.html#http_class_http_clientrequest">http requests, on the client</a></li> <li><a href="http.html#http_class_http_serverresponse">http responses, on the server</a></li> <li><a href="fs.html#fs_class_fs_writestream">fs write streams</a></li> <li><a href="zlib.html">zlib streams</a></li> <li><a href="crypto.html">crypto streams</a></li> <li><a href="net.html#net_class_net_socket">tcp sockets</a></li> <li><a href="child_process.html#child_process_child_stdin">child process stdin</a></li> <li><a href="process.html#process_process_stdout"><code>process.stdout</code></a>, <a href="process.html#process_process_stderr"><code>process.stderr</code></a></li> </ul> <h4>Event: 'drain'<span><a class="mark" href="#all_event_drain_1" id="all_event_drain_1">#</a></span></h4> <p>If a <a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write(chunk)</code></a> call returns false, then the <code>'drain'</code> event will indicate when it is appropriate to begin writing more data to the stream. </p> <pre><code class="javascript">// Write the data to the supplied writable stream one million times. // Be attentive to back-pressure. function writeOneMillionTimes(writer, data, encoding, callback) { var i = 1000000; write(); function write() { var ok = true; do { i -= 1; if (i === 0) { // last time! writer.write(data, encoding, callback); } else { // see if we should continue, or wait // don't pass the callback, because we're not done yet. ok = writer.write(data, encoding); } } while (i > 0 && ok); if (i > 0) { // had to stop early! // write some more once it drains writer.once('drain', write); } } }</code></pre> <h4>Event: 'error'<span><a class="mark" href="#all_event_error_7" id="all_event_error_7">#</a></span></h4> <div class="signature"><ul> <li><span class="type">Error object</span></li> </div></ul> <p>Emitted if there was an error when writing or piping data. </p> <h4>Event: 'finish'<span><a class="mark" href="#all_event_finish_1" id="all_event_finish_1">#</a></span></h4> <p>When the <a href="#stream_writable_end_chunk_encoding_callback"><code>end()</code></a> method has been called, and all data has been flushed to the underlying system, this event is emitted. </p> <pre><code class="javascript">var writer = getWritableStreamSomehow(); for (var i = 0; i < 100; i ++) { writer.write('hello, #${i}!\n'); } writer.end('this is the end\n'); writer.on('finish', () => { console.error('all writes are now complete.'); });</code></pre> <h4>Event: 'pipe'<span><a class="mark" href="#all_event_pipe" id="all_event_pipe">#</a></span></h4> <div class="signature"><ul> <li><code>src</code> <span class="type"><a href="#stream_class_stream_readable">Readable</a> Stream</span> source stream that is piping to this writable</li> </div></ul> <p>This is emitted whenever the <code>pipe()</code> method is called on a readable stream, adding this writable to its set of destinations. </p> <pre><code class="javascript">var writer = getWritableStreamSomehow(); var reader = getReadableStreamSomehow(); writer.on('pipe', (src) => { console.error('something is piping into the writer'); assert.equal(src, reader); }); reader.pipe(writer);</code></pre> <h4>Event: 'unpipe'<span><a class="mark" href="#all_event_unpipe" id="all_event_unpipe">#</a></span></h4> <div class="signature"><ul> <li><code>src</code> <span class="type"><a href="#stream_class_stream_readable">Readable</a> Stream</span> The source stream that <a href="#stream_readable_unpipe_destination">unpiped</a> this writable</li> </div></ul> <p>This is emitted whenever the <a href="#stream_readable_unpipe_destination"><code>unpipe()</code></a> method is called on a readable stream, removing this writable from its set of destinations. </p> <pre><code class="javascript">var writer = getWritableStreamSomehow(); var reader = getReadableStreamSomehow(); writer.on('unpipe', (src) => { console.error('something has stopped piping into the writer'); assert.equal(src, reader); }); reader.pipe(writer); reader.unpipe(writer);</code></pre> <h4>writable.cork()<span><a class="mark" href="#all_writable_cork" id="all_writable_cork">#</a></span></h4> <p>Forces buffering of all writes. </p> <p>Buffered data will be flushed either at <code>.uncork()</code> or at <code>.end()</code> call. </p> <h4>writable.end([chunk][, encoding][, callback])<span><a class="mark" href="#all_writable_end_chunk_encoding_callback" id="all_writable_end_chunk_encoding_callback">#</a></span></h4> <div class="signature"><ul> <li><code>chunk</code> <span class="type">String | Buffer</span> Optional data to write</li> <li><code>encoding</code> <span class="type">String</span> The encoding, if <code>chunk</code> is a String</li> <li><code>callback</code> <span class="type">Function</span> Optional callback for when the stream is finished</li> </div></ul> <p>Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the <code>'finish'</code> event. </p> <p>Calling <a href="#stream_writable_write_chunk_encoding_callback"><code>write()</code></a> after calling <a href="#stream_writable_end_chunk_encoding_callback"><code>end()</code></a> will raise an error. </p> <pre><code class="javascript">// write 'hello, ' and then end with 'world!' var file = fs.createWriteStream('example.txt'); file.write('hello, '); file.end('world!'); // writing more now is not allowed!</code></pre> <h4>writable.setDefaultEncoding(encoding)<span><a class="mark" href="#all_writable_setdefaultencoding_encoding" id="all_writable_setdefaultencoding_encoding">#</a></span></h4> <div class="signature"><ul> <li><code>encoding</code> <span class="type">String</span> The new default encoding</li> </div></ul> <p>Sets the default encoding for a writable stream. </p> <h4>writable.uncork()<span><a class="mark" href="#all_writable_uncork" id="all_writable_uncork">#</a></span></h4> <p>Flush all data, buffered since <code>.cork()</code> call. </p> <h4>writable.write(chunk[, encoding][, callback])<span><a class="mark" href="#all_writable_write_chunk_encoding_callback" id="all_writable_write_chunk_encoding_callback">#</a></span></h4> <div class="signature"><ul> <li><code>chunk</code> <span class="type">String | Buffer</span> The data to write</li> <li><code>encoding</code> <span class="type">String</span> The encoding, if <code>chunk</code> is a String</li> <li><code>callback</code> <span class="type">Function</span> Callback for when this chunk of data is flushed</li> <li>Returns: <span class="type">Boolean</span> True if the data was handled completely.</li> </div></ul> <p>This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. </p> <p>The return value indicates if you should continue writing right now. If the data had to be buffered internally, then it will return <code>false</code>. Otherwise, it will return <code>true</code>. </p> <p>This return value is strictly advisory. You MAY continue to write, even if it returns <code>false</code>. However, writes will be buffered in memory, so it is best not to do this excessively. Instead, wait for the <code>'drain'</code> event before writing more data. </p> <h2>API for Stream Implementors<span><a class="mark" href="#all_api_for_stream_implementors" id="all_api_for_stream_implementors">#</a></span></h2> <!--type=misc--> <p>To implement any sort of stream, the pattern is the same: </p> <ol> <li>Extend the appropriate parent class in your own subclass. (The <a href="util.html#util_util_inherits_constructor_superconstructor"><code>util.inherits</code></a> method is particularly helpful for this.)</li> <li>Call the appropriate parent class constructor in your constructor, to be sure that the internal mechanisms are set up properly.</li> <li>Implement one or more specific methods, as detailed below.</li> </ol> <p>The class to extend and the method(s) to implement depend on the sort of stream class you are writing: </p> <table> <thead> <tr> <th> <p>Use-case</p> </th> <th> <p>Class</p> </th> <th> <p>Method(s) to implement</p> </th> </tr> </thead> <tr> <td> <p>Reading only</p> </td> <td> <p><a href="#stream_class_stream_readable_1">Readable</a></p> </td> <td> <p><code><a href="#stream_readable_read_size_1">_read</a></code></p> </td> </tr> <tr> <td> <p>Writing only</p> </td> <td> <p><a href="#stream_class_stream_writable_1">Writable</a></p> </td> <td> <p><code><a href="#stream_writable_write_chunk_encoding_callback_1">_write</a></code>, <code><a href="#stream_writable_writev_chunks_callback">_writev</a></code></p> </td> </tr> <tr> <td> <p>Reading and writing</p> </td> <td> <p><a href="#stream_class_stream_duplex_1">Duplex</a></p> </td> <td> <p><code><a href="#stream_readable_read_size_1">_read</a></code>, <code><a href="#stream_writable_write_chunk_encoding_callback_1">_write</a></code>, <code><a href="#stream_writable_writev_chunks_callback">_writev</a></code></p> </td> </tr> <tr> <td> <p>Operate on written data, then read the result</p> </td> <td> <p><a href="#stream_class_stream_transform_1">Transform</a></p> </td> <td> <p><code><a href="#stream_transform_transform_chunk_encoding_callback">_transform</a></code>, <code><a href="#stream_transform_flush_callback">_flush</a></code></p> </td> </tr> </table> <p>In your implementation code, it is very important to never call the methods described in <a href="#stream_api_for_stream_consumers">API for Stream Consumers</a> above. Otherwise, you can potentially cause adverse side effects in programs that consume your streaming interfaces. </p> <h3>Class: stream.Duplex<span><a class="mark" href="#all_class_stream_duplex_1" id="all_class_stream_duplex_1">#</a></span></h3> <!--type=class--> <p>A "duplex" stream is one that is both Readable and Writable, such as a TCP socket connection. </p> <p>Note that <code>stream.Duplex</code> is an abstract class designed to be extended with an underlying implementation of the <code>_read(size)</code> and <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write(chunk, encoding, callback)</code></a> methods as you would with a Readable or Writable stream class. </p> <p>Since JavaScript doesn't have multiple prototypal inheritance, this class prototypally inherits from Readable, and then parasitically from Writable. It is thus up to the user to implement both the lowlevel <code>_read(n)</code> method as well as the lowlevel <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write(chunk, encoding, callback)</code></a> method on extension duplex classes. </p> <h4>new stream.Duplex(options)<span><a class="mark" href="#all_new_stream_duplex_options" id="all_new_stream_duplex_options">#</a></span></h4> <div class="signature"><ul> <li><code>options</code> <span class="type">Object</span> Passed to both Writable and Readable constructors. Also has the following fields:<ul> <li><code>allowHalfOpen</code> <span class="type">Boolean</span> Default=true. If set to <code>false</code>, then the stream will automatically end the readable side when the writable side ends and vice versa.</li> <li><code>readableObjectMode</code> <span class="type">Boolean</span> Default=false. Sets <code>objectMode</code> for readable side of the stream. Has no effect if <code>objectMode</code> is <code>true</code>.</li> <li><code>writableObjectMode</code> <span class="type">Boolean</span> Default=false. Sets <code>objectMode</code> for writable side of the stream. Has no effect if <code>objectMode</code> is <code>true</code>.</li> </ul> </li> </div></ul> <p>In classes that extend the Duplex class, make sure to call the constructor so that the buffering settings can be properly initialized. </p> <h3>Class: stream.PassThrough<span><a class="mark" href="#all_class_stream_passthrough" id="all_class_stream_passthrough">#</a></span></h3> <p>This is a trivial implementation of a <a href="#stream_class_stream_transform">Transform</a> stream that simply passes the input bytes across to the output. Its purpose is mainly for examples and testing, but there are occasionally use cases where it can come in handy as a building block for novel sorts of streams. </p> <h3>Class: stream.Readable<span><a class="mark" href="#all_class_stream_readable_1" id="all_class_stream_readable_1">#</a></span></h3> <!--type=class--> <p><code>stream.Readable</code> is an abstract class designed to be extended with an underlying implementation of the <a href="#stream_readable_read_size_1"><code>_read(size)</code></a> method. </p> <p>Please see above under <a href="#stream_api_for_stream_consumers">API for Stream Consumers</a> for how to consume streams in your programs. What follows is an explanation of how to implement Readable streams in your programs. </p> <h4>new stream.Readable(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#all_new_stream_readable_options" id="all_new_stream_readable_options">#</a></span></h4> <div class="signature"><ul> <li><code>options</code> <span class="type">Object</span><ul> <li><code>highWaterMark</code> <span class="type">Number</span> The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb, or 16 for <code>objectMode</code> streams</li> <li><code>encoding</code> <span class="type">String</span> If specified, then buffers will be decoded to strings using the specified encoding. Default=null</li> <li><code>objectMode</code> <span class="type">Boolean</span> Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false</li> </ul> </li> </div></ul> <p>In classes that extend the Readable class, make sure to call the Readable constructor so that the buffering settings can be properly initialized. </p> <h4>readable._read(size)<span><a class="mark" href="#all_readable_read_size_1" id="all_readable_read_size_1">#</a></span></h4> <div class="signature"><ul> <li><code>size</code> <span class="type">Number</span> Number of bytes to read asynchronously</li> </div></ul> <p>Note: <strong>Implement this method, but do NOT call it directly.</strong> </p> <p>This method is prefixed with an underscore because it is internal to the class that defines it and should only be called by the internal Readable class methods. All Readable stream implementations must provide a _read method to fetch data from the underlying resource. </p> <p>When _read is called, if data is available from the resource, <code>_read</code> should start pushing that data into the read queue by calling <code>this.push(dataChunk)</code>. <code>_read</code> should continue reading from the resource and pushing data until push returns false, at which point it should stop reading from the resource. Only when _read is called again after it has stopped should it start reading more data from the resource and pushing that data onto the queue. </p> <p>Note: once the <code>_read()</code> method is called, it will not be called again until the <code>push</code> method is called. </p> <p>The <code>size</code> argument is advisory. Implementations where a "read" is a single call that returns data can use this to know how much data to fetch. Implementations where that is not relevant, such as TCP or TLS, may ignore this argument, and simply provide data whenever it becomes available. There is no need, for example to "wait" until <code>size</code> bytes are available before calling <a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>. </p> <h4>readable.push(chunk[, encoding])<span><a class="mark" href="#all_readable_push_chunk_encoding" id="all_readable_push_chunk_encoding">#</a></span></h4> <div class="signature"><ul> <li><code>chunk</code> <span class="type">Buffer | null | String</span> Chunk of data to push into the read queue</li> <li><code>encoding</code> <span class="type">String</span> Encoding of String chunks. Must be a valid Buffer encoding, such as <code>'utf8'</code> or <code>'ascii'</code></li> <li>return <span class="type">Boolean</span> Whether or not more pushes should be performed</li> </div></ul> <p>Note: <strong>This method should be called by Readable implementors, NOT by consumers of Readable streams.</strong> </p> <p>If a value other than null is passed, The <code>push()</code> method adds a chunk of data into the queue for subsequent stream processors to consume. If <code>null</code> is passed, it signals the end of the stream (EOF), after which no more data can be written. </p> <p>The data added with <code>push</code> can be pulled out by calling the <code>read()</code> method when the <code>'readable'</code> event fires. </p> <p>This API is designed to be as flexible as possible. For example, you may be wrapping a lower-level source which has some sort of pause/resume mechanism, and a data callback. In those cases, you could wrap the low-level source object by doing something like this: </p> <pre><code class="javascript">// source is an object with readStop() and readStart() methods, // and an `ondata` member that gets called when it has data, and // an `onend` member that gets called when the data is over. util.inherits(SourceWrapper, Readable); function SourceWrapper(options) { Readable.call(this, options); this._source = getLowlevelSourceObject(); var self = this; // Every time there's data, we push it into the internal buffer. this._source.ondata = function(chunk) { // if push() returns false, then we need to stop reading from source if (!self.push(chunk)) self._source.readStop(); }; // When the source ends, we push the EOF-signaling `null` chunk this._source.onend = function() { self.push(null); }; } // _read will be called when the stream wants to pull more data in // the advisory size argument is ignored in this case. SourceWrapper.prototype._read = function(size) { this._source.readStart(); };</code></pre> <h4>Example: A Counting Stream<span><a class="mark" href="#all_example_a_counting_stream" id="all_example_a_counting_stream">#</a></span></h4> <!--type=example--> <p>This is a basic example of a Readable stream. It emits the numerals from 1 to 1,000,000 in ascending order, and then ends. </p> <pre><code class="javascript">const Readable = require('stream').Readable; const util = require('util'); util.inherits(Counter, Readable); function Counter(opt) { Readable.call(this, opt); this._max = 1000000; this._index = 1; } Counter.prototype._read = function() { var i = this._index++; if (i > this._max) this.push(null); else { var str = '' + i; var buf = new Buffer(str, 'ascii'); this.push(buf); } };</code></pre> <h4>Example: SimpleProtocol v1 (Sub-optimal)<span><a class="mark" href="#all_example_simpleprotocol_v1_sub_optimal" id="all_example_simpleprotocol_v1_sub_optimal">#</a></span></h4> <p>This is similar to the <code>parseHeader</code> function described above, but implemented as a custom stream. Also, note that this implementation does not convert the incoming data to a string. </p> <p>However, this would be better implemented as a <a href="#stream_class_stream_transform">Transform</a> stream. See below for a better implementation. </p> <pre><code class="javascript">// A parser for a simple data protocol. // The "header" is a JSON object, followed by 2 \n characters, and // then a message body. // // NOTE: This can be done more simply as a Transform stream! // Using Readable directly for this is sub-optimal. See the // alternative example below under the Transform section. const Readable = require('stream').Readable; const util = require('util'); util.inherits(SimpleProtocol, Readable); function SimpleProtocol(source, options) { if (!(this instanceof SimpleProtocol)) return new SimpleProtocol(source, options); Readable.call(this, options); this._inBody = false; this._sawFirstCr = false; // source is a readable stream, such as a socket or file this._source = source; var self = this; source.on('end', () => { self.push(null); }); // give it a kick whenever the source is readable // read(0) will not consume any bytes source.on('readable', () => { self.read(0); }); this._rawHeader = []; this.header = null; } SimpleProtocol.prototype._read = function(n) { if (!this._inBody) { var chunk = this._source.read(); // if the source doesn't have data, we don't have data yet. if (chunk === null) return this.push(''); // check if the chunk has a \n\n var split = -1; for (var i = 0; i < chunk.length; i++) { if (chunk[i] === 10) { // '\n' if (this._sawFirstCr) { split = i; break; } else { this._sawFirstCr = true; } } else { this._sawFirstCr = false; } } if (split === -1) { // still waiting for the \n\n // stash the chunk, and try again. this._rawHeader.push(chunk); this.push(''); } else { this._inBody = true; var h = chunk.slice(0, split); this._rawHeader.push(h); var header = Buffer.concat(this._rawHeader).toString(); try { this.header = JSON.parse(header); } catch (er) { this.emit('error', new Error('invalid simple protocol data')); return; } // now, because we got some extra data, unshift the rest // back into the read queue so that our consumer will see it. var b = chunk.slice(split); this.unshift(b); // calling unshift by itself does not reset the reading state // of the stream; since we're inside _read, doing an additional // push('') will reset the state appropriately. this.push(''); // and let them know that we are done parsing the header. this.emit('header', this.header); } } else { // from there on, just provide the data to our consumer. // careful not to push(null), since that would indicate EOF. var chunk = this._source.read(); if (chunk) this.push(chunk); } }; // Usage: // var parser = new SimpleProtocol(source); // Now parser is a readable stream that will emit 'header' // with the parsed header data.</code></pre> <h3>Class: stream.Transform<span><a class="mark" href="#all_class_stream_transform_1" id="all_class_stream_transform_1">#</a></span></h3> <p>A "transform" stream is a duplex stream where the output is causally connected in some way to the input, such as a <a href="zlib.html">zlib</a> stream or a <a href="crypto.html">crypto</a> stream. </p> <p>There is no requirement that the output be the same size as the input, the same number of chunks, or arrive at the same time. For example, a Hash stream will only ever have a single chunk of output which is provided when the input is ended. A zlib stream will produce output that is either much smaller or much larger than its input. </p> <p>Rather than implement the <a href="#stream_readable_read_size_1"><code>_read()</code></a> and <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write()</code></a> methods, Transform classes must implement the <code>_transform()</code> method, and may optionally also implement the <code>_flush()</code> method. (See below.) </p> <h4>new stream.Transform(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#all_new_stream_transform_options" id="all_new_stream_transform_options">#</a></span></h4> <div class="signature"><ul> <li><code>options</code> <span class="type">Object</span> Passed to both Writable and Readable constructors.</li> </div></ul> <p>In classes that extend the Transform class, make sure to call the constructor so that the buffering settings can be properly initialized. </p> <h4>Events: 'finish' and 'end'<span><a class="mark" href="#all_events_finish_and_end" id="all_events_finish_and_end">#</a></span></h4> <p>The <a href="#stream_event_finish"><code>'finish'</code></a> and <a href="#stream_event_end"><code>'end'</code></a> events are from the parent Writable and Readable classes respectively. The <code>'finish'</code> event is fired after <code>.end()</code> is called and all chunks have been processed by <code>_transform</code>, <code>end</code> is fired after all data has been output which is after the callback in <code>_flush</code> has been called. </p> <h4>transform._flush(callback)<span><a class="mark" href="#all_transform_flush_callback" id="all_transform_flush_callback">#</a></span></h4> <div class="signature"><ul> <li><code>callback</code> <span class="type">Function</span> Call this function (optionally with an error argument) when you are done flushing any remaining data.</li> </div></ul> <p>Note: <strong>This function MUST NOT be called directly.</strong> It MAY be implemented by child classes, and if so, will be called by the internal Transform class methods only. </p> <p>In some cases, your transform operation may need to emit a bit more data at the end of the stream. For example, a <code>Zlib</code> compression stream will store up some internal state so that it can optimally compress the output. At the end, however, it needs to do the best it can with what is left, so that the data will be complete. </p> <p>In those cases, you can implement a <code>_flush</code> method, which will be called at the very end, after all the written data is consumed, but before emitting <code>end</code> to signal the end of the readable side. Just like with <code>_transform</code>, call <code>transform.push(chunk)</code> zero or more times, as appropriate, and call <code>callback</code> when the flush operation is complete. </p> <p>This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you <strong>are</strong> expected to override this method in your own extension classes. </p> <h4>transform._transform(chunk, encoding, callback)<span><a class="mark" href="#all_transform_transform_chunk_encoding_callback" id="all_transform_transform_chunk_encoding_callback">#</a></span></h4> <div class="signature"><ul> <li><code>chunk</code> <span class="type">Buffer | String</span> The chunk to be transformed. Will <strong>always</strong> be a buffer unless the <code>decodeStrings</code> option was set to <code>false</code>.</li> <li><code>encoding</code> <span class="type">String</span> If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value - 'buffer', ignore it in this case.</li> <li><code>callback</code> <span class="type">Function</span> Call this function (optionally with an error argument and data) when you are done processing the supplied chunk.</li> </div></ul> <p>Note: <strong>This function MUST NOT be called directly.</strong> It should be implemented by child classes, and called by the internal Transform class methods only. </p> <p>All Transform stream implementations must provide a <code>_transform</code> method to accept input and produce output. </p> <p><code>_transform</code> should do whatever has to be done in this specific Transform class, to handle the bytes being written, and pass them off to the readable portion of the interface. Do asynchronous I/O, process things, and so on. </p> <p>Call <code>transform.push(outputChunk)</code> 0 or more times to generate output from this input chunk, depending on how much data you want to output as a result of this chunk. </p> <p>Call the callback function only when the current chunk is completely consumed. Note that there may or may not be output as a result of any particular input chunk. If you supply a second argument to the callback it will be passed to the push method. In other words the following are equivalent: </p> <pre><code class="javascript">transform.prototype._transform = function (data, encoding, callback) { this.push(data); callback(); }; transform.prototype._transform = function (data, encoding, callback) { callback(null, data); };</code></pre> <p>This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you <strong>are</strong> expected to override this method in your own extension classes. </p> <h4>Example: <code>SimpleProtocol</code> parser v2<span><a class="mark" href="#all_example_simpleprotocol_parser_v2" id="all_example_simpleprotocol_parser_v2">#</a></span></h4> <p>The example above of a simple protocol parser can be implemented simply by using the higher level <a href="#stream_class_stream_transform">Transform</a> stream class, similar to the <code>parseHeader</code> and <code>SimpleProtocol v1</code> examples above. </p> <p>In this example, rather than providing the input as an argument, it would be piped into the parser, which is a more idiomatic Node.js stream approach. </p> <pre><code class="javascript">const util = require('util'); const Transform = require('stream').Transform; util.inherits(SimpleProtocol, Transform); function SimpleProtocol(options) { if (!(this instanceof SimpleProtocol)) return new SimpleProtocol(options); Transform.call(this, options); this._inBody = false; this._sawFirstCr = false; this._rawHeader = []; this.header = null; } SimpleProtocol.prototype._transform = function(chunk, encoding, done) { if (!this._inBody) { // check if the chunk has a \n\n var split = -1; for (var i = 0; i < chunk.length; i++) { if (chunk[i] === 10) { // '\n' if (this._sawFirstCr) { split = i; break; } else { this._sawFirstCr = true; } } else { this._sawFirstCr = false; } } if (split === -1) { // still waiting for the \n\n // stash the chunk, and try again. this._rawHeader.push(chunk); } else { this._inBody = true; var h = chunk.slice(0, split); this._rawHeader.push(h); var header = Buffer.concat(this._rawHeader).toString(); try { this.header = JSON.parse(header); } catch (er) { this.emit('error', new Error('invalid simple protocol data')); return; } // and let them know that we are done parsing the header. this.emit('header', this.header); // now, because we got some extra data, emit this first. this.push(chunk.slice(split)); } } else { // from there on, just provide the data to our consumer as-is. this.push(chunk); } done(); }; // Usage: // var parser = new SimpleProtocol(); // source.pipe(parser) // Now parser is a readable stream that will emit 'header' // with the parsed header data.</code></pre> <h3>Class: stream.Writable<span><a class="mark" href="#all_class_stream_writable_1" id="all_class_stream_writable_1">#</a></span></h3> <!--type=class--> <p><code>stream.Writable</code> is an abstract class designed to be extended with an underlying implementation of the <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write(chunk, encoding, callback)</code></a> method. </p> <p>Please see above under <a href="#stream_api_for_stream_consumers">API for Stream Consumers</a> for how to consume writable streams in your programs. What follows is an explanation of how to implement Writable streams in your programs. </p> <h4>new stream.Writable(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#all_new_stream_writable_options" id="all_new_stream_writable_options">#</a></span></h4> <div class="signature"><ul> <li><code>options</code> <span class="type">Object</span><ul> <li><code>highWaterMark</code> <span class="type">Number</span> Buffer level when <a href="#stream_writable_write_chunk_encoding_callback"><code>write()</code></a> starts returning false. Default=16kb, or 16 for <code>objectMode</code> streams</li> <li><code>decodeStrings</code> <span class="type">Boolean</span> Whether or not to decode strings into Buffers before passing them to <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write()</code></a>. Default=true</li> <li><code>objectMode</code> <span class="type">Boolean</span> Whether or not the <code>write(anyObj)</code> is a valid operation. If set you can write arbitrary data instead of only <code>Buffer</code> / <code>String</code> data. Default=false</li> </ul> </li> </div></ul> <p>In classes that extend the Writable class, make sure to call the constructor so that the buffering settings can be properly initialized. </p> <h4>writable._write(chunk, encoding, callback)<span><a class="mark" href="#all_writable_write_chunk_encoding_callback_1" id="all_writable_write_chunk_encoding_callback_1">#</a></span></h4> <div class="signature"><ul> <li><code>chunk</code> <span class="type">Buffer | String</span> The chunk to be written. Will <strong>always</strong> be a buffer unless the <code>decodeStrings</code> option was set to <code>false</code>.</li> <li><code>encoding</code> <span class="type">String</span> If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value - 'buffer', ignore it in this case.</li> <li><code>callback</code> <span class="type">Function</span> Call this function (optionally with an error argument) when you are done processing the supplied chunk.</li> </div></ul> <p>All Writable stream implementations must provide a <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write()</code></a> method to send data to the underlying resource. </p> <p>Note: <strong>This function MUST NOT be called directly.</strong> It should be implemented by child classes, and called by the internal Writable class methods only. </p> <p>Call the callback using the standard <code>callback(error)</code> pattern to signal that the write completed successfully or with an error. </p> <p>If the <code>decodeStrings</code> flag is set in the constructor options, then <code>chunk</code> may be a string rather than a Buffer, and <code>encoding</code> will indicate the sort of string that it is. This is to support implementations that have an optimized handling for certain string data encodings. If you do not explicitly set the <code>decodeStrings</code> option to <code>false</code>, then you can safely ignore the <code>encoding</code> argument, and assume that <code>chunk</code> will always be a Buffer. </p> <p>This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you <strong>are</strong> expected to override this method in your own extension classes. </p> <h4>writable._writev(chunks, callback)<span><a class="mark" href="#all_writable_writev_chunks_callback" id="all_writable_writev_chunks_callback">#</a></span></h4> <div class="signature"><ul> <li><code>chunks</code> <span class="type">Array</span> The chunks to be written. Each chunk has following format: <code>{ chunk: ..., encoding: ... }</code>.</li> <li><code>callback</code> <span class="type">Function</span> Call this function (optionally with an error argument) when you are done processing the supplied chunks.</li> </div></ul> <p>Note: <strong>This function MUST NOT be called directly.</strong> It may be implemented by child classes, and called by the internal Writable class methods only. </p> <p>This function is completely optional to implement. In most cases it is unnecessary. If implemented, it will be called with all the chunks that are buffered in the write queue. </p> <h2>Simplified Constructor API<span><a class="mark" href="#all_simplified_constructor_api" id="all_simplified_constructor_api">#</a></span></h2> <!--type=misc--> <p>In simple cases there is now the added benefit of being able to construct a stream without inheritance. </p> <p>This can be done by passing the appropriate methods as constructor options: </p> <p>Examples: </p> <h3>Duplex<span><a class="mark" href="#all_duplex" id="all_duplex">#</a></span></h3> <pre><code class="javascript">var duplex = new stream.Duplex({ read: function(n) { // sets this._read under the hood // push data onto the read queue, passing null // will signal the end of the stream (EOF) this.push(chunk); }, write: function(chunk, encoding, next) { // sets this._write under the hood // An optional error can be passed as the first argument next() } }); // or var duplex = new stream.Duplex({ read: function(n) { // sets this._read under the hood // push data onto the read queue, passing null // will signal the end of the stream (EOF) this.push(chunk); }, writev: function(chunks, next) { // sets this._writev under the hood // An optional error can be passed as the first argument next() } });</code></pre> <h3>Readable<span><a class="mark" href="#all_readable" id="all_readable">#</a></span></h3> <pre><code class="javascript">var readable = new stream.Readable({ read: function(n) { // sets this._read under the hood // push data onto the read queue, passing null // will signal the end of the stream (EOF) this.push(chunk); } });</code></pre> <h3>Transform<span><a class="mark" href="#all_transform" id="all_transform">#</a></span></h3> <pre><code class="javascript">var transform = new stream.Transform({ transform: function(chunk, encoding, next) { // sets this._transform under the hood // generate output as many times as needed // this.push(chunk); // call when the current chunk is consumed next(); }, flush: function(done) { // sets this._flush under the hood // generate output as many times as needed // this.push(chunk); done(); } });</code></pre> <h3>Writable<span><a class="mark" href="#all_writable" id="all_writable">#</a></span></h3> <pre><code class="javascript">var writable = new stream.Writable({ write: function(chunk, encoding, next) { // sets this._write under the hood // An optional error can be passed as the first argument next() } }); // or var writable = new stream.Writable({ writev: function(chunks, next) { // sets this._writev under the hood // An optional error can be passed as the first argument next() } });</code></pre> <h2>Streams: Under the Hood<span><a class="mark" href="#all_streams_under_the_hood" id="all_streams_under_the_hood">#</a></span></h2> <!--type=misc--> <h3>Buffering<span><a class="mark" href="#all_buffering" id="all_buffering">#</a></span></h3> <!--type=misc--> <p>Both Writable and Readable streams will buffer data on an internal object which can be retrieved from <code>_writableState.getBuffer()</code> or <code>_readableState.buffer</code>, respectively. </p> <p>The amount of data that will potentially be buffered depends on the <code>highWaterMark</code> option which is passed into the constructor. </p> <p>Buffering in Readable streams happens when the implementation calls <a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not call <code>stream.read()</code>, then the data will sit in the internal queue until it is consumed. </p> <p>Buffering in Writable streams happens when the user calls <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(chunk)</code></a> repeatedly, even when <code>write()</code> returns <code>false</code>. </p> <p>The purpose of streams, especially with the <code>pipe()</code> method, is to limit the buffering of data to acceptable levels, so that sources and destinations of varying speed will not overwhelm the available memory. </p> <h3>Compatibility with Older Node.js Versions<span><a class="mark" href="#all_compatibility_with_older_node_js_versions" id="all_compatibility_with_older_node_js_versions">#</a></span></h3> <!--type=misc--> <p>In versions of Node.js prior to v0.10, the Readable stream interface was simpler, but also less powerful and less useful. </p> <ul> <li>Rather than waiting for you to call the <code>read()</code> method, <code>'data'</code> events would start emitting immediately. If you needed to do some I/O to decide how to handle data, then you had to store the chunks in some kind of buffer so that they would not be lost.</li> <li>The <a href="#stream_readable_pause"><code>pause()</code></a> method was advisory, rather than guaranteed. This meant that you still had to be prepared to receive <code>'data'</code> events even when the stream was in a paused state.</li> </ul> <p>In Node.js v0.10, the Readable class described below was added. For backwards compatibility with older Node.js programs, Readable streams switch into "flowing mode" when a <code>'data'</code> event handler is added, or when the <a href="#stream_readable_resume"><code>resume()</code></a> method is called. The effect is that, even if you are not using the new <code>read()</code> method and <code>'readable'</code> event, you no longer have to worry about losing <code>'data'</code> chunks. </p> <p>Most programs will continue to function normally. However, this introduces an edge case in the following conditions: </p> <ul> <li>No <a href="#stream_event_data"><code>'data'</code></a> event handler is added.</li> <li>The <a href="#stream_readable_resume"><code>resume()</code></a> method is never called.</li> <li>The stream is not piped to any writable destination.</li> </ul> <p>For example, consider the following code: </p> <pre><code class="javascript">// WARNING! BROKEN! net.createServer((socket) => { // we add an 'end' method, but never consume the data socket.on('end', () => { // It will never get here. socket.end('I got your message (but didnt read it)\n'); }); }).listen(1337);</code></pre> <p>In versions of Node.js prior to v0.10, the incoming message data would be simply discarded. However, in Node.js v0.10 and beyond, the socket will remain paused forever. </p> <p>The workaround in this situation is to call the <code>resume()</code> method to start the flow of data: </p> <pre><code class="javascript">// Workaround net.createServer((socket) => { socket.on('end', () => { socket.end('I got your message (but didnt read it)\n'); }); // start the flow of data, discarding it. socket.resume(); }).listen(1337);</code></pre> <p>In addition to new Readable streams switching into flowing mode, pre-v0.10 style streams can be wrapped in a Readable class using the <code>wrap()</code> method. </p> <h3>Object Mode<span><a class="mark" href="#all_object_mode" id="all_object_mode">#</a></span></h3> <!--type=misc--> <p>Normally, Streams operate on Strings and Buffers exclusively. </p> <p>Streams that are in <strong>object mode</strong> can emit generic JavaScript values other than Buffers and Strings. </p> <p>A Readable stream in object mode will always return a single item from a call to <code>stream.read(size)</code>, regardless of what the size argument is. </p> <p>A Writable stream in object mode will always ignore the <code>encoding</code> argument to <code>stream.write(data, encoding)</code>. </p> <p>The special value <code>null</code> still retains its special value for object mode streams. That is, for object mode readable streams, <code>null</code> as a return value from <code>stream.read()</code> indicates that there is no more data, and <a href="#stream_readable_push_chunk_encoding"><code>stream.push(null)</code></a> will signal the end of stream data (<code>EOF</code>). </p> <p>No streams in Node.js core are object mode streams. This pattern is only used by userland streaming libraries. </p> <p>You should set <code>objectMode</code> in your stream child class constructor on the options object. Setting <code>objectMode</code> mid-stream is not safe. </p> <p>For Duplex streams <code>objectMode</code> can be set exclusively for readable or writable side with <code>readableObjectMode</code> and <code>writableObjectMode</code> respectively. These options can be used to implement parsers and serializers with Transform streams. </p> <pre><code class="javascript">const util = require('util'); const StringDecoder = require('string_decoder').StringDecoder; const Transform = require('stream').Transform; util.inherits(JSONParseStream, Transform); // Gets \n-delimited JSON string data, and emits the parsed objects function JSONParseStream() { if (!(this instanceof JSONParseStream)) return new JSONParseStream(); Transform.call(this, { readableObjectMode : true }); this._buffer = ''; this._decoder = new StringDecoder('utf8'); } JSONParseStream.prototype._transform = function(chunk, encoding, cb) { this._buffer += this._decoder.write(chunk); // split on newlines var lines = this._buffer.split(/\r?\n/); // keep the last partial line buffered this._buffer = lines.pop(); for (var l = 0; l < lines.length; l++) { var line = lines[l]; try { var obj = JSON.parse(line); } catch (er) { this.emit('error', er); return; } // push the parsed object out to the readable consumer this.push(obj); } cb(); }; JSONParseStream.prototype._flush = function(cb) { // Just handle any leftover var rem = this._buffer.trim(); if (rem) { try { var obj = JSON.parse(rem); } catch (er) { this.emit('error', er); return; } // push the parsed object out to the readable consumer this.push(obj); } cb(); };</code></pre> <h3><code>stream.read(0)</code><span><a class="mark" href="#all_stream_read_0" id="all_stream_read_0">#</a></span></h3> <p>There are some cases where you want to trigger a refresh of the underlying readable stream mechanisms, without actually consuming any data. In that case, you can call <code>stream.read(0)</code>, which will always return null. </p> <p>If the internal read buffer is below the <code>highWaterMark</code>, and the stream is not currently reading, then calling <code>read(0)</code> will trigger a low-level <code>_read</code> call. </p> <p>There is almost never a need to do this. However, you will see some cases in Node.js's internals where this is done, particularly in the Readable stream class internals. </p> <h3><code>stream.push('')</code><span><a class="mark" href="#all_stream_push" id="all_stream_push">#</a></span></h3> <p>Pushing a zero-byte string or Buffer (when not in <a href="#stream_object_mode">Object mode</a>) has an interesting side effect. Because it <em>is</em> a call to <a href="#stream_readable_push_chunk_encoding"><code>stream.push()</code></a>, it will end the <code>reading</code> process. However, it does <em>not</em> add any data to the readable buffer, so there's nothing for a user to consume. </p> <p>Very rarely, there are cases where you have no data to provide now, but the consumer of your stream (or, perhaps, another bit of your own code) will know when to check again, by calling <code>stream.read(0)</code>. In those cases, you <em>may</em> call <code>stream.push('')</code>. </p> <p>So far, the only use case for this functionality is in the <a href="tls.html#tls_class_cryptostream"><code>tls.CryptoStream</code></a> class, which is deprecated in Node.js/io.js v1.0. If you find that you have to use <code>stream.push('')</code>, please consider another approach, because it almost certainly indicates that something is horribly wrong. </p> <h1>StringDecoder<span><a class="mark" href="#all_stringdecoder" id="all_stringdecoder">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</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>const StringDecoder = require('string_decoder').StringDecoder; const decoder = new StringDecoder('utf8'); const cent = new Buffer([0xC2, 0xA2]); console.log(decoder.write(cent)); const 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>decoder.end()<span><a class="mark" href="#all_decoder_end" id="all_decoder_end">#</a></span></h3> <p>Returns any trailing bytes that were left in the buffer. </p> <h3>decoder.write(buffer)<span><a class="mark" href="#all_decoder_write_buffer" id="all_decoder_write_buffer">#</a></span></h3> <p>Returns a decoded string. </p> <h1>Timers<span><a class="mark" href="#all_timers" id="all_timers">#</a></span></h1> <pre class="api_stability_3">Stability: 3 - Locked</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>clearImmediate(immediateObject)<span><a class="mark" href="#all_clearimmediate_immediateobject" id="all_clearimmediate_immediateobject">#</a></span></h2> <p>Stops an immediate from triggering. </p> <h2>clearInterval(intervalObject)<span><a class="mark" href="#all_clearinterval_intervalobject" id="all_clearinterval_intervalobject">#</a></span></h2> <p>Stops an interval from triggering. </p> <h2>clearTimeout(timeoutObject)<span><a class="mark" href="#all_cleartimeout_timeoutobject" id="all_cleartimeout_timeoutobject">#</a></span></h2> <p>Prevents a timeout from triggering. </p> <h2>ref()<span><a class="mark" href="#all_ref" id="all_ref">#</a></span></h2> <p>If you had previously <code>unref()</code>d a timer you can call <code>ref()</code> to explicitly request the timer hold the program open. If the timer is already <code>ref</code>d calling <code>ref</code> again will have no effect. </p> <p>Returns the timer. </p> <h2>setImmediate(callback[, arg][, ...])<span><a class="mark" href="#all_setimmediate_callback_arg" id="all_setimmediate_callback_arg">#</a></span></h2> <p>To schedule the "immediate" execution of <code>callback</code> after I/O events callbacks and before <a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout</code></a> and <a href="timers.html#timers_setinterval_callback_delay_arg"><code>setInterval</code></a>. Returns an <code>immediateObject</code> for possible use with <code>clearImmediate()</code>. Optionally you can also pass arguments to the callback. </p> <p>Callbacks for immediates are queued in the order in which they were created. The entire callback queue is processed every event loop iteration. If you queue an immediate from inside an executing callback, that immediate won't fire until the next event loop iteration. </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>intervalObject</code> for possible use with <code>clearInterval()</code>. Optionally you can also pass arguments to the callback. </p> <p>To follow browser behavior, when using delays larger than 2147483647 milliseconds (approximately 25 days) or less than 1, Node.js will use 1 as the <code>delay</code>. </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>timeoutObject</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> <p>To follow browser behavior, when using delays larger than 2147483647 milliseconds (approximately 25 days) or less than 1, the timeout is executed immediately, as if the <code>delay</code> was set to 1. </p> <h2>unref()<span><a class="mark" href="#all_unref" id="all_unref">#</a></span></h2> <p>The opaque value returned by <a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout</code></a> and <a href="timers.html#timers_setinterval_callback_delay_arg"><code>setInterval</code></a> also has the method <code>timer.unref()</code> which will allow you to create a timer that is active but if it is the only item left in the event loop, it won't keep the program running. If the timer is already <code>unref</code>d calling <code>unref</code> again will have no effect. </p> <p>In the case of <code>setTimeout</code> when you <code>unref</code> you create a separate timer that will wakeup the event loop, creating too many of these may adversely effect event loop performance -- use wisely. </p> <p>Returns the timer. </p> <h1>TLS (SSL)<span><a class="mark" href="#all_tls_ssl" id="all_tls_ssl">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</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 2048</code></pre> <p>All servers 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 -sha256 -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>For Perfect Forward Secrecy, it is required to generate Diffie-Hellman parameters: </p> <pre><code>openssl dhparam -outform PEM -out dhparam.pem 2048</code></pre> <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_tlssocket">tls.TLSSocket</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 10 minutes.</p> </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>Modifying the Default TLS Cipher suite<span><a class="mark" href="#all_modifying_the_default_tls_cipher_suite" id="all_modifying_the_default_tls_cipher_suite">#</a></span></h2> <p>Node.js is built with a default suite of enabled and disabled TLS ciphers. Currently, the default cipher suite is: </p> <pre><code>ECDHE-RSA-AES128-GCM-SHA256: ECDHE-ECDSA-AES128-GCM-SHA256: ECDHE-RSA-AES256-GCM-SHA384: ECDHE-ECDSA-AES256-GCM-SHA384: DHE-RSA-AES128-GCM-SHA256: ECDHE-RSA-AES128-SHA256: DHE-RSA-AES128-SHA256: ECDHE-RSA-AES256-SHA384: DHE-RSA-AES256-SHA384: ECDHE-RSA-AES256-SHA256: DHE-RSA-AES256-SHA256: HIGH: !aNULL: !eNULL: !EXPORT: !DES: !RC4: !MD5: !PSK: !SRP: !CAMELLIA</code></pre> <p>This default can be overriden entirely using the <code>--tls-cipher-list</code> command line switch. For instance, the following makes <code>ECDHE-RSA-AES128-GCM-SHA256:!RC4</code> the default TLS cipher suite: </p> <pre><code>node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"</code></pre> <p>Note that the default cipher suite included within Node.js has been carefully selected to reflect current security best practices and risk mitigation. Changing the default cipher suite can have a significant impact on the security of an application. The <code>--tls-cipher-list</code> switch should by used only if absolutely necessary. </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>Perfect Forward Secrecy<span><a class="mark" href="#all_perfect_forward_secrecy" id="all_perfect_forward_secrecy">#</a></span></h2> <!-- type=misc --> <p>The term "<a href="https://en.wikipedia.org/wiki/Perfect_forward_secrecy">Forward Secrecy</a>" or "Perfect Forward Secrecy" describes a feature of key-agreement (i.e. key-exchange) methods. Practically it means that even if the private key of a (your) server is compromised, communication can only be decrypted by eavesdroppers if they manage to obtain the key-pair specifically generated for each session. </p> <p>This is achieved by randomly generating a key pair for key-agreement on every handshake (in contrary to the same key for all sessions). Methods implementing this technique, thus offering Perfect Forward Secrecy, are called "ephemeral". </p> <p>Currently two methods are commonly used to achieve Perfect Forward Secrecy (note the character "E" appended to the traditional abbreviations): </p> <ul> <li><a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange">DHE</a> - An ephemeral version of the Diffie Hellman key-agreement protocol.</li> <li><a href="https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman">ECDHE</a> - An ephemeral version of the Elliptic Curve Diffie Hellman key-agreement protocol.</li> </ul> <p>Ephemeral methods may have some performance drawbacks, because key generation is expensive. </p> <h2>Class: CryptoStream<span><a class="mark" href="#all_class_cryptostream" id="all_class_cryptostream">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <a href="#tls_class_tls_tlssocket">tls.TLSSocket</a> instead.</pre><p>This is an encrypted stream. </p> <h3>cryptoStream.bytesWritten<span><a class="mark" href="#all_cryptostream_byteswritten" id="all_cryptostream_byteswritten">#</a></span></h3> <p>A proxy to the underlying socket's bytesWritten accessor, this will return the total bytes written to the socket, <em>including the TLS overhead</em>. </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 <code>'secureConnection'</code> 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: 'clientError'<span><a class="mark" href="#all_event_clienterror_1" id="all_event_clienterror_1">#</a></span></h3> <p><code>function (exception, tlsSocket) { }</code> </p> <p>When a client connection emits an <code>'error'</code> event before secure connection is established - it will be forwarded here. </p> <p><code>tlsSocket</code> is the <a href="#tls_class_tls_tlssocket">tls.TLSSocket</a> that the error originated from. </p> <h3>Event: 'newSession'<span><a class="mark" href="#all_event_newsession" id="all_event_newsession">#</a></span></h3> <p><code>function (sessionId, sessionData, callback) { }</code> </p> <p>Emitted on creation of TLS session. May be used to store sessions in external storage. <code>callback</code> must be invoked eventually, otherwise no data will be sent or received from secure connection. </p> <p>NOTE: adding this event listener will have an effect only on connections established after addition of event listener. </p> <h3>Event: 'OCSPRequest'<span><a class="mark" href="#all_event_ocsprequest" id="all_event_ocsprequest">#</a></span></h3> <p><code>function (certificate, issuer, callback) { }</code> </p> <p>Emitted when the client sends a certificate status request. You could parse server's current certificate to obtain OCSP url and certificate id, and after obtaining OCSP response invoke <code>callback(null, resp)</code>, where <code>resp</code> is a <code>Buffer</code> instance. Both <code>certificate</code> and <code>issuer</code> are a <code>Buffer</code> DER-representations of the primary and issuer's certificates. They could be used to obtain OCSP certificate id and OCSP endpoint url. </p> <p>Alternatively, <code>callback(null, null)</code> could be called, meaning that there is no OCSP response. </p> <p>Calling <code>callback(err)</code> will result in a <code>socket.destroy(err)</code> call. </p> <p>Typical flow: </p> <ol> <li>Client connects to server and sends <code>'OCSPRequest'</code> to it (via status info extension in ClientHello.)</li> <li>Server receives request and invokes <code>'OCSPRequest'</code> event listener if present</li> <li>Server grabs OCSP url from either <code>certificate</code> or <code>issuer</code> and performs an <a href="https://en.wikipedia.org/wiki/OCSP_stapling">OCSP request</a> to the CA</li> <li>Server receives <code>OCSPResponse</code> from CA and sends it back to client via <code>callback</code> argument</li> <li>Client validates the response and either destroys socket or performs a handshake.</li> </ol> <p>NOTE: <code>issuer</code> could be null, if the certificate is self-signed or if the issuer is not in the root certificates list. (You could provide an issuer via <code>ca</code> option.) </p> <p>NOTE: adding this event listener will have an effect only on connections established after addition of event listener. </p> <p>NOTE: you may want to use some npm module like <a href="https://npmjs.org/package/asn1.js">asn1.js</a> to parse the certificates. </p> <h3>Event: 'resumeSession'<span><a class="mark" href="#all_event_resumesession" id="all_event_resumesession">#</a></span></h3> <p><code>function (sessionId, callback) { }</code> </p> <p>Emitted when client wants to resume previous TLS session. Event listener may perform lookup in external storage using given <code>sessionId</code>, and invoke <code>callback(null, sessionData)</code> once finished. If session can't be resumed (i.e. doesn't exist in storage) one may call <code>callback(null, null)</code>. Calling <code>callback(err)</code> will terminate incoming connection and destroy socket. </p> <p>NOTE: adding this event listener will have an effect only on connections established after addition of event listener. </p> <p>Here's an example for using TLS session resumption: </p> <pre><code>var tlsSessionStore = {}; server.on('newSession', (id, data, cb) => { tlsSessionStore[id.toString('hex')] = data; cb(); }); server.on('resumeSession', (id, cb) => { cb(null, tlsSessionStore[id.toString('hex')] || null); });</code></pre> <h3>Event: 'secureConnection'<span><a class="mark" href="#all_event_secureconnection" id="all_event_secureconnection">#</a></span></h3> <p><code>function (tlsSocket) {}</code> </p> <p>This event is emitted after a new connection has been successfully handshaked. The argument is an instance of <a href="#tls_class_tls_tlssocket">tls.TLSSocket</a>. It has all the common stream methods and events. </p> <p><code>socket.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>socket.authorized</code> is false, then <code>socket.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>socket.npnProtocol</code> is a string containing selected NPN protocol. <code>socket.servername</code> is a string containing servername requested with SNI. </p> <h3>server.addContext(hostname, context)<span><a class="mark" href="#all_server_addcontext_hostname_context" id="all_server_addcontext_hostname_context">#</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>context</code> can contain <code>key</code>, <code>cert</code>, <code>ca</code> and/or any other properties from <code>tls.createSecureContext</code> <code>options</code> argument. </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. See <a href="net.html#net_server_address">net.Server.address()</a> for more information. </p> <h3>server.close([callback])<span><a class="mark" href="#all_server_close_callback_3" id="all_server_close_callback_3">#</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. Optionally, you can pass a callback to listen for the <code>'close'</code> event. </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> <h3>server.getTicketKeys()<span><a class="mark" href="#all_server_getticketkeys" id="all_server_getticketkeys">#</a></span></h3> <p>Returns <code>Buffer</code> instance holding the keys currently used for encryption/decryption of the <a href="https://www.ietf.org/rfc/rfc5077.txt">TLS Session Tickets</a> </p> <h3>server.listen(port[, hostname][, callback])<span><a class="mark" href="#all_server_listen_port_hostname_callback" id="all_server_listen_port_hostname_callback">#</a></span></h3> <p>Begin accepting connections on the specified <code>port</code> and <code>hostname</code>. If the <code>hostname</code> is omitted, the server will accept connections on any IPv6 address (<code>::</code>) when IPv6 is available, or any IPv4 address (<code>0.0.0.0</code>) otherwise. A port value of zero will assign a random port. </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.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> <h3>server.setTicketKeys(keys)<span><a class="mark" href="#all_server_setticketkeys_keys" id="all_server_setticketkeys_keys">#</a></span></h3> <p>Updates the keys for encryption/decryption of the <a href="https://www.ietf.org/rfc/rfc5077.txt">TLS Session Tickets</a>. </p> <p>NOTE: the buffer should be 48 bytes long. See server <code>ticketKeys</code> option for more information oh how it is going to be used. </p> <p>NOTE: the change is effective only for the future server connections. Existing or currently pending server connections will use previous keys. </p> <h2>Class: tls.TLSSocket<span><a class="mark" href="#all_class_tls_tlssocket" id="all_class_tls_tlssocket">#</a></span></h2> <p>This is a wrapped version of <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> that does transparent encryption of written data and all required TLS negotiation. </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>Methods that return TLS connection meta data (e.g. <a href="#tls_tlssocket_getpeercertificate_detailed">getPeerCertificate</a> will only return data while the connection is open. </p> <h2>new tls.TLSSocket(socket[, options])<span><a class="mark" href="#all_new_tls_tlssocket_socket_options" id="all_new_tls_tlssocket_socket_options">#</a></span></h2> <p>Construct a new TLSSocket object from existing TCP socket. </p> <p><code>socket</code> is an instance of <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> </p> <p><code>options</code> is an optional object that might contain following properties: </p> <ul> <li><p><code>secureContext</code>: An optional TLS context object from <code>tls.createSecureContext( ... )</code></p> </li> <li><p><code>isServer</code>: If <code>true</code> - TLS socket will be instantiated in server-mode. Default: <code>false</code></p> </li> <li><p><code>server</code>: An optional <a href="net.html#net_class_net_server"><code>net.Server</code></a> instance</p> </li> <li><p><code>requestCert</code>: Optional, see <a href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options">tls.createSecurePair</a></p> </li> <li><p><code>rejectUnauthorized</code>: Optional, see <a href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options">tls.createSecurePair</a></p> </li> <li><p><code>NPNProtocols</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener">tls.createServer</a></p> </li> <li><p><code>SNICallback</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener">tls.createServer</a></p> </li> <li><p><code>session</code>: Optional, a <code>Buffer</code> instance, containing TLS session</p> </li> <li><p><code>requestOCSP</code>: Optional, if <code>true</code> - OCSP status request extension would be added to client hello, and <code>'OCSPResponse'</code> event will be emitted on socket before establishing secure communication</p> </li> </ul> <h3>Event: 'OCSPResponse'<span><a class="mark" href="#all_event_ocspresponse" id="all_event_ocspresponse">#</a></span></h3> <p><code>function (response) { }</code> </p> <p>This event will be emitted if <code>requestOCSP</code> option was set. <code>response</code> is a buffer object, containing server's OCSP response. </p> <p>Traditionally, the <code>response</code> is a signed object from the server's CA that contains information about server's certificate revocation status. </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>tlsSocket.authorized</code> to see if the server certificate was signed by one of the specified CAs. If <code>tlsSocket.authorized === false</code> then the error can be found in <code>tlsSocket.authorizationError</code>. Also if NPN was used - you can check <code>tlsSocket.npnProtocol</code> for negotiated protocol. </p> <h3>tlsSocket.address()<span><a class="mark" href="#all_tlssocket_address" id="all_tlssocket_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>tlsSocket.authorized<span><a class="mark" href="#all_tlssocket_authorized" id="all_tlssocket_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>tlsSocket.authorizationError<span><a class="mark" href="#all_tlssocket_authorizationerror" id="all_tlssocket_authorizationerror">#</a></span></h3> <p>The reason why the peer's certificate has not been verified. This property becomes available only when <code>tlsSocket.authorized === false</code>. </p> <h3>tlsSocket.encrypted<span><a class="mark" href="#all_tlssocket_encrypted" id="all_tlssocket_encrypted">#</a></span></h3> <p>Static boolean value, always <code>true</code>. May be used to distinguish TLS sockets from regular ones. </p> <h3>tlsSocket.getCipher()<span><a class="mark" href="#all_tlssocket_getcipher" id="all_tlssocket_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="https://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS">https://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS</a> for more information. </p> <h3>tlsSocket.getPeerCertificate([ detailed ])<span><a class="mark" href="#all_tlssocket_getpeercertificate_detailed" id="all_tlssocket_getpeercertificate_detailed">#</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. If <code>detailed</code> argument is <code>true</code> - the full chain with <code>issuer</code> property will be returned, if <code>false</code> - only the top certificate without <code>issuer</code> property. </p> <p>Example: </p> <pre><code>{ subject: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, issuerInfo: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, issuer: { ... another certificate ... }, raw: < RAW DER buffer >, 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', serialNumber: 'B9B0D332A1AA5635' }</code></pre> <p>If the peer does not provide a certificate, it returns <code>null</code> or an empty object. </p> <h3>tlsSocket.getSession()<span><a class="mark" href="#all_tlssocket_getsession" id="all_tlssocket_getsession">#</a></span></h3> <p>Return ASN.1 encoded TLS session or <code>undefined</code> if none was negotiated. Could be used to speed up handshake establishment when reconnecting to the server. </p> <h3>tlsSocket.getTLSTicket()<span><a class="mark" href="#all_tlssocket_gettlsticket" id="all_tlssocket_gettlsticket">#</a></span></h3> <p>NOTE: Works only with client TLS sockets. Useful only for debugging, for session reuse provide <code>session</code> option to <code>tls.connect</code>. </p> <p>Return TLS session ticket or <code>undefined</code> if none was negotiated. </p> <h3>tlsSocket.localPort<span><a class="mark" href="#all_tlssocket_localport" id="all_tlssocket_localport">#</a></span></h3> <p>The numeric representation of the local port. </p> <h3>tlsSocket.localAddress<span><a class="mark" href="#all_tlssocket_localaddress" id="all_tlssocket_localaddress">#</a></span></h3> <p>The string representation of the local IP address. </p> <h3>tlsSocket.remoteAddress<span><a class="mark" href="#all_tlssocket_remoteaddress" id="all_tlssocket_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>tlsSocket.remoteFamily<span><a class="mark" href="#all_tlssocket_remotefamily" id="all_tlssocket_remotefamily">#</a></span></h3> <p>The string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>. </p> <h3>tlsSocket.remotePort<span><a class="mark" href="#all_tlssocket_remoteport" id="all_tlssocket_remoteport">#</a></span></h3> <p>The numeric representation of the remote port. For example, <code>443</code>. </p> <h3>tlsSocket.renegotiate(options, callback)<span><a class="mark" href="#all_tlssocket_renegotiate_options_callback" id="all_tlssocket_renegotiate_options_callback">#</a></span></h3> <p>Initiate TLS renegotiation process. The <code>options</code> may contain the following fields: <code>rejectUnauthorized</code>, <code>requestCert</code> (See <a href="#tls_tls_createserver_options_secureconnectionlistener">tls.createServer</a> for details). <code>callback(err)</code> will be executed with <code>null</code> as <code>err</code>, once the renegotiation is successfully completed. </p> <p>NOTE: Can be used to request peer's certificate after the secure connection has been established. </p> <p>ANOTHER NOTE: When running as the server, socket will be destroyed with an error after <code>handshakeTimeout</code> timeout. </p> <h3>tlsSocket.setMaxSendFragment(size)<span><a class="mark" href="#all_tlssocket_setmaxsendfragment_size" id="all_tlssocket_setmaxsendfragment_size">#</a></span></h3> <p>Set maximum TLS fragment size (default and maximum value is: <code>16384</code>, minimum is: <code>512</code>). Returns <code>true</code> on success, <code>false</code> otherwise. </p> <p>Smaller fragment size decreases buffering latency on the client: large fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips, and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput. </p> <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>path</code>: Creates unix socket connection to path. 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 client 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. (Could be an array of keys).</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. (Could be an array of certs).</p> </li> <li><p><code>ca</code>: A string, <code>Buffer</code> or array of strings or <code>Buffer</code>s of trusted certificates in PEM format. 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>ciphers</code>: A string describing the ciphers to use or exclude, separated by <code>:</code>. Uses the same default cipher suite as <code>tls.createServer</code>.</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; <code>err.code</code> contains the OpenSSL error code. Default: <code>true</code>.</p> </li> <li><p><code>NPNProtocols</code>: An array of strings or <code>Buffer</code>s containing supported NPN protocols. <code>Buffer</code>s 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> <li><p><code>checkServerIdentity(servername, cert)</code>: Provide an override for checking server's hostname against the certificate. Should return an error if verification fails. Return <code>undefined</code> if passing.</p> </li> <li><p><code>secureProtocol</code>: The SSL method to use, e.g. <code>SSLv3_method</code> to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant <a href="https://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS">SSL_METHODS</a>.</p> </li> <li><p><code>session</code>: A <code>Buffer</code> instance, containing TLS session.</p> </li> </ul> <p>The <code>callback</code> parameter will be added as a listener for the <a href="#tls_event_secureconnect"><code>'secureConnect'</code></a> event. </p> <p><code>tls.connect()</code> returns a <a href="#tls_class_tls_tlssocket">tls.TLSSocket</a> object. </p> <p>Here is an example of a client of echo server as described previously: </p> <pre><code>const tls = require('tls'); const fs = require('fs'); const 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 socket = tls.connect(8000, options, () => { console.log('client connected', socket.authorized ? 'authorized' : 'unauthorized'); process.stdin.pipe(socket); process.stdin.resume(); }); socket.setEncoding('utf8'); socket.on('data', (data) => { console.log(data); }); socket.on('end', () => { server.close(); });</code></pre> <p>Or </p> <pre><code>const tls = require('tls'); const fs = require('fs'); const options = { pfx: fs.readFileSync('client.pfx') }; var socket = tls.connect(8000, options, () => { console.log('client connected', socket.authorized ? 'authorized' : 'unauthorized'); process.stdin.pipe(socket); process.stdin.resume(); }); socket.setEncoding('utf8'); socket.on('data', (data) => { console.log(data); }); socket.on('end', () => { server.close(); });</code></pre> <h2>tls.createSecureContext(details)<span><a class="mark" href="#all_tls_createsecurecontext_details" id="all_tls_createsecurecontext_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 or <code>Buffer</code> containing the private key of the server in PEM format. To support multiple keys using different algorithms, an array can be provided. It can either be a plain array of keys, or an array of objects in the format <code>{pem: key, passphrase: passphrase}</code>. (Required)</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>: A string, <code>Buffer</code> or array of strings or <code>Buffer</code>s of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.</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="https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT</a> for details on the format.</li> <li><code>honorCipherOrder</code> : When choosing a cipher, use the server's preferences instead of the client preferences. For further details see <code>tls</code> module documentation.</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>tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized])<span><a class="mark" href="#all_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized" id="all_tls_createsecurepair_context_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 secure context object from tls.createSecureContext( ... )</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 <code>cleartext</code> and <code>encrypted</code> stream properties. </p> <p>NOTE: <code>cleartext</code> has the same APIs as <a href="#tls_class_tls_tlssocket">tls.TLSSocket</a> </p> <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"><code>'secureConnection'</code></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. To support multiple keys using different algorithms, an array can be provided. It can either be a plain array of keys, or an array of objects in the format <code>{pem: key, passphrase: passphrase}</code>. (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. (Could be an array of certs). (Required)</p> </li> <li><p><code>ca</code>: A string, <code>Buffer</code> or array of strings or <code>Buffer</code>s of trusted certificates in PEM format. 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, separated by <code>:</code>. The default cipher suite is:</p> <pre><code>ECDHE-RSA-AES128-GCM-SHA256: ECDHE-ECDSA-AES128-GCM-SHA256: ECDHE-RSA-AES256-GCM-SHA384: ECDHE-ECDSA-AES256-GCM-SHA384: DHE-RSA-AES128-GCM-SHA256: ECDHE-RSA-AES128-SHA256: DHE-RSA-AES128-SHA256: ECDHE-RSA-AES256-SHA384: DHE-RSA-AES256-SHA384: ECDHE-RSA-AES256-SHA256: DHE-RSA-AES256-SHA256: HIGH: !aNULL: !eNULL: !EXPORT: !DES: !RC4: !MD5: !PSK: !SRP: !CAMELLIA</code></pre> <p>The default cipher suite prefers GCM ciphers for <a href="https://www.chromium.org/Home/chromium-security/education/tls#TOC-Deprecation-of-TLS-Features-Algorithms-in-Chrome">Chrome's 'modern cryptography' setting</a> and also prefers ECDHE and DHE ciphers for Perfect Forward secrecy, while offering <em>some</em> backward compatibiltity.</p> <p>128 bit AES is preferred over 192 and 256 bit AES in light of <a href="https://www.schneier.com/blog/archives/2009/07/another_new_aes.html">specific attacks affecting larger AES key sizes</a>.</p> <p>Old clients that rely on insecure and deprecated RC4 or DES-based ciphers (like Internet Explorer 6) aren't able to complete the handshake with the default configuration. If you absolutely must support these clients, the <a href="https://wiki.mozilla.org/Security/Server_Side_TLS">TLS recommendations</a> may offer a compatible cipher suite. For more details on the format, see the <a href="https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">OpenSSL cipher list format documentation</a>.</p> </li> <li><p><code>ecdhCurve</code>: A string describing a named curve to use for ECDH key agreement or false to disable ECDH.</p> <p>Defaults to <code>prime256v1</code> (NIST P-256). Use <a href="crypto.html#crypto_crypto_getcurves">crypto.getCurves()</a> to obtain a list of available curve names. On recent releases, <code>openssl ecparam -list_curves</code> will also display the name and description of each available elliptic curve.</p> </li> <li><p><code>dhparam</code>: A string or <code>Buffer</code> containing Diffie Hellman parameters, required for Perfect Forward Secrecy. Use <code>openssl dhparam</code> to create it. Its key length should be greater than or equal to 1024 bits, otherwise it throws an error. It is strongly recommended to use 2048 bits or more for stronger security. If omitted or invalid, it is silently discarded and DHE ciphers won't be available.</p> </li> <li><p><code>handshakeTimeout</code>: Abort the connection if the SSL/TLS handshake does not finish in this many milliseconds. The default is 120 seconds.</p> <p>A <code>'clientError'</code> is emitted on the <code>tls.Server</code> object whenever a handshake times out.</p> </li> <li><p><code>honorCipherOrder</code> : When choosing a cipher, use the server's preferences instead of the client preferences. Default: <code>true</code>.</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(servername, cb)</code>: A function that will be called if client supports SNI TLS extension. Two argument will be passed to it: <code>servername</code>, and <code>cb</code>. <code>SNICallback</code> should invoke <code>cb(null, ctx)</code>, where <code>ctx</code> is a SecureContext instance. (You can use <code>tls.createSecureContext(...)</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>sessionTimeout</code>: An integer specifying the seconds after which TLS session identifiers and TLS session tickets created by the server are timed out. See <a href="https://www.openssl.org/docs/ssl/SSL_CTX_set_timeout.html">SSL_CTX_set_timeout</a> for more details.</p> </li> <li><p><code>ticketKeys</code>: A 48-byte <code>Buffer</code> instance consisting of 16-byte prefix, 16-byte hmac key, 16-byte AES key. You could use it to accept tls session tickets on multiple instances of tls server.</p> <p>NOTE: Automatically shared between <code>cluster</code> module workers.</p> </li> <li><p><code>sessionIdContext</code>: A string containing an opaque identifier for session resumption. If <code>requestCert</code> is <code>true</code>, the default is MD5 hash value generated from command-line. (In FIPS mode a truncated SHA1 hash is used instead.) Otherwise, the default is not provided.</p> </li> <li><p><code>secureProtocol</code>: The SSL method to use, e.g. <code>SSLv3_method</code> to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant <a href="https://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS">SSL_METHODS</a>.</p> </li> </ul> <p>Here is a simple example echo server: </p> <pre><code>const tls = require('tls'); const fs = require('fs'); const 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, (socket) => { console.log('server connected', socket.authorized ? 'authorized' : 'unauthorized'); socket.write('welcome!\n'); socket.setEncoding('utf8'); socket.pipe(socket); }); server.listen(8000, () => { console.log('server bound'); });</code></pre> <p>Or </p> <pre><code>const tls = require('tls'); const fs = require('fs'); const options = { pfx: fs.readFileSync('server.pfx'), // This is necessary only if using the client certificate authentication. requestCert: true, }; var server = tls.createServer(options, (socket) => { console.log('server connected', socket.authorized ? 'authorized' : 'unauthorized'); socket.write('welcome!\n'); socket.setEncoding('utf8'); socket.pipe(socket); }); server.listen(8000, () => { 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.getCiphers()<span><a class="mark" href="#all_tls_getciphers" id="all_tls_getciphers">#</a></span></h2> <p>Returns an array with the names of the supported SSL ciphers. </p> <p>Example: </p> <pre><code>var ciphers = tls.getCiphers(); console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]</code></pre> <h1>TTY<span><a class="mark" href="#all_tty" id="all_tty">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</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.js 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.js 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>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.js 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>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', () => { console.log('screen size has changed!'); console.log(`${process.stdout.columns}x${process.stdout.rows}`); });</code></pre> <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 <code>'resize'</code> 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 <code>'resize'</code> events. </p> <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> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <a href="#tty_rs_setrawmode_mode">tty.ReadStream#setRawMode</a> (i.e. process.stdin.setRawMode) instead.</pre><h1>URL<span><a class="mark" href="#all_url" id="all_url">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>This module has utilities for URL resolution and parsing. Call <code>require('url')</code> to use it. </p> <h2>URL Parsing<span><a class="mark" href="#all_url_parsing" id="all_url_parsing">#</a></span></h2> <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>slashes</code>: The protocol requires slashes after the colon.</p> <p> Example: true or false</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. No decoding is performed.</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>. No decoding is performed.</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> <h3>Escaped Characters<span><a class="mark" href="#all_escaped_characters" id="all_escaped_characters">#</a></span></h3> <p>Spaces (<code>' '</code>) and the following characters will be automatically escaped in the properties of URL objects: </p> <pre><code>< > " ` \r \n \t { } | \ ^ '</code></pre> <hr> <p>The following methods are provided by the URL module: </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> <p>Here's how the formatting process works: </p> <ul> <li><code>href</code> will be ignored.</li> <li><code>path</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) as long as <code>host</code>/<code>hostname</code> are present.</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>slashes</code> set to <code>true</code> if the protocol requires <code>://</code> (colon-slash-slash)<ul> <li>Only needs to be set for protocols not previously listed as requiring slashes, such as <code>mongodb://localhost:8000/</code>, or if <code>host</code>/<code>hostname</code> are absent.</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>query</code> (object; see <code>querystring</code>) will only be used if <code>search</code> is absent.</li> <li><code>search</code> will be used in place of <code>query</code>.<ul> <li>It is treated the same with or without the leading <code>?</code> (question mark).</li> </ul> </li> <li><code>hash</code> is treated the same with or without the leading <code>#</code> (pound sign, anchor).</li> </ul> <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. If <code>true</code> then the <code>query</code> property will always be assigned an object, and the <code>search</code> property will always be a (possibly empty) string. If <code>false</code> then the <code>query</code> property will not be parsed or decoded. 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.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. Examples: </p> <pre><code>url.resolve('/one/two/three', 'four') // '/one/two/four' url.resolve('http://example.com/', '/one') // 'http://example.com/one' url.resolve('http://example.com/one', '/two') // 'http://example.com/two'</code></pre> <h1>util<span><a class="mark" href="#all_util" id="all_util">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>These functions are in the module <code>'util'</code>. Use <code>require('util')</code> to access them. </p> <p>The <code>util</code> module is primarily designed to support the needs of Node.js's internal APIs. Many of these utilities are useful for your own programs. If you find that these functions are lacking for your purposes, however, you are encouraged to write your own utilities. We are not interested in any future additions to the <code>util</code> module that are unnecessary for Node.js's internal functionality. </p> <h2>util.debug(string)<span><a class="mark" href="#all_util_debug_string" id="all_util_debug_string">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated: use console.error() instead.</pre><p>Deprecated predecessor of <code>console.error</code>. </p> <h2>util.debuglog(section)<span><a class="mark" href="#all_util_debuglog_section" id="all_util_debuglog_section">#</a></span></h2> <div class="signature"><ul> <li><code>section</code> <span class="type">String</span> The section of the program to be debugged</li> <li>Returns: <span class="type">Function</span> The logging function</li> </div></ul> <p>This is used to create a function which conditionally writes to stderr based on the existence of a <code>NODE_DEBUG</code> environment variable. If the <code>section</code> name appears in that environment variable, then the returned function will be similar to <code>console.error()</code>. If not, then the returned function is a no-op. </p> <p>For example: </p> <pre><code class="javascript">var debuglog = util.debuglog('foo'); var bar = 123; debuglog('hello from foo [%d]', bar);</code></pre> <p>If this program is run with <code>NODE_DEBUG=foo</code> in the environment, then it will output something like: </p> <pre><code>FOO 3245: hello from foo [123]</code></pre> <p>where <code>3245</code> is the process id. If it is not run with that environment variable set, then it will not print anything. </p> <p>You may separate multiple <code>NODE_DEBUG</code> environment variables with a comma. For example, <code>NODE_DEBUG=fs,net,tls</code>. </p> <h2>util.deprecate(function, string)<span><a class="mark" href="#all_util_deprecate_function_string" id="all_util_deprecate_function_string">#</a></span></h2> <p>Marks that a method should not be used any more. </p> <pre><code>const util = require('util'); exports.puts = util.deprecate(function() { for (var i = 0, len = arguments.length; i < len; ++i) { process.stdout.write(arguments[i] + '\n'); } }, 'util.puts: Use console.log instead');</code></pre> <p>It returns a modified function which warns once by default. </p> <p>If <code>--no-deprecation</code> is set then this function is a NO-OP. Configurable at run-time through the <code>process.noDeprecation</code> boolean (only effective when set before a module is loaded.) </p> <p>If <code>--trace-deprecation</code> is set, a warning and a stack trace are logged to the console the first time the deprecated API is used. Configurable at run-time through the <code>process.traceDeprecation</code> boolean. </p> <p>If <code>--throw-deprecation</code> is set then the application throws an exception when the deprecated API is used. Configurable at run-time through the <code>process.throwDeprecation</code> boolean. </p> <p><code>process.throwDeprecation</code> takes precedence over <code>process.traceDeprecation</code>. </p> <h2>util.error([...])<span><a class="mark" href="#all_util_error" id="all_util_error">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated: Use console.error() instead.</pre><p>Deprecated predecessor of <code>console.error</code>. </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. Replaced with the string <code>'[Circular]'</code> if the argument contains circular references.</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 coerced to strings (for objects and symbols, <code>util.inspect()</code> is used) and then 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.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>const util = require('util'); const EventEmitter = require('events'); function MyStream() { EventEmitter.call(this); } util.inherits(MyStream, EventEmitter); MyStream.prototype.write = function(data) { this.emit('data', data); } var stream = new MyStream(); console.log(stream instanceof EventEmitter); // true console.log(MyStream.super_ === EventEmitter); // true stream.on('data', (data) => { console.log(`Received data: "${data}"`); }) stream.write('It works!'); // Received data: "It works!"</code></pre> <h2>util.inspect(object[, options])<span><a class="mark" href="#all_util_inspect_object_options" id="all_util_inspect_object_options">#</a></span></h2> <p>Return a string representation of <code>object</code>, which is useful for debugging. </p> <p>An optional <em>options</em> object may be passed that alters certain aspects of the formatted string: </p> <ul> <li><p><code>showHidden</code> - if <code>true</code> then the object's non-enumerable and symbol properties will be shown too. Defaults to <code>false</code>.</p> </li> <li><p><code>depth</code> - tells <code>inspect</code> how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to <code>2</code>. To make it recurse indefinitely pass <code>null</code>.</p> </li> <li><p><code>colors</code> - if <code>true</code>, then the output will be styled with ANSI color codes. Defaults to <code>false</code>. Colors are customizable, see below.</p> </li> <li><p><code>customInspect</code> - if <code>false</code>, then custom <code>inspect(depth, opts)</code> functions defined on the objects being inspected won't be called. Defaults to <code>true</code>.</p> </li> </ul> <p>Example of inspecting all properties of the <code>util</code> object: </p> <pre><code>const util = require('util'); console.log(util.inspect(util, { showHidden: true, depth: null }));</code></pre> <p>Values may supply their own custom <code>inspect(depth, opts)</code> functions, when called they receive the current depth in the recursive inspection, as well as the options object passed to <code>util.inspect()</code>. </p> <h3>Customizing <code>util.inspect</code> colors<span><a class="mark" href="#all_customizing_util_inspect_colors" id="all_customizing_util_inspect_colors">#</a></span></h3> <!-- type=misc --> <p>Color output (if enabled) of <code>util.inspect</code> is customizable globally via <code>util.inspect.styles</code> and <code>util.inspect.colors</code> objects. </p> <p><code>util.inspect.styles</code> is a map assigning each style a color from <code>util.inspect.colors</code>. Highlighted styles and their default values are: <em> <code>number</code> (yellow) </em> <code>boolean</code> (yellow) <em> <code>string</code> (green) </em> <code>date</code> (magenta) <em> <code>regexp</code> (red) </em> <code>null</code> (bold) <em> <code>undefined</code> (grey) </em> <code>special</code> - only function at this time (cyan) * <code>name</code> (intentionally no styling) </p> <p>Predefined color codes are: <code>white</code>, <code>grey</code>, <code>black</code>, <code>blue</code>, <code>cyan</code>, <code>green</code>, <code>magenta</code>, <code>red</code> and <code>yellow</code>. There are also <code>bold</code>, <code>italic</code>, <code>underline</code> and <code>inverse</code> codes. </p> <h3>Custom <code>inspect()</code> function on Objects<span><a class="mark" href="#all_custom_inspect_function_on_objects" id="all_custom_inspect_function_on_objects">#</a></span></h3> <!-- type=misc --> <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>const util = require('util'); var obj = { name: 'nate' }; obj.inspect = function(depth) { return `{${this.name}}`; }; util.inspect(obj); // "{nate}"</code></pre> <p>You may also return another Object entirely, and the returned String will be formatted according to the returned Object. This is similar to how <code>JSON.stringify()</code> works: </p> <pre><code>var obj = { foo: 'this will not show up in the inspect() output' }; obj.inspect = function(depth) { return { bar: 'baz' }; }; util.inspect(obj); // "{ bar: 'baz' }"</code></pre> <h2>util.isArray(object)<span><a class="mark" href="#all_util_isarray_object" id="all_util_isarray_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Internal alias for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray"><code>Array.isArray</code></a>. </p> <p>Returns <code>true</code> if the given "object" is an <code>Array</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isArray([]) // true util.isArray(new Array) // true util.isArray({}) // false</code></pre> <h2>util.isBoolean(object)<span><a class="mark" href="#all_util_isboolean_object" id="all_util_isboolean_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Boolean</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isBoolean(1) // false util.isBoolean(0) // false util.isBoolean(false) // true</code></pre> <h2>util.isBuffer(object)<span><a class="mark" href="#all_util_isbuffer_object" id="all_util_isbuffer_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Use <code>Buffer.isBuffer()</code> instead. </p> <p>Returns <code>true</code> if the given "object" is a <code>Buffer</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isBuffer({ length: 0 }) // false util.isBuffer([]) // false util.isBuffer(new Buffer('hello world')) // true</code></pre> <h2>util.isDate(object)<span><a class="mark" href="#all_util_isdate_object" id="all_util_isdate_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Date</code>. <code>false</code> otherwise. </p> <pre><code>const 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> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is an <a href="errors.html#errors_class_error"><code>Error</code></a>. <code>false</code> otherwise. </p> <pre><code>const 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.isFunction(object)<span><a class="mark" href="#all_util_isfunction_object" id="all_util_isfunction_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Function</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); function Foo() {} var Bar = function() {}; util.isFunction({}) // false util.isFunction(Foo) // true util.isFunction(Bar) // true</code></pre> <h2>util.isNull(object)<span><a class="mark" href="#all_util_isnull_object" id="all_util_isnull_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is strictly <code>null</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isNull(0) // false util.isNull(undefined) // false util.isNull(null) // true</code></pre> <h2>util.isNullOrUndefined(object)<span><a class="mark" href="#all_util_isnullorundefined_object" id="all_util_isnullorundefined_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is <code>null</code> or <code>undefined</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isNullOrUndefined(0) // false util.isNullOrUndefined(undefined) // true util.isNullOrUndefined(null) // true</code></pre> <h2>util.isNumber(object)<span><a class="mark" href="#all_util_isnumber_object" id="all_util_isnumber_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Number</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isNumber(false) // false util.isNumber(Infinity) // true util.isNumber(0) // true util.isNumber(NaN) // true</code></pre> <h2>util.isObject(object)<span><a class="mark" href="#all_util_isobject_object" id="all_util_isobject_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is strictly an <code>Object</code> <strong>and</strong> not a <code>Function</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isObject(5) // false util.isObject(null) // false util.isObject({}) // true util.isObject(function(){}) // false</code></pre> <h2>util.isPrimitive(object)<span><a class="mark" href="#all_util_isprimitive_object" id="all_util_isprimitive_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a primitive type. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isPrimitive(5) // true util.isPrimitive('foo') // true util.isPrimitive(false) // true util.isPrimitive(null) // true util.isPrimitive(undefined) // true util.isPrimitive({}) // false util.isPrimitive(function() {}) // false util.isPrimitive(/^$/) // false util.isPrimitive(new Date()) // false</code></pre> <h2>util.isRegExp(object)<span><a class="mark" href="#all_util_isregexp_object" id="all_util_isregexp_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>RegExp</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isRegExp(/some regexp/) // true util.isRegExp(new RegExp('another regexp')) // true util.isRegExp({}) // false</code></pre> <h2>util.isString(object)<span><a class="mark" href="#all_util_isstring_object" id="all_util_isstring_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>String</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isString('') // true util.isString('foo') // true util.isString(String('foo')) // true util.isString(5) // false</code></pre> <h2>util.isSymbol(object)<span><a class="mark" href="#all_util_issymbol_object" id="all_util_issymbol_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Symbol</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); util.isSymbol(5) // false util.isSymbol('foo') // false util.isSymbol(Symbol('foo')) // true</code></pre> <h2>util.isUndefined(object)<span><a class="mark" href="#all_util_isundefined_object" id="all_util_isundefined_object">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is <code>undefined</code>. <code>false</code> otherwise. </p> <pre><code>const util = require('util'); var foo; util.isUndefined(5) // false util.isUndefined(foo) // true util.isUndefined(null) // false</code></pre> <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.print([...])<span><a class="mark" href="#all_util_print" id="all_util_print">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated: Use <code>console.log</code> instead.</pre><p>Deprecated predecessor of <code>console.log</code>. </p> <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 class="api_stability_0">Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)</pre><p>Deprecated predecessor of <code>stream.pipe()</code>. </p> <h2>util.puts([...])<span><a class="mark" href="#all_util_puts" id="all_util_puts">#</a></span></h2> <pre class="api_stability_0">Stability: 0 - Deprecated: Use console.log() instead.</pre><p>Deprecated predecessor of <code>console.log</code>. </p> <h1>V8<span><a class="mark" href="#all_v8" id="all_v8">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>This module exposes events and interfaces specific to the version of <a href="https://code.google.com/p/v8/">V8</a> built with Node.js. These interfaces are subject to change by upstream and are therefore not covered under the stability index. </p> <h2>getHeapStatistics()<span><a class="mark" href="#all_getheapstatistics" id="all_getheapstatistics">#</a></span></h2> <p>Returns an object with the following properties </p> <pre><code>{ total_heap_size: 7326976, total_heap_size_executable: 4194304, total_physical_size: 7326976, total_available_size: 1152656, used_heap_size: 3476208, heap_size_limit: 1535115264 }</code></pre> <h2>setFlagsFromString(string)<span><a class="mark" href="#all_setflagsfromstring_string" id="all_setflagsfromstring_string">#</a></span></h2> <p>Set additional V8 command line flags. Use with care; changing settings after the VM has started may result in unpredictable behavior, including crashes and data loss. Or it may simply do nothing. </p> <p>The V8 options available for a version of Node.js may be determined by running <code>node --v8-options</code>. An unofficial, community-maintained list of options and their effects is available <a href="https://github.com/thlorenz/v8-flags/blob/master/flags-0.11.md">here</a>. </p> <p>Usage: </p> <pre><code>// Print GC events to stdout for one minute. const v8 = require('v8'); v8.setFlagsFromString('--trace_gc'); setTimeout(function() { v8.setFlagsFromString('--notrace_gc'); }, 60e3);</code></pre> <h1>Executing JavaScript<span><a class="mark" href="#all_executing_javascript" id="all_executing_javascript">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><!--name=vm--> <p>You can access this module with: </p> <pre><code>const vm = require('vm');</code></pre> <p>JavaScript code can be compiled and run immediately or compiled, saved, and run later. </p> <h2>Class: Script<span><a class="mark" href="#all_class_script" id="all_class_script">#</a></span></h2> <p>A class for holding precompiled scripts, and running them in specific sandboxes. </p> <h3>new vm.Script(code, options)<span><a class="mark" href="#all_new_vm_script_code_options" id="all_new_vm_script_code_options">#</a></span></h3> <p>Creating a new <code>Script</code> compiles <code>code</code> but does not run it. Instead, the created <code>vm.Script</code> object represents 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. </p> <p>The options when creating a script are: </p> <ul> <li><code>filename</code>: allows you to control the filename that shows up in any stack traces produced from this script.</li> <li><code>lineOffset</code>: allows you to add an offset to the line number that is displayed in stack traces</li> <li><code>columnOffset</code>: allows you to add an offset to the column number that is displayed in stack traces</li> <li><code>displayErrors</code>: whether or not to print any errors to stderr, with the line of code that caused them highlighted, before throwing an exception. Applies only to syntax errors compiling the code; errors while running the code are controlled by the options to the script's methods.</li> <li><code>timeout</code>: a number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> <h3>script.runInContext(contextifiedSandbox[, options])<span><a class="mark" href="#all_script_runincontext_contextifiedsandbox_options" id="all_script_runincontext_contextifiedsandbox_options">#</a></span></h3> <p>Similar to <code>vm.runInContext</code> but a method of a precompiled <code>Script</code> object. <code>script.runInContext</code> runs <code>script</code>'s compiled code in <code>contextifiedSandbox</code> and returns the result. Running code does not have access to local scope. </p> <p><code>script.runInContext</code> takes the same options as <code>script.runInThisContext</code>. </p> <p>Example: compile code that increments a global variable and sets one, then execute the code multiple times. These globals are contained in the sandbox. </p> <pre><code>const util = require('util'); const vm = require('vm'); var sandbox = { animal: 'cat', count: 2 }; var context = new vm.createContext(sandbox); var script = new vm.Script('count += 1; name = "kitty"'); for (var i = 0; i < 10; ++i) { script.runInContext(context); } 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. <code>script.runInContext</code> is quite useful, but safely running untrusted code requires a separate process. </p> <h3>script.runInNewContext([sandbox][, options])<span><a class="mark" href="#all_script_runinnewcontext_sandbox_options" id="all_script_runinnewcontext_sandbox_options">#</a></span></h3> <p>Similar to <code>vm.runInNewContext</code> but a method of a precompiled <code>Script</code> object. <code>script.runInNewContext</code> contextifies <code>sandbox</code> if passed or creates a new contextified sandbox if it's omitted, and then runs <code>script</code>'s compiled code with the sandbox as the global object and returns the result. Running code does not have access to local scope. </p> <p><code>script.runInNewContext</code> takes the same options as <code>script.runInThisContext</code>. </p> <p>Example: compile code that sets a global variable, then execute the code multiple times in different contexts. These globals are set on and contained in the sandboxes. </p> <pre><code>const util = require('util'); const vm = require('vm'); const sandboxes = [{}, {}, {}]; const script = new vm.Script('globalVar = "set"'); sandboxes.forEach((sandbox) => { script.runInNewContext(sandbox); }); console.log(util.inspect(sandboxes)); // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]</code></pre> <p>Note that running untrusted code is a tricky business requiring great care. <code>script.runInNewContext</code> is quite useful, but safely running untrusted code requires a separate process. </p> <h3>script.runInThisContext(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#all_script_runinthiscontext_options" id="all_script_runinthiscontext_options">#</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 <code>script</code>'s compiled code and returns the result. Running code does not have access to local scope, but does have access to the current <code>global</code> object. </p> <p>Example of using <code>script.runInThisContext</code> to compile code once and run it multiple times: </p> <pre><code>const vm = require('vm'); global.globalVar = 0; const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); for (var i = 0; i < 1000; ++i) { script.runInThisContext(); } console.log(globalVar); // 1000</code></pre> <p>The options for running a script are: </p> <ul> <li><code>filename</code>: allows you to control the filename that shows up in any stack traces produced.</li> <li><code>lineOffset</code>: allows you to add an offset to the line number that is displayed in stack traces</li> <li><code>columnOffset</code>: allows you to add an offset to the column number that is displayed in stack traces</li> <li><code>displayErrors</code>: whether or not to print any errors to stderr, with the line of code that caused them highlighted, before throwing an exception. Applies only to runtime errors executing the code; it is impossible to create a <code>Script</code> instance with syntax errors, as the constructor will throw.</li> <li><code>timeout</code>: a number of milliseconds to execute the script before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> <h2>vm.createContext([sandbox])<span><a class="mark" href="#all_vm_createcontext_sandbox" id="all_vm_createcontext_sandbox">#</a></span></h2> <p>If given a <code>sandbox</code> object, will "contextify" that sandbox so that it can be used in calls to <code>vm.runInContext</code> or <code>script.runInContext</code>. Inside scripts run as such, <code>sandbox</code> will be the global object, retaining all its existing properties but also having the built-in objects and functions any standard <a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, <code>sandbox</code> will be unchanged. </p> <p>If not given a sandbox object, returns a new, empty contextified sandbox object you can use. </p> <p>This function is useful for creating a sandbox that can be used to run multiple scripts, e.g. if you were emulating a web browser it could be used to create a single sandbox representing a window's global object, then run all <code><script></code> tags together inside that sandbox. </p> <h2>vm.isContext(sandbox)<span><a class="mark" href="#all_vm_iscontext_sandbox" id="all_vm_iscontext_sandbox">#</a></span></h2> <p>Returns whether or not a sandbox object has been contextified by calling <code>vm.createContext</code> on it. </p> <h2>vm.runInContext(code, contextifiedSandbox[, options])<span><a class="mark" href="#all_vm_runincontext_code_contextifiedsandbox_options" id="all_vm_runincontext_code_contextifiedsandbox_options">#</a></span></h2> <p><code>vm.runInContext</code> compiles <code>code</code>, then runs it in <code>contextifiedSandbox</code> and returns the result. Running code does not have access to local scope. The <code>contextifiedSandbox</code> object must have been previously contextified via <code>vm.createContext</code>; it will be used as the global object for <code>code</code>. </p> <p><code>vm.runInContext</code> takes the same options as <code>vm.runInThisContext</code>. </p> <p>Example: compile and execute different scripts in a single existing context. </p> <pre><code>const util = require('util'); const vm = require('vm'); const sandbox = { globalVar: 1 }; vm.createContext(sandbox); for (var i = 0; i < 10; ++i) { vm.runInContext('globalVar *= 2;', sandbox); } console.log(util.inspect(sandbox)); // { globalVar: 1024 }</code></pre> <p>Note that running untrusted code is a tricky business requiring great care. <code>vm.runInContext</code> is quite useful, but safely running untrusted code requires a separate process. </p> <h2>vm.runInDebugContext(code)<span><a class="mark" href="#all_vm_runindebugcontext_code" id="all_vm_runindebugcontext_code">#</a></span></h2> <p><code>vm.runInDebugContext</code> compiles and executes <code>code</code> inside the V8 debug context. The primary use case is to get access to the V8 debug object: </p> <pre><code>const Debug = vm.runInDebugContext('Debug'); Debug.scripts().forEach(function(script) { console.log(script.name); });</code></pre> <p>Note that the debug context and object are intrinsically tied to V8's debugger implementation and may change (or even get removed) without prior warning. </p> <p>The debug object can also be exposed with the <code>--expose_debug_as=</code> switch. </p> <h2>vm.runInNewContext(code[, sandbox][, options])<span><a class="mark" href="#all_vm_runinnewcontext_code_sandbox_options" id="all_vm_runinnewcontext_code_sandbox_options">#</a></span></h2> <p><code>vm.runInNewContext</code> compiles <code>code</code>, contextifies <code>sandbox</code> if passed or creates a new contextified sandbox if it's omitted, and then runs the code with the sandbox as the global object and returns the result. </p> <p><code>vm.runInNewContext</code> takes the same options as <code>vm.runInThisContext</code>. </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>const util = require('util'); const vm = require('vm'); const sandbox = { animal: 'cat', count: 2 }; vm.runInNewContext('count += 1; name = "kitty"', sandbox); 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. <code>vm.runInNewContext</code> is quite useful, but safely running untrusted code requires a separate process. </p> <h2>vm.runInThisContext(code[, options])<span><a class="mark" href="#all_vm_runinthiscontext_code_options" id="all_vm_runinthiscontext_code_options">#</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, but does have access to the current <code>global</code> object. </p> <p>Example of using <code>vm.runInThisContext</code> and <code>eval</code> to run the same code: </p> <pre><code>const vm = require('vm'); var localVar = 'initial value'; const vmResult = vm.runInThisContext('localVar = "vm";'); console.log('vmResult: ', vmResult); console.log('localVar: ', localVar); const evalResult = eval('localVar = "eval";'); console.log('evalResult: ', evalResult); console.log('localVar: ', localVar); // vmResult: 'vm', localVar: 'initial value' // evalResult: 'eval', localVar: 'eval'</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 this way <code>vm.runInThisContext</code> is much like an <a href="https://es5.github.io/#x10.4.2">indirect <code>eval</code> call</a>, e.g. <code>(0,eval)('code')</code>. However, it also has the following additional options: </p> <ul> <li><code>filename</code>: allows you to control the filename that shows up in any stack traces produced.</li> <li><code>lineOffset</code>: allows you to add an offset to the line number that is displayed in stack traces</li> <li><code>columnOffset</code>: allows you to add an offset to the column number that is displayed in stack traces</li> <li><code>displayErrors</code>: whether or not to print any errors to stderr, with the line of code that caused them highlighted, before throwing an exception. Will capture both syntax errors from compiling <code>code</code> and runtime errors thrown by executing the compiled code. Defaults to <code>true</code>.</li> <li><code>timeout</code>: a number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> <h1>Zlib<span><a class="mark" href="#all_zlib" id="all_zlib">#</a></span></h1> <pre class="api_stability_2">Stability: 2 - Stable</pre><p>You can access this module with: </p> <pre><code>const 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>const gzip = zlib.createGzip(); const fs = require('fs'); const inp = fs.createReadStream('input.txt'); const 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>const input = '.................................'; zlib.deflate(input, function(err, buffer) { if (!err) { console.log(buffer.toString('base64')); } }); const 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="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3">accept-encoding</a> on requests, and the <a href="https://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 const zlib = require('zlib'); const http = require('http'); const fs = require('fs'); const request = http.get({ host: 'izs.me', path: '/', port: 80, headers: { 'accept-encoding': 'gzip,deflate' } }); request.on('response', (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. const zlib = require('zlib'); const http = require('http'); const fs = require('fs'); http.createServer((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>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.js'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.js 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 <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> <h2>Class Options<span><a class="mark" href="#all_class_options" id="all_class_options">#</a></span></h2> <!--type=misc--> <p>Each class takes an options object. All options are optional. </p> <p>Note that some options are only relevant when compressing, and are ignored by the decompression classes. </p> <ul> <li>flush (default: <code>zlib.Z_NO_FLUSH</code>)</li> <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 </p> <p><a href="http://zlib.net/manual.html#Advanced">http://zlib.net/manual.html#Advanced</a> for more information on these. </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.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.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.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.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.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>Class: zlib.Zlib<span><a class="mark" href="#all_class_zlib_zlib" id="all_class_zlib_zlib">#</a></span></h2> <p>Not exported by the <code>zlib</code> module. It is documented here because it is the base class of the compressor/decompressor classes. </p> <h3>zlib.flush([kind], callback)<span><a class="mark" href="#all_zlib_flush_kind_callback" id="all_zlib_flush_kind_callback">#</a></span></h3> <p><code>kind</code> defaults to <code>zlib.Z_FULL_FLUSH</code>. </p> <p>Flush pending data. Don't call this frivolously, premature flushes negatively impact the effectiveness of the compression algorithm. </p> <h3>zlib.params(level, strategy, callback)<span><a class="mark" href="#all_zlib_params_level_strategy_callback" id="all_zlib_params_level_strategy_callback">#</a></span></h3> <p>Dynamically update the compression level and compression strategy. Only applicable to deflate algorithm. </p> <h3>zlib.reset()<span><a class="mark" href="#all_zlib_reset" id="all_zlib_reset">#</a></span></h3> <p>Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms. </p> <h2>zlib.createDeflate(<a href="#zlib_class_options">options</a>)<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_class_options">options</a>. </p> <h2>zlib.createDeflateRaw(<a href="#zlib_class_options">options</a>)<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_class_options">options</a>. </p> <h2>zlib.createGunzip(<a href="#zlib_class_options">options</a>)<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_class_options">options</a>. </p> <h2>zlib.createGzip(<a href="#zlib_class_options">options</a>)<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_class_options">options</a>. </p> <h2>zlib.createInflate(<a href="#zlib_class_options">options</a>)<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_class_options">options</a>. </p> <h2>zlib.createInflateRaw(<a href="#zlib_class_options">options</a>)<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_class_options">options</a>. </p> <h2>zlib.createUnzip(<a href="#zlib_class_options">options</a>)<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_class_options">options</a>. </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, an optional second argument to supply options to the zlib classes and will call the supplied callback with <code>callback(error, result)</code>. </p> <p>Every method has a <code>*Sync</code> counterpart, which accept the same arguments, but without a callback. </p> <h3>zlib.deflate(buf[, options], callback)<span><a class="mark" href="#all_zlib_deflate_buf_options_callback" id="all_zlib_deflate_buf_options_callback">#</a></span></h3> <p>Compress a string with Deflate. </p> <h3>zlib.deflateRaw(buf[, options], callback)<span><a class="mark" href="#all_zlib_deflateraw_buf_options_callback" id="all_zlib_deflateraw_buf_options_callback">#</a></span></h3> <h3>zlib.deflateRawSync(buf[, options])<span><a class="mark" href="#all_zlib_deflaterawsync_buf_options" id="all_zlib_deflaterawsync_buf_options">#</a></span></h3> <p>Compress a string with DeflateRaw. </p> <h3>zlib.deflateSync(buf[, options])<span><a class="mark" href="#all_zlib_deflatesync_buf_options" id="all_zlib_deflatesync_buf_options">#</a></span></h3> <p>Compress a string with Deflate. </p> <h3>zlib.gunzip(buf[, options], callback)<span><a class="mark" href="#all_zlib_gunzip_buf_options_callback" id="all_zlib_gunzip_buf_options_callback">#</a></span></h3> <h3>zlib.gunzipSync(buf[, options])<span><a class="mark" href="#all_zlib_gunzipsync_buf_options" id="all_zlib_gunzipsync_buf_options">#</a></span></h3> <p>Decompress a raw Buffer with Gunzip. </p> <h3>zlib.gzip(buf[, options], callback)<span><a class="mark" href="#all_zlib_gzip_buf_options_callback" id="all_zlib_gzip_buf_options_callback">#</a></span></h3> <h3>zlib.gzipSync(buf[, options])<span><a class="mark" href="#all_zlib_gzipsync_buf_options" id="all_zlib_gzipsync_buf_options">#</a></span></h3> <p>Compress a string with Gzip. </p> <h3>zlib.inflate(buf[, options], callback)<span><a class="mark" href="#all_zlib_inflate_buf_options_callback" id="all_zlib_inflate_buf_options_callback">#</a></span></h3> <p>Decompress a raw Buffer with Inflate. </p> <h3>zlib.inflateRaw(buf[, options], callback)<span><a class="mark" href="#all_zlib_inflateraw_buf_options_callback" id="all_zlib_inflateraw_buf_options_callback">#</a></span></h3> <h3>zlib.inflateRawSync(buf[, options])<span><a class="mark" href="#all_zlib_inflaterawsync_buf_options" id="all_zlib_inflaterawsync_buf_options">#</a></span></h3> <p>Decompress a raw Buffer with InflateRaw. </p> <h3>zlib.inflateSync(buf[, options])<span><a class="mark" href="#all_zlib_inflatesync_buf_options" id="all_zlib_inflatesync_buf_options">#</a></span></h3> <p>Decompress a raw Buffer with Inflate. </p> <h3>zlib.unzip(buf[, options], callback)<span><a class="mark" href="#all_zlib_unzip_buf_options_callback" id="all_zlib_unzip_buf_options_callback">#</a></span></h3> <h3>zlib.unzipSync(buf[, options])<span><a class="mark" href="#all_zlib_unzipsync_buf_options" id="all_zlib_unzipsync_buf_options">#</a></span></h3> <p>Decompress a raw Buffer with Unzip. </p> </div> </div> </div> <script src="assets/sh_main.js"></script> <script src="assets/sh_javascript.min.js"></script> <script>highlight(undefined, undefined, 'pre');</script> </body> </html>