{"id":5413,"date":"2019-01-25T00:58:26","date_gmt":"2019-01-24T19:28:26","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=5413"},"modified":"2021-06-18T08:13:42","modified_gmt":"2021-06-18T02:43:42","slug":"getting-started-node-worker-thread","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/getting-started-node-worker-thread\/","title":{"rendered":"Getting Started With Worker Thread in NodeJS"},"content":{"rendered":"<p>NodeJS v11.7.0 is released and we have one of the most asked feature requests i.e threads. As we all know, Node provides the developer with a single-threaded system and internally uses threads to manage various I\/O calls which work great but when we do CPU intensive task then Node doesn&#8217;t perform up to mark.<\/p>\n<p>Well no more, with the release of the worker threads, we can use threads and write CPU intensive code in Node.<\/p>\n<p>Here is what the documentation of Node says about the worker threads:<\/p>\n<blockquote><p>Workers (threads) are useful for performing CPU-intensive JavaScript operations. They will not help much with I\/O-intensive work. Node.js\u2019s built-in asynchronous I\/O operations are more efficient than Workers can be.<\/p><\/blockquote>\n<p>Update your Node version to the latest and let&#8217;s get started with the code.<\/p>\n<p>Here is sample code to get started. <\/p>\n<div class='file_name'>workerthread.js<\/div>\n<p><code lang='javascript'><br \/>\nconst { Worker } = require('worker_threads')<\/p>\n<p>function runService(workerData) {<br \/>\n  return new Promise((resolve, reject) => {<br \/>\n    const worker = new Worker('.\/worker.js', { workerData });<br \/>\n    worker.on('message', resolve);<br \/>\n    worker.on('error', reject);<br \/>\n    worker.on('exit', (code) => {<br \/>\n      if (code !== 0)<br \/>\n        reject(new Error(`Worker stopped with exit code ${code}`));<br \/>\n    })<br \/>\n  })<br \/>\n}<\/p>\n<p>async function run() {<br \/>\n  const result = await runService('abc.js')<br \/>\n  console.log(result);<br \/>\n}<\/p>\n<p>run().catch(err => console.error(err))<br \/>\n<\/code><\/p>\n<p>Here is the worker.js:<\/p>\n<div class='file_name'>worker.js<\/div>\n<p><code lang='javascript'><br \/>\nconst { workerData, parentPort } = require('worker_threads')<\/p>\n<p>\/\/ You can do any heavy stuff here, in a synchronous way<br \/>\n\/\/ without blocking the \"main thread\"<\/p>\n<p>console.log('Going to write tons of content on file '+workerData);<br \/>\nparentPort.postMessage({ fileName: workerData, status: 'Done' })<br \/>\n<\/code><\/p>\n<p>Now run the code using the following command:<\/p>\n<p><code><br \/>\n$ node workerthread.js<br \/>\n<\/code><\/p>\n<p>Here is the output:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2019\/01\/Screenshot-2019-01-25-at-12.46.37-AM.png\" alt=\"Node worker thread\" width=\"1214\" height=\"603\" class=\"aligncenter size-full wp-image-5425\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2019\/01\/Screenshot-2019-01-25-at-12.46.37-AM.png 1214w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2019\/01\/Screenshot-2019-01-25-at-12.46.37-AM-300x149.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2019\/01\/Screenshot-2019-01-25-at-12.46.37-AM-768x381.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2019\/01\/Screenshot-2019-01-25-at-12.46.37-AM-1024x509.png 1024w\" sizes=\"(max-width: 1214px) 100vw, 1214px\" \/><\/p>\n<p>In worker, we send the workerData to the child process and get it back using the postMessage function.<\/p>\n<p>Well, that&#8217;s it. This is the simplest example to get started.<\/p>\n<p>For more information, visit the <strong><a href=\"https:\/\/nodejs.org\/api\/worker_threads.html#worker_threads_worker_threads\" rel=\"noopener\" target=\"_blank\">official<\/a><\/strong> documentation.<\/p>\n<h2>Conclusion<\/h2>\n<p>Personally, I think this is great to have a feature. Node is always criticized for its bad CPU intensive performance and with the help of web worker we can achieve the results and get the good part of threads without actually creating a deadlock and bottleneck situation in the code. <\/p>\n<p>I will develop a complete and real-world project soon with worker threads so stay tuned.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>NodeJS v11.7.0 is released and we have one of the most asked feature requests i.e threads. As we all know, Node provides the developer with a single-threaded system and internally uses threads to manage various I\/O calls which work great but when we do CPU intensive task then Node doesn&#8217;t perform up to mark. Well [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"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,16],"tags":[],"class_list":["post-5413","post","type-post","status-publish","format-standard","hentry","category-nodejs","category-short-tips"],"blocksy_meta":[],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Shahid","author_link":"https:\/\/codeforgeek.com\/author\/shahid\/"},"uagb_comment_info":0,"uagb_excerpt":"NodeJS v11.7.0 is released and we have one of the most asked feature requests i.e threads. As we all know, Node provides the developer with a single-threaded system and internally uses threads to manage various I\/O calls which work great but when we do CPU intensive task then Node doesn&#8217;t perform up to mark. Well&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/5413","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\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=5413"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/5413\/revisions"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=5413"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=5413"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=5413"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}