{"id":14177,"date":"2022-10-31T00:13:45","date_gmt":"2022-10-30T18:43:45","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=14177"},"modified":"2022-11-13T00:13:56","modified_gmt":"2022-11-12T18:43:56","slug":"nodejs-child-process","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/nodejs-child-process\/","title":{"rendered":"NodeJS Child Process &#8211; A Complete Guide"},"content":{"rendered":"\n<p>NodeJs Child Process is used to create child processes that can run simultaneously proving a multicore functionality to a Node.js application.<\/p>\n\n\n\n<p>Node.js is a single-threaded, it can perform one operation at a time. This limits the scalability of a Node.js Application since we are not able to utilize the full power of the CPU. For running multiple operations at a time parallelly, Node.js Provide a module Child Process which contains many methods used to initiate processes that can run individually without affecting other processes. The child processes then terminate once complete their execution.&nbsp;<\/p>\n\n\n\n<p>To understand the Child Process it is important to have prior knowledge of Events and Streams in Node.js. We have covered<a href=\"https:\/\/codeforgeek.com\/nodejs-events\/\" data-type=\"post\" data-id=\"14146\"> Node.js Events<\/a> and <a href=\"https:\/\/codeforgeek.com\/streams-in-nodejs-part-1\/\" data-type=\"post\" data-id=\"9136\">Node.js Streams <\/a>in another article if you want to learn about them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">NodeJS <strong>Child Process Module<\/strong><\/h2>\n\n\n\n<p>For creating child processes, it is required to import the child process module using the below statement.&nbsp;<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst childProcess = require(&#039;child_process&#039;); \n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\"><strong>Methods to Create Child Process<\/strong><\/h2>\n\n\n\n<p>Let&#8217;s now look at some of the methods that can be used to create child processes in NodeJs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. spawn()<\/strong><\/h3>\n\n\n\n<p>This method takes commands, arguments, and options to start a new process. The options can contain shell as a boolean value, and &#8220;true&#8221; runs the command inside the shell. By default, the value is false which will not execute the command on the shell, so it is important to pass the shell as true.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nspawn(command&#x5B;,arguments]&#x5B;,options])\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Here we are using the spawn method to create a child process that will execute the command pass as an argument. The result of this method is equivalent to the result that comes when passing the command mkdir new-folder in the shell.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst { spawn } = require(&#039;child_process&#039;);\nconst child = spawn(&#039;mkdir&#039;, &#x5B;&#039;new-folder&#039;], {shell: true});\n\nchild.stdout.on(&#039;data&#039;, (data) =&gt; {\n  console.log(`stdout: ${data}`);\n});\n  \nchild.stderr.on(&#039;data&#039;, (data) =&gt; {\n  console.error(`stderr: ${data}`);\n});\n\nchild.on(&#039;close&#039;, () =&gt; {\n  console.log(&#039;child process closed&#039;);\n});\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"258\" height=\"106\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/new-folder-created.png\" alt=\"New Folder Created\" class=\"wp-image-14180\"\/><figcaption class=\"wp-element-caption\">New Folder Created<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"749\" height=\"176\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/spawn-example-output.png\" alt=\"Spawn Example Output\" class=\"wp-image-14179\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/spawn-example-output.png 749w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/spawn-example-output-300x70.png 300w\" sizes=\"(max-width: 749px) 100vw, 749px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2. exec()<\/strong><\/h3>\n\n\n\n<p>This method takes a command, options, and a callback function in which we can write the code to log the error or success message.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nexec(command&#x5B;, options]&#x5B;, callback])\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Here we are executing the same command as the previous example by using the exec() method. We are passing the command and argument together instead of passing them separately like in the case of the spawn method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst { exec } = require(&#039;child_process&#039;);  \nexec(&#039;mkdir new-folder&#039;, (err) =&gt; {  \n  if (err) {  \n    console.error(err);  \n    return;  \n  }  \n  console.log(&quot;New folder Created&quot;);  \n}); \n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"949\" height=\"337\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/fork-example-output.png\" alt=\"Exec Example Output\" class=\"wp-image-14182\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/fork-example-output.png 949w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/fork-example-output-300x107.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/fork-example-output-768x273.png 768w\" sizes=\"(max-width: 949px) 100vw, 949px\" \/><figcaption class=\"wp-element-caption\">We already created a folder with the name <strong>new-folder<\/strong> using the spawn method so it returns an error.<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3. fork()<\/strong><\/h3>\n\n\n\n<p>This method is similar to spawn but it provides a way of communication between the parent and child process via the IPC&nbsp; communication channel by using the send method.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nfork(modulePath&#x5B;, args]&#x5B;, options])\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Here we have established a channel between the parent file parent.js and the child file child.js by using the fork module. Then send a message from child.js to parent.js to see that they are able to communicate, once received the message at both ends, we close the child process because it is no longer needed.<\/p>\n\n\n\n<p><strong>parent.js<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst { fork } = require(&#039;child_process&#039;);\n  \nconst child = fork(__dirname + &#039;\/child.js&#039;);\n  \nchild.on(&#039;message&#039;, function(message) {\n  console.log(&quot;Message from child: &quot; + message.msg);\n});\n  \nchild.send({ msg: &#039;This is parent process&#039; });\n  \n<\/pre><\/div>\n\n\n<p><strong>child.js<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nprocess.on(&#039;message&#039;, function(message) {\n    console.log(&quot;Message from parent: &quot; + message.msg);\n  });\n    \nprocess.send({ msg: &#039;This is child process&#039; });\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"784\" height=\"147\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/fork-example-output-1.png\" alt=\"Fork Example Output 1\" class=\"wp-image-14183\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/fork-example-output-1.png 784w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/fork-example-output-1-300x56.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/fork-example-output-1-768x144.png 768w\" sizes=\"(max-width: 784px) 100vw, 784px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Summary<\/strong><\/h2>\n\n\n\n<p>Child Process is helpful for running various processes simultaneously, this helps in utilizing multitasking functionality in Node.js since by default Node.js runs every process on a single thread. This is very useful when <a href=\"https:\/\/codeforgeek.com\/nodejs-installation-setup-and-hello-world-application\/\" data-type=\"post\" data-id=\"12795\">creating a large-scale Node.js Application<\/a> running many tasks at a time, without blocking the other part of the code. <\/p>\n\n\n\n<p>Child processes run independently from each other so does not interrupt other processes. There are various methods to start a child process providing different implementations and features. Hope this article helps you to understand the concept of the child process in Node.js.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Reference<\/strong><\/h2>\n\n\n\n<p><a href=\"https:\/\/nodejs.org\/api\/child_process.html#child-process\" target=\"_blank\" rel=\"noopener\">https:\/\/nodejs.org\/api\/child_process.html#child-process<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>NodeJs Child Process is used to create child processes that can run simultaneously proving a multicore functionality to a Node.js application. Node.js is a single-threaded, it can perform one operation at a time. This limits the scalability of a Node.js Application since we are not able to utilize the full power of the CPU. For [&hellip;]<\/p>\n","protected":false},"author":79,"featured_media":14178,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[14],"tags":[],"class_list":["post-14177","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-nodejs"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/Node.js-Child-Process-Thumbnail.png",1200,600,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/Node.js-Child-Process-Thumbnail-150x150.png",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/Node.js-Child-Process-Thumbnail-300x150.png",300,150,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/Node.js-Child-Process-Thumbnail-768x384.png",768,384,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/Node.js-Child-Process-Thumbnail-1024x512.png",1024,512,true],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/Node.js-Child-Process-Thumbnail.png",1200,600,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/10\/Node.js-Child-Process-Thumbnail.png",1200,600,false]},"uagb_author_info":{"display_name":"Aditya Gupta","author_link":"https:\/\/codeforgeek.com\/author\/aditya\/"},"uagb_comment_info":0,"uagb_excerpt":"NodeJs Child Process is used to create child processes that can run simultaneously proving a multicore functionality to a Node.js application. Node.js is a single-threaded, it can perform one operation at a time. This limits the scalability of a Node.js Application since we are not able to utilize the full power of the CPU. For&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/14177","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/79"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=14177"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/14177\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/14178"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=14177"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=14177"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=14177"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}