1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Child Process | Node.js v4.8.2 Manual & Documentation</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic">
<link rel="stylesheet" href="assets/style.css">
<link rel="stylesheet" href="assets/sh.css">
<link rel="canonical" href="https://nodejs.org/api/child_process.html">
</head>
<body class="alt apidoc" id="api-section-child_process">
<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
</a>
</div>
<ul>
<li><a class="nav-documentation" href="documentation.html">About these Docs</a></li>
<li><a class="nav-synopsis" href="synopsis.html">Usage & Example</a></li>
</ul>
<div class="line"></div>
<ul>
<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 active" href="child_process.html">Child Processes</a></li>
<li><a class="nav-cluster" href="cluster.html">Cluster</a></li>
<li><a class="nav-cli" href="cli.html">Command Line Options</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 class="line"></div>
<ul>
<li><a class="nav-https-github-com-nodejs-node" href="https://github.com/nodejs/node">GitHub Repo & Issue Tracker</a></li>
<li><a class="nav-http-groups-google-com-group-nodejs" href="http://groups.google.com/group/nodejs">Mailing List</a></li>
</ul>
</div>
<div id="column1" data-id="child_process" class="interior">
<header>
<h1>Node.js v4.8.2 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="child_process.json">View as JSON</a>
</p>
</div>
<hr>
</header>
<div id="toc">
<h2>Table of Contents</h2>
<ul>
<li><span class="stability_2"><a href="#child_process_child_process">Child Process</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_asynchronous_process_creation">Asynchronous Process Creation</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_spawning_bat_and_cmd_files_on_windows">Spawning <code>.bat</code> and <code>.cmd</code> files on Windows</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_exec_command_options_callback">child_process.exec(command[, options][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_execfile_file_args_options_callback">child_process.execFile(file[, args][, options][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_fork_modulepath_args_options">child_process.fork(modulePath[, args][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_spawn_command_args_options">child_process.spawn(command[, args][, options])</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_options_detached">options.detached</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_options_stdio">options.stdio</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_synchronous_process_creation">Synchronous Process Creation</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_child_process_execfilesync_file_args_options">child_process.execFileSync(file[, args][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_execsync_command_options">child_process.execSync(command[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_spawnsync_command_args_options">child_process.spawnSync(command[, args][, options])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_class_childprocess">Class: ChildProcess</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_disconnect">Event: 'disconnect'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_exit">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_message">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_connected">child.connected</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_disconnect">child.disconnect()</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_kill_signal">child.kill([signal])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_pid">child.pid</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_send_message_sendhandle_callback">child.send(message[, sendHandle][, callback])</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_example_sending_a_server_object">Example: sending a server object</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_example_sending_a_socket_object">Example: sending a socket object</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_child_stderr">child.stderr</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_stdin">child.stdin</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_stdio">child.stdio</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_stdout">child.stdout</a></span></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div id="apicontent">
<h1>Child Process<span><a class="mark" href="#child_process_child_process" id="child_process_child_process">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>The <code>child_process</code> module provides the ability to spawn child processes in
a manner that is similar, but not identical, to <a href="http://linux.die.net/man/3/popen"><code>popen(3)</code></a>. This capability
is primarily provided by the <code>child_process.spawn()</code> function:</p>
<pre><code class="lang-js">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>By default, pipes for <code>stdin</code>, <code>stdout</code> and <code>stderr</code> are established between
the parent Node.js process and the spawned child. It is possible to stream data
through these pipes in a non-blocking way. <em>Note, however, that some programs
use line-buffered I/O internally. While that does not affect Node.js, it can
mean that data sent to the child process may not be immediately consumed.</em></p>
<p>The <code>child_process.spawn()</code> method spawns the child process asynchronously,
without blocking the Node.js event loop. The <code>child_process.spawnSync()</code>
function provides equivalent functionality in a synchronous manner that blocks
the event loop until the spawned process either exits or is terminated.</p>
<p>For convenience, the <code>child_process</code> module provides a handful of synchronous
and asynchronous alternatives to <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> and
<a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>. <em>Note that each of these alternatives are
implemented on top of <code>child_process.spawn()</code> or <code>child_process.spawnSync()</code>.</em></p>
<ul>
<li><code>child_process.exec()</code>: spawns a shell and runs a command within that shell,
passing the <code>stdout</code> and <code>stderr</code> to a callback function when complete.</li>
<li><code>child_process.execFile()</code>: similar to <code>child_process.exec()</code> except that
it spawns the command directly without first spawning a shell.</li>
<li><code>child_process.fork()</code>: spawns a new Node.js process and invokes a
specified module with an IPC communication channel established that allows
sending messages between parent and child.</li>
<li><code>child_process.execSync()</code>: a synchronous version of
<code>child_process.exec()</code> that <em>will</em> block the Node.js event loop.</li>
<li><code>child_process.execFileSync()</code>: a synchronous version of
<code>child_process.execFile()</code> that <em>will</em> block the Node.js event loop.</li>
</ul>
<p>For certain use cases, such as automating shell scripts, the
<a href="#child_process_synchronous_process_creation">synchronous counterparts</a> may be more convenient. In many cases, however,
the synchronous methods can have significant impact on performance due to
stalling the event loop while spawned processes complete.</p>
<h2>Asynchronous Process Creation<span><a class="mark" href="#child_process_asynchronous_process_creation" id="child_process_asynchronous_process_creation">#</a></span></h2>
<p>The <code>child_process.spawn()</code>, <code>child_process.fork()</code>, <code>child_process.exec()</code>,
and <code>child_process.execFile()</code> methods all follow the idiomatic asynchronous
programming pattern typical of other Node.js APIs.</p>
<p>Each of the methods returns a <a href="#child_process_child_process"><code>ChildProcess</code></a> instance. These objects
implement the Node.js <a href="events.html#events_class_events_eventemitter"><code>EventEmitter</code></a> API, allowing the parent process to
register listener functions that are called when certain events occur during
the life cycle of the child process.</p>
<p>The <code>child_process.exec()</code> and <code>child_process.execFile()</code> methods additionally
allow for an optional <code>callback</code> function to be specified that is invoked
when the child process terminates.</p>
<h3>Spawning <code>.bat</code> and <code>.cmd</code> files on Windows<span><a class="mark" href="#child_process_spawning_bat_and_cmd_files_on_windows" id="child_process_spawning_bat_and_cmd_files_on_windows">#</a></span></h3>
<p>The importance of the distinction between <code>child_process.exec()</code> and
<code>child_process.execFile()</code> can vary based on platform. On Unix-type operating
systems (Unix, Linux, OSX) <code>child_process.execFile()</code> can be more efficient
because it does not spawn a shell. On Windows, however, <code>.bat</code> and <code>.cmd</code>
files are not executable on their own without a terminal, and therefore cannot
be launched using <code>child_process.execFile()</code>. When running on Windows, <code>.bat</code>
and <code>.cmd</code> files can be invoked using <code>child_process.spawn()</code> with the <code>shell</code>
option set, with <code>child_process.exec()</code>, or by spawning <code>cmd.exe</code> and passing
the <code>.bat</code> or <code>.cmd</code> file as an argument (which is what the <code>shell</code> option and
<code>child_process.exec()</code> do).</p>
<pre><code class="lang-js">// On Windows Only ...
const spawn = require('child_process').spawn;
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
bat.stdout.on('data', (data) => {
console.log(data);
});
bat.stderr.on('data', (data) => {
console.log(data);
});
bat.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});
// OR...
const exec = require('child_process').exec;
exec('my.bat', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
</code></pre>
<h3>child_process.exec(command[, options][, callback])<span><a class="mark" href="#child_process_child_process_exec_command_options_callback" id="child_process_child_process_exec_command_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The command to run, with space-separated arguments</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Current working directory of the child process</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> (Default: 'utf8')</li>
<li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> (Default: 0)</li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <span class="type"><Integer></span> (Default: 'SIGTERM')</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html">setuid(2)</a>.)</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html">setgid(2)</a>.)</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> called with the output when process terminates<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="child_process.html#child_process_class_childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>Spawns a shell then executes the <code>command</code> within that shell, buffering any
generated output.</p>
<p><strong>Note: Never pass unsanitised user input to this function. Any input
containing shell metacharacters may be used to trigger arbitrary command
execution.</strong></p>
<pre><code class="lang-js">const exec = require('child_process').exec;
exec('cat *.js bad_file | wc -l', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
</code></pre>
<p>If a <code>callback</code> function is provided, it is called with 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>. The <code>error.code</code> property will be
the exit code of the child process while <code>error.signal</code> will be set to the
signal that terminated the process. Any exit code other than <code>0</code> is considered
to be an error.</p>
<p>The <code>stdout</code> and <code>stderr</code> arguments passed to the callback will contain the
stdout and stderr output of the child process. By default, Node.js will decode
the output as UTF-8 and pass strings to the callback. The <code>encoding</code> option
can be used to specify the character encoding used to decode the stdout and
stderr output. If <code>encoding</code> is <code>'buffer'</code>, or an unrecognized character
encoding, <code>Buffer</code> objects will be passed to the callback instead.</p>
<p>The <code>options</code> argument may be passed as the second argument to customize how
the process is spawned. The default options are:</p>
<pre><code class="lang-js">{
encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null
}
</code></pre>
<p>If <code>timeout</code> is greater than <code>0</code>, the parent will send the the signal
identified by the <code>killSignal</code> property (the default is <code>'SIGTERM'</code>) if the
child runs longer than <code>timeout</code> milliseconds.</p>
<p>The <code>maxBuffer</code> option specifies the largest amount of data (in bytes) allowed
on stdout or stderr - if this value is exceeded then the child process is
terminated.</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="#child_process_child_process_execfile_file_args_options_callback" id="child_process_child_process_execfile_file_args_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.91</span>
</div><ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The name or path of the executable file to run</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Current working directory of the child process</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> (Default: 'utf8')</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> (Default: 0)</li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <span class="type"><Integer></span> (Default: 'SIGTERM')</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html">setuid(2)</a>.)</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html">setgid(2)</a>.)</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> called with the output when process terminates<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="child_process.html#child_process_class_childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>The <code>child_process.execFile()</code> function is similar to <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>
except that it does not spawn a shell. Rather, the specified executable <code>file</code>
is spawned directly as a new process making it slightly more efficient than
<a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>.</p>
<p>The same options as <code>child_process.exec()</code> are supported. Since a shell is not
spawned, behaviors such as I/O redirection and file globbing are not supported.</p>
<pre><code class="lang-js">const execFile = require('child_process').execFile;
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
</code></pre>
<p>The <code>stdout</code> and <code>stderr</code> arguments passed to the callback will contain the
stdout and stderr output of the child process. By default, Node.js will decode
the output as UTF-8 and pass strings to the callback. The <code>encoding</code> option
can be used to specify the character encoding used to decode the stdout and
stderr output. If <code>encoding</code> is <code>'buffer'</code>, or an unrecognized character
encoding, <code>Buffer</code> objects will be passed to the callback instead.</p>
<h3>child_process.fork(modulePath[, args][, options])<span><a class="mark" href="#child_process_child_process_fork_modulepath_args_options" id="child_process_child_process_fork_modulepath_args_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><ul>
<li><code>modulePath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The module to run in the child</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Current working directory of the child process</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs</li>
<li><code>execPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Executable used to create the child process</li>
<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments passed to the executable
(Default: <code>process.execArgv</code>)</li>
<li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> 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>child_process.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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html">setuid(2)</a>.)</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html">setgid(2)</a>.)</li>
</ul>
</li>
<li>Returns: <a href="child_process.html#child_process_class_childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>The <code>child_process.fork()</code> method is a special case of
<a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> used specifically to spawn new Node.js processes.
Like <code>child_process.spawn()</code>, a <code>ChildProcess</code> object is returned. The returned
<code>ChildProcess</code> will have an additional communication channel built-in that
allows messages to be passed back and forth between the parent and child. See
<a href="#child_process_child_send_message_sendhandle_callback"><code>ChildProcess#send()</code></a> for details.</p>
<p>It is important to keep in mind that spawned Node.js child processes are
independent of the parent with exception of the IPC communication channel
that is established between the two. Each process has its own memory, with
their own V8 instances. Because of the additional resource allocations
required, spawning a large number of child Node.js processes is not
recommended.</p>
<p>By default, <code>child_process.fork()</code> will spawn new Node.js instances using the
<code>process.execPath</code> of the parent process. The <code>execPath</code> property in the
<code>options</code> object allows for an alternative execution path to be used.</p>
<p>Node.js processes launched with a custom <code>execPath</code> will communicate with the
parent process using the file descriptor (fd) identified using the
environment 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_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="#child_process_child_process_spawn_command_args_options" id="child_process_child_process_spawn_command_args_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The command to run</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Current working directory of the child process</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs</li>
<li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Child's stdio configuration. (See
<a href="#child_process_options_stdio"><code>options.stdio</code></a>)</li>
<li><code>detached</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Prepare child to run independently of its parent
process. Specific behavior depends on the platform, see
<a href="#child_process_options_detached"><code>options.detached</code></a>)</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html">setuid(2)</a>.)</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html">setgid(2)</a>.)</li>
<li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses
'/bin/sh' on UNIX, and 'cmd.exe' on Windows. A different shell can be
specified as a string. The shell should understand the <code>-c</code> switch on UNIX,
or <code>/s /c</code> on Windows. Defaults to <code>false</code> (no shell).</li>
</ul>
</li>
<li>Returns: <a href="child_process.html#child_process_class_childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>The <code>child_process.spawn()</code> method spawns a new process using 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><strong>Note: If the <code>shell</code> option is enabled, do not pass unsanitised user input to
this function. Any input containing shell metacharacters may be used to
trigger arbitrary command execution.</strong></p>
<p>A third argument may be used to specify additional options, with these defaults:</p>
<pre><code class="lang-js">{
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 class="lang-js">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 class="lang-js">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 class="lang-js">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="#child_process_options_detached" id="child_process_options_detached">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</div><p>On Windows, setting <code>options.detached</code> to <code>true</code> makes it possible for the
child process to continue running after the parent exits. The child will have
its own console window. <em>Once enabled for a child process, it cannot be
disabled</em>.</p>
<p>On non-Windows platforms, if <code>options.detached</code> is set to <code>true</code>, 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 regardless of
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.
Doing so will cause the parent's event loop to not include the child in its
reference count, allowing the parent to exit independently of the child, unless
there is an established IPC channel between the child and parent.</p>
<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>
<p>Example of a long-running process, by detaching and also ignoring its parent
<code>stdio</code> file descriptors, in order to ignore the parent's termination:</p>
<pre><code class="lang-js">const spawn = require('child_process').spawn;
const child = spawn(process.argv[0], ['child_program.js'], {
detached: true,
stdio: 'ignore'
});
child.unref();
</code></pre>
<p>Alternatively one can redirect the child process' output into files:</p>
<pre><code class="lang-js">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>
<h4>options.stdio<span><a class="mark" href="#child_process_options_stdio" id="child_process_options_stdio">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</div><p>The <code>options.stdio</code> option is used to configure the pipes that are established
between the parent and child process. By default, the child's stdin, stdout,
and stderr are redirected to corresponding <code>child.stdin</code>, <code>child.stdout</code>, and
<code>child.stderr</code> streams on the <code>ChildProcess</code> object. This is equivalent to
setting the <code>options.stdio</code> equal to <code>['pipe', 'pipe', 'pipe']</code>.</p>
<p>For convenience, <code>options.stdio</code> may be one of the following strings:</p>
<ul>
<li><code>'pipe'</code> - equivalent to <code>['pipe', 'pipe', 'pipe']</code> (the default)</li>
<li><code>'ignore'</code> - equivalent to <code>['ignore', 'ignore', 'ignore']</code></li>
<li><code>'inherit'</code> - equivalent to <code>[process.stdin, process.stdout, process.stderr]</code>
or <code>[0,1,2]</code></li>
</ul>
<p>Otherwise, the value of <code>option.stdio</code> is an array where each index corresponds
to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,
and stderr, respectively. Additional fds can be specified to create additional
pipes between the parent and 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, the
<code>ChildProcess.on('message')</code> event handler will be triggered in the parent.
If the child is a Node.js process, the presence of an IPC channel will enable
<code>process.send()</code>, <code>process.disconnect()</code>, <code>process.on('disconnect')</code>, and
<code>process.on('message')</code> within the child.</li>
<li><code>'ignore'</code> - Instructs Node.js to ignore the fd in the child. While Node.js
will always open fds 0 - 2 for the processes it spawns, setting the fd to
<code>'ignore'</code> will cause Node.js to 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 class="lang-js">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 presenting a
// startd-style interface.
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
</code></pre>
<p><em>It is worth noting that when an IPC channel is established between the
parent and child processes, and the child is a Node.js process, the child
is launched with the IPC channel unreferenced (using <code>unref()</code>) until the
child registers an event handler for the <code>process.on('disconnect')</code> event
or the <code>process.on('message')</code> event.This allows the child to exit normally
without the process being held open by the open IPC channel.</em></p>
<p>See also: <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a></p>
<h2>Synchronous Process Creation<span><a class="mark" href="#child_process_synchronous_process_creation" id="child_process_synchronous_process_creation">#</a></span></h2>
<p>The <code>child_process.spawnSync()</code>, <code>child_process.execSync()</code>, and
<code>child_process.execFileSync()</code> methods are <strong>synchronous</strong> and <strong>WILL</strong> block
the Node.js event loop, pausing execution of any additional 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="#child_process_child_process_execfilesync_file_args_options" id="child_process_child_process_execfilesync_file_args_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The name or path of the executable file to run</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Current working directory of the child process</li>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html">setuid(2)</a>.)</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html">setgid(2)</a>.)</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)</li>
<li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <span class="type"><Integer></span> The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')</li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> largest amount of data (in bytes) allowed on stdout or
stderr - if exceeded child process is killed</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The encoding used for all stdio inputs and outputs. (Default: 'buffer')</li>
</ul>
</li>
<li>Returns: <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The stdout from the command</li>
</ul>
<p>The <code>child_process.execFileSync()</code> method is generally identical to
<code>child_process.execFile()</code> with the exception that the method 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. <em>Note that if the child process intercepts and handles
the <code>SIGTERM</code> signal and does not exit, the parent process will still wait
until the child process has exited.</em></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="#child_process_child_process_execsync_command_options" id="child_process_child_process_execsync_command_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The command to run</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Current working directory of the child process</li>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs</li>
<li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html">setuid(2)</a>.)</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html">setgid(2)</a>.)</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)</li>
<li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <span class="type"><Integer></span> The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')</li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> largest amount of data (in bytes) allowed on stdout or
stderr - if exceeded child process is killed</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The encoding used for all stdio inputs and outputs. (Default: 'buffer')</li>
</ul>
</li>
<li>Returns: <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The stdout from the command</li>
</ul>
<p>The <code>child_process.execSync()</code> method is generally identical to
<code>child_process.exec()</code> with the exception that the method 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. <em>Note that if the child process intercepts and handles the <code>SIGTERM</code>
signal and doesn't exit, the parent process will wait until the child
process has exited.</em></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>
<p><strong>Note: Never pass unsanitised user input to this function. Any input
containing shell metacharacters may be used to trigger arbitrary command
execution.</strong></p>
<h3>child_process.spawnSync(command[, args][, options])<span><a class="mark" href="#child_process_child_process_spawnsync_command_args_options" id="child_process_child_process_spawnsync_command_args_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The command to run</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Current working directory of the child process</li>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Child's stdio configuration. (Default: 'pipe')</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html">setuid(2)</a>.)</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html">setgid(2)</a>.)</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)</li>
<li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <span class="type"><Integer></span> The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')</li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> largest amount of data (in bytes) allowed on stdout or
stderr - if exceeded child process is killed</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The encoding used for all stdio inputs and outputs. (Default: 'buffer')</li>
<li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses
'/bin/sh' on UNIX, and 'cmd.exe' on Windows. A different shell can be
specified as a string. The shell should understand the <code>-c</code> switch on UNIX,
or <code>/s /c</code> on Windows. Defaults to <code>false</code> (no shell).</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Pid of the child process</li>
<li><code>output</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Array of results from stdio output</li>
<li><code>stdout</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The contents of <code>output[1]</code></li>
<li><code>stderr</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The contents of <code>output[2]</code></li>
<li><code>status</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The exit code of the child process</li>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The signal used to kill the child process</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The error object if the child process failed or timed out</li>
</ul>
</li>
</ul>
<p>The <code>child_process.spawnSync()</code> method is generally identical to
<code>child_process.spawn()</code> with the exception that the function 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. Note that if the process intercepts and handles the
<code>SIGTERM</code> signal and doesn't exit, the parent process will wait until the child
process has exited.</p>
<p><strong>Note: If the <code>shell</code> option is enabled, do not pass unsanitised user input to
this function. Any input containing shell metacharacters may be used to
trigger arbitrary command execution.</strong></p>
<h2>Class: ChildProcess<span><a class="mark" href="#child_process_class_childprocess" id="child_process_class_childprocess">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v2.2.0</span>
</div><p>Instances of the <code>ChildProcess</code> class are <a href="events.html#events_class_events_eventemitter"><code>EventEmitters</code></a> that represent
spawned child processes.</p>
<p>Instances of <code>ChildProcess</code> are not intended to be created directly. Rather,
use the <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>, <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>,
<a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a>, or <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> methods to create
instances of <code>ChildProcess</code>.</p>
<h3>Event: 'close'<span><a class="mark" href="#child_process_event_close" id="child_process_event_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> the exit code if the child exited on its own.</li>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> the signal by which the child process was terminated.</li>
</ul>
<p>The <code>'close'</code> event is emitted when the stdio streams of a child process have
been closed. This is distinct from the <code>'exit'</code> event, since multiple
processes might share the same stdio streams.</p>
<h3>Event: 'disconnect'<span><a class="mark" href="#child_process_event_disconnect" id="child_process_event_disconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div><p>The <code>'disconnect'</code> event is emitted after calling the
<code>ChildProcess.disconnect()</code> method in the parent or child process. After
disconnecting it is no longer possible to send or receive messages, and the
<code>ChildProcess.connected</code> property is false.</p>
<h3>Event: 'error'<span><a class="mark" href="#child_process_event_error" id="child_process_event_error">#</a></span></h3>
<div class="signature"><ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> the error.</li>
</ul>
</div><p>The <code>'error'</code> event is emitted whenever:</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 to both the <code>'exit'</code> and <code>'error'</code> events, it is important
to guard against accidentally invoking handler functions multiple times.</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="#child_process_event_exit" id="child_process_event_exit">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> the exit code if the child exited on its own.</li>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> the signal by which the child process was terminated.</li>
</ul>
<p>The <code>'exit'</code> event is emitted after the child process ends. If the process
exited, <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>. One of the two will always be non-null.</p>
<p>Note that when the <code>'exit'</code> event is triggered, 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> and Node.js processes will not terminate immediately due to receipt
of those signals. Rather, Node.js will perform a sequence of cleanup actions
and then will re-raise the handled signal.</p>
<p>See <code>waitpid(2)</code>.</p>
<h3>Event: 'message'<span><a class="mark" href="#child_process_event_message" id="child_process_event_message">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div><ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> a parsed JSON object or primitive value.</li>
<li><code>sendHandle</code> <a href="net.html#net_server_listen_handle_backlog_callback" class="type"><Handle></a> 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>
</ul>
<p>The <code>'message'</code> event is triggered when a child process uses <code>process.send()</code>
to send messages.</p>
<h3>child.connected<span><a class="mark" href="#child_process_child_connected" id="child_process_child_connected">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Set to false after <code>.disconnect</code> is called</li>
</ul>
<p>The <code>child.connected</code> property indicates whether it is still possible to send
and receive messages from a child process. When <code>child.connected</code> is false, it
is no longer possible to send or receive messages.</p>
<h3>child.disconnect()<span><a class="mark" href="#child_process_child_disconnect" id="child_process_child_disconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div><p>Closes 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>child.connected</code> and <code>process.connected</code> properties in both
the parent and child (respectively) will be set to <code>false</code>, and it will be no
longer possible to pass messages between the processes.</p>
<p>The <code>'disconnect'</code> event will be emitted when there are no messages in the
process of being received. This will most often be triggered immediately after
calling <code>child.disconnect()</code>.</p>
<p>Note that when the child process is a Node.js instance (e.g. spawned using
<a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>), the <code>process.disconnect()</code> method can be invoked
within the child process to close the IPC channel as well.</p>
<h3>child.kill([signal])<span><a class="mark" href="#child_process_child_kill_signal" id="child_process_child_kill_signal">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a></li>
</ul>
<p>The <code>child.kill()</code> methods sends a signal to the child process. If no argument
is given, the process will be sent the <code>'SIGTERM'</code> signal. See <a href="http://man7.org/linux/man-pages/man7/signal.7.html">signal(7)</a> for
a list of available signals.</p>
<pre><code class="lang-js">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>The <code>ChildProcess</code> object may emit an <code>'error'</code> event if 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 which can have unexpected results.</p>
<p>Note that while the function is called <code>kill</code>, the signal delivered to the
child process may not actually terminate the process.</p>
<p>See <code>kill(2)</code> for reference.</p>
<p>Also note: on Linux, child processes of child processes will not be terminated
when attempting to kill their parent. This is likely to happen when running a
new process in a shell or with use of the <code>shell</code> option of <code>ChildProcess</code>, such
as in this example:</p>
<pre><code class="lang-js">'use strict';
const spawn = require('child_process').spawn;
let child = spawn('sh', ['-c',
`node -e "setInterval(() => {
console.log(process.pid, 'is alive')
}, 500);"`
], {
stdio: ['inherit', 'inherit', 'inherit']
});
setTimeout(() => {
child.kill(); // does not terminate the node process in the shell
}, 2000);
</code></pre>
<h3>child.pid<span><a class="mark" href="#child_process_child_pid" id="child_process_child_pid">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Integer</li>
</ul>
<p>Returns the process identifier (PID) of the child process.</p>
<p>Example:</p>
<pre><code class="lang-js">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="#child_process_child_send_message_sendhandle_callback" id="child_process_child_send_message_sendhandle_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div><ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>sendHandle</code> <a href="net.html#net_server_listen_handle_backlog_callback" class="type"><Handle></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a></li>
</ul>
<p>When an IPC channel has been established between the parent and child (
i.e. when using <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>), the <code>child.send()</code> method can be
used to send messages to the child process. When the child process is a Node.js
instance, these messages can be received via the <code>process.on('message')</code> event.</p>
<p>For example, in the parent script:</p>
<pre><code class="lang-js">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 class="lang-js">process.on('message', (m) => {
console.log('CHILD got message:', m);
});
process.send({ foo: 'bar' });
</code></pre>
<p>Child Node.js processes will have a <code>process.send()</code> method of their own that
allows the child to send messages back to the parent.</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 are considered to be reserved
for use within Node.js core and will not be emitted in the child's
<code>process.on('message')</code> event. Rather, such messages are emitted using the
<code>process.on('internalMessage')</code> event and are consumed internally by Node.js.
Applications should avoid using such messages or listening for
<code>'internalMessage'</code> events as it is subject to change without notice.</p>
<p>The optional <code>sendHandle</code> argument that may be passed to <code>child.send()</code> is for
passing a TCP server or socket object to the child process. The child will
receive the object as the second argument passed to the callback function
registered on the <code>process.on('message')</code> event. Any data that is received and
buffered in the socket will not be sent to the child.</p>
<p>The optional <code>callback</code> is a function that is invoked after the message is
sent but before the child may have received it. The function 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>If no <code>callback</code> function is provided and the message cannot be sent, an
<code>'error'</code> event will be emitted by the <code>ChildProcess</code> object. This can happen,
for instance, when the child process has already exited.</p>
<p><code>child.send()</code> will return <code>false</code> if the channel has closed or when the
backlog of unsent messages exceeds a threshold that makes it unwise to send
more. Otherwise, the method returns <code>true</code>. The <code>callback</code> function can be
used to implement flow control.</p>
<h4>Example: sending a server object<span><a class="mark" href="#child_process_example_sending_a_server_object" id="child_process_example_sending_a_server_object">#</a></span></h4>
<p>The <code>sendHandle</code> argument can be used, for instance, to pass the handle of
a TCP server object to the child process as illustrated in the example below:</p>
<pre><code class="lang-js">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>The child would then receive the server object as:</p>
<pre><code class="lang-js">process.on('message', (m, server) => {
if (m === 'server') {
server.on('connection', (socket) => {
socket.end('handled by child');
});
}
});
</code></pre>
<p>Once the server is now shared between the parent and child, some connections
can be handled by the parent and some by the child.</p>
<p>While the example above uses a server created using the <code>net</code> module, <code>dgram</code>
module servers use exactly the same workflow with the exceptions of listening on
a <code>'message'</code> event instead of <code>'connection'</code> and using <code>server.bind</code> instead of
<code>server.listen</code>. This is, however, currently only supported on UNIX platforms.</p>
<h4>Example: sending a socket object<span><a class="mark" href="#child_process_example_sending_a_socket_object" id="child_process_example_sending_a_socket_object">#</a></span></h4>
<p>Similarly, the <code>sendHandler</code> argument can be used to pass the handle of a
socket to the child process. The example below spawns two children that each
handle connections with "normal" or "special" priority:</p>
<pre><code class="lang-js">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 special priority
if (socket.remoteAddress === '74.125.127.100') {
special.send('socket', socket);
return;
}
// This is normal priority
normal.send('socket', socket);
});
server.listen(1337);
</code></pre>
<p>The <code>child.js</code> would receive the socket handle as the second argument passed
to the event callback function:</p>
<pre><code class="lang-js">process.on('message', (m, socket) => {
if (m === 'socket') {
socket.end(`Request handled with ${process.argv[2]} priority`);
}
});
</code></pre>
<p>Once a socket has been passed to a child, the parent is no longer capable of
tracking when the socket is destroyed. To indicate this, the <code>.connections</code>
property becomes <code>null</code>. It is recommended not to use <code>.maxConnections</code> when
this occurs.</p>
<p><em>Note: this function uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify()</code></a> internally to serialize the <code>message</code>.</em></p>
<h3>child.stderr<span><a class="mark" href="#child_process_child_stderr" id="child_process_child_stderr">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><a href="stream.html#stream_stream" class="type"><Stream></a></li>
</ul>
<p>A <code>Readable Stream</code> that represents the child process's <code>stderr</code>.</p>
<p>If the child was spawned with <code>stdio[2]</code> set to anything other than <code>'pipe'</code>,
then this will be <code>undefined</code>.</p>
<p><code>child.stderr</code> is an alias for <code>child.stdio[2]</code>. Both properties will refer to
the same value.</p>
<h3>child.stdin<span><a class="mark" href="#child_process_child_stdin" id="child_process_child_stdin">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><a href="stream.html#stream_stream" class="type"><Stream></a></li>
</ul>
<p>A <code>Writable Stream</code> that represents the child process's <code>stdin</code>.</p>
<p><em>Note that if a child process waits to read all of its input, the child will not
continue until this stream has been closed via <code>end()</code>.</em></p>
<p>If the child was spawned with <code>stdio[0]</code> set to anything other than <code>'pipe'</code>,
then this will be <code>undefined</code>.</p>
<p><code>child.stdin</code> is an alias for <code>child.stdio[0]</code>. Both properties will refer to
the same value.</p>
<h3>child.stdio<span><a class="mark" href="#child_process_child_stdio" id="child_process_child_stdio">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</div><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</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 passed to <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> that have been set
to the value <code>'pipe'</code>. Note that <code>child.stdio[0]</code>, <code>child.stdio[1]</code>, and
<code>child.stdio[2]</code> are also available as <code>child.stdin</code>, <code>child.stdout</code>, and
<code>child.stderr</code>, respectively.</p>
<p>In the following example, only the child's fd <code>1</code> (stdout) is configured 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 class="lang-js">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="#child_process_child_stdout" id="child_process_child_stdout">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><a href="stream.html#stream_stream" class="type"><Stream></a></li>
</ul>
<p>A <code>Readable Stream</code> that represents the child process's <code>stdout</code>.</p>
<p>If the child was spawned with <code>stdio[1]</code> set to anything other than <code>'pipe'</code>,
then this will be <code>undefined</code>.</p>
<p><code>child.stdout</code> is an alias for <code>child.stdio[1]</code>. Both properties will refer
to the same value.</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>
<!-- __TRACKING__ -->
</body>
</html>
|