How NodeJS Works?

  Рет қаралды 77,490

Piyush Garg

Piyush Garg

Жыл бұрын

Hey Everyone, In this video, we will look at the working of nodejs. We'll see the event queue, the event loop, and how threads work in nodejs.
► Complete Full Stack Web Developer RoadMap 2023: • Complete Full Stack We...
► Master NodeJS Playlist: • Master NodeJS
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server side, creating server-side applications with JavaScript.
► My Website: www.piyushgarg.dev
My Gears
► My Girlfriend: amzn.to/3WD6FRp
► Apple MacBook Laptop: amzn.to/3WBJgQn
► Anker USB Hub: amzn.to/3GhZSr0
► Blue Yeti Microphone: amzn.to/3YKZ9FT
► External 27” Monitor: amzn.to/3Vp3xaO
► Logitech MK295 Wireless Keyboard and Mouse: amzn.to/3DuL1bB
► Seagate Expansion 1TB External HDD: amzn.to/3QMm5Q8
► Tripod: amzn.to/3S4OwK4
► Ring Light: amzn.to/3YLf8DR
Disclaimer: All the links above are affiliate links.
Social Links
► Twitter - / piyushgarg_dev
► LinkedIn - / piyushgarg195
Video Titles
How NodeJS Works?
What is an Event Loop in NodeJS?
Nodejs Architecture
Thread Pool in NodeJS
Event Queue in NodeJS
Tags
#nodejs #javascript #developer #javascriptinhindi #webdevelopment #webapp #realtimeapp #serverside #nonblockingio #tech

Пікірлер: 117
@AkshaySharma-bg3oj
@AkshaySharma-bg3oj 5 ай бұрын
I got this after some research, hope it helps. The statement "blocking threads are non-blocking" is not entirely accurate. It's important to make a distinction between the nature of the operation and the execution model: Nature of the operation: A blocking operation is one that suspends the execution of the current thread until it completes. This means that while the thread is waiting, it cannot execute any other code. Execution model: Node.js utilizes a single-threaded event loop with a pool of worker threads. The event loop is responsible for handling non-blocking I/O and scheduling tasks. Worker threads are used to execute blocking operations asynchronously. Therefore, while an individual operation might be blocking, the execution model in Node.js utilizes worker threads and the event loop to manage these blocking operations in a non-blocking manner. This allows the main thread to remain responsive and handle other tasks while the blocking operations are running in the background. Here's a more accurate way to express the concept: Node.js can handle blocking operations in a non-blocking way by utilizing worker threads and the event loop. This statement clarifies that the blocking nature of individual operations doesn't prevent Node.js from being a non-blocking environment overall. ------------------------------------------------------------------------------------ Yes, that's correct. Node.js internally decides whether a task will run on the main thread or a worker thread based on several factors, including: * **Nature of the operation:** Long-running and blocking operations are more likely to be assigned to worker threads, while short-lived and non-blocking tasks are typically handled by the main thread. * **Available resources:** Node.js considers the available CPU cores and memory when deciding whether to utilize worker threads. If resources are limited, it might prefer to run even blocking tasks on the main thread to avoid overhead. * **Application configuration:** Some libraries and frameworks might specify how certain tasks should be handled, influencing whether they run on the main thread or a worker thread. * **Node.js version and configuration:** Different versions of Node.js and specific configurations might have different heuristics for deciding when to use worker threads. Even for blocking operations like `fs.readFileSync`, Node.js might choose to execute them on the main thread if: * The operation is very fast and doesn't significantly block the main thread. * Utilizing a worker thread would introduce more overhead than simply waiting for the operation to finish on the main thread. * The application is running on a system with limited resources, and using a worker thread would be detrimental to performance. Ultimately, Node.js aims to optimize performance and resource utilization by intelligently allocating tasks between the main thread and worker threads. While developers can influence this behavior through libraries, frameworks, and application architecture, the final decision ultimately rests with the Node.js runtime based on its internal analysis.
@bm9code
@bm9code 2 ай бұрын
such deep info in simple terms; thank you
@kaustubh9605
@kaustubh9605 2 ай бұрын
@AkshaySharma-bg3oj great info, where did you found this? can you share any resources
@haseebsheikh6101
@haseebsheikh6101 2 ай бұрын
You explained very well and i hope it would also help others
@ashishsharma-uv5un
@ashishsharma-uv5un Ай бұрын
great , thanks for sharing
@Harsh-nv3xw
@Harsh-nv3xw Ай бұрын
Thanks for explaining things in very simple terms.
@umangkumar2005
@umangkumar2005 2 ай бұрын
Bro ,you are teaching wrong synchronous task of nodejs is only run in main thread , they dont utilize thread pool , thread pool is availble in libuv to do.........In Node.js, the thread pool is primarily available for handling certain types of asynchronous tasks, such as file system operations, network I/O, and cryptographic operations. It's important to note that the thread pool is not used for executing synchronous tasks; those tasks are executed on the main thread.
@crix_05
@crix_05 Ай бұрын
Blocking Requests: 1. When your code encounters a blocking request (like synchronously reading a large file), it goes directly onto the call stack. 2. The event loop prioritizes the call stack, and the blocking request is executed immediately. 3. The entire main thread of Node.js gets tied up waiting for the blocking operation to finish. 4. The event queue and any asynchronous tasks have to wait until the blocking request completes. Asynchronous Tasks and Callbacks: 1. When your code initiates an asynchronous operation (like reading a file asynchronously), the callback function representing that task is added directly to the event queue. 2. The callback function doesn't go on the call stack immediately because the asynchronous operation takes time to complete (e.g., waiting for the file to be read). 3. The event loop continues processing tasks on the call stack, focusing on synchronous tasks. 4. Only once the call stack is empty does the event loop check the event queue for waiting callbacks. 5. The event loop picks up the oldest callback from the queue (FIFO) and pushes it onto the call stack. 6. Now, the callback function gets its turn for execution on the call stack. I hope this would help...
@pabitrapradhan2428
@pabitrapradhan2428 Ай бұрын
I think you missed to mention one important concept about event demultiplexer. Event demultiplexer watches the I/O resources and once they are done with I/O task then it pushes set of events to the Event Queue and then the callbacks are executed and control comes back to the event queue. It goes in a cycle or loop which we called an event loop.
@Raw_Matter
@Raw_Matter 8 ай бұрын
Great sir... Really helped me to understand this whole working. Am a fresher and wanted to learn node.js.. literally feels like my elder brother is teaching.. thankyou so much sir
@zafariqbal92
@zafariqbal92 10 ай бұрын
Got a very good clarity. THANKS PIYUSH. Liked and Subscribed. Can we have more of these videos please, that should help in coding interviews!
@ronaksurve9168
@ronaksurve9168 9 күн бұрын
The synchronous tasks run on a single thread, because JS is a single-threaded language. The thread pool is used only for blocking operations that are CPU-intensive.
@Nothing-eg9ol
@Nothing-eg9ol 5 ай бұрын
Great Sir understood each line now i can also teach these topics to anyone😍
@weforyouweb1165
@weforyouweb1165 Жыл бұрын
Hello Piyush ji I want to ask one question that if node server is running with web socket server then at that time should there is any role of request of http blocking or non blocking?
@Solo_playz
@Solo_playz 2 ай бұрын
You and Telusko sir made it very easy to understand the architecture(how node js works) of node js in a very simplified way. Thank u piyush bhai
@sammykumar1777
@sammykumar1777 Жыл бұрын
One question,in file system lect you told we should use readSync i.e blocking function but here you told to use non blocking operation.pls ans
@codeshahar
@codeshahar 2 ай бұрын
Bro, amazing video with full clarity and increases curiosity to watch ur next videos, great work mate
@hack4one
@hack4one 5 ай бұрын
hi, i am confused now, i think non-blocking operations are handled by worker threads and blocking operations are handled by main thread. please clear it out.
@AnmolThakur-vv9lf
@AnmolThakur-vv9lf 4 ай бұрын
Understood everything very grateful for this amazing content.
@jagdishchoudhary7944
@jagdishchoudhary7944 5 ай бұрын
if sync function uses thread of cpu to perform the tasks, what async function uses to perform a task?
@l-_._-l
@l-_._-l 3 ай бұрын
user makes a request to server (green box node js) every request get queued in event queue event loop watches on event queue (fifo) the request can be of two types blocking/sync or non blocking/ async non blocking get resolved at the spot blocking operation goes to thread pool
@VarinderSingh-ec5ec
@VarinderSingh-ec5ec 2 ай бұрын
For Non-Blocking or Async code , how it will work behind the scenese like how it will let other code to execute first and then it will execute at the end ??
@ishikatiwari1238
@ishikatiwari1238 6 ай бұрын
Very well explained! Thanks!
@ashmikashandilya9544
@ashmikashandilya9544 6 ай бұрын
Amazing explanation Thank you so much
@kreevek
@kreevek Сағат бұрын
learned you are real teacher
@user-xy4ki6tm9v
@user-xy4ki6tm9v 2 ай бұрын
Wow sir I wish I would have got this playlist earlier Great Explaination 👏👏👏
@mitrajanumishra8071
@mitrajanumishra8071 11 ай бұрын
Great explanation bro but can you please make a video on how to fetch data quickly from mongo db with huge number of collection with aggregation and indexing
@user-jz1lx1rv1n
@user-jz1lx1rv1n Ай бұрын
Do we not require worker threads for non blocking as well?
@sandeepsolanki193
@sandeepsolanki193 Жыл бұрын
Beautiful explanation Easy understood Please react ki playlist bhi lekar aao..
@bulbergaming9142
@bulbergaming9142 4 ай бұрын
brother i think your statement is wrong.Asynchronous task is handled by thread pool while synchronous or blocking task is handled by the main thread.if i am wrong please i am open to your explanation
@AkshaySharma-bg3oj
@AkshaySharma-bg3oj 5 ай бұрын
thanks dude for the video. Just a sort of suggestion, I think you should not fear on explaining complex topics, thinking viewers if not get it might dislike that. I am confused now , node is single threaded. So how come a thread pool with so many threads. Secondly if it goes for a worker thread than it should be non blocking no? as each of the task has its own independent thread? @Piyush can you help here man. Or anyone?
@imNavneet_
@imNavneet_ 4 ай бұрын
in blocking opertion node use's C library which is libuv library using this it achives mutli threading and in node cluster module can achive same feature
@abhinavsharma7916
@abhinavsharma7916 2 ай бұрын
bro nodejs is synchronous architecture but it is asynchronous by default just sort it out in a way blocking request executes line by line but when it comes to non blocking operation it executes the operation like which was simple adn easy adn further move to the execution or loops part
@poojaganvir5631
@poojaganvir5631 4 ай бұрын
Great explanation. Thank you
@harleenkaur7751
@harleenkaur7751 7 ай бұрын
Thanks bhaiya, u really made it easy.
@ASD-mt4mf
@ASD-mt4mf 3 ай бұрын
if my cpu has 8 cores then it has 16 threads right? so why cant i use those 16 threads?
@sugrivlodhi2607
@sugrivlodhi2607 9 ай бұрын
Good explanations I love it Thanks bhaiya
@shubhamyadav-pf6bv
@shubhamyadav-pf6bv Ай бұрын
I think blocking (synchronous) code is executed by single main thread while non- blocking (async) code is delegated to thread from thread pool.
@Rohitsingh-zh6qx
@Rohitsingh-zh6qx 10 ай бұрын
hello sir please tell me how Will get to know this is block operation code or non blocking code
@aqeelsiddique3471
@aqeelsiddique3471 8 ай бұрын
very good and easy way explain , i like it thanku
@technologicalvivek7510
@technologicalvivek7510 3 ай бұрын
Bhaiya aap bahut sache padhate ho.Aapki voice bahut aachi hai ek dum polite.Aap dikhte bhi bahut smart ho.Thank you bhaiya for this amazing playlist ❤❤❤
@omkarporlikar6225
@omkarporlikar6225 2 ай бұрын
😂
@ashkshah4043
@ashkshah4043 Ай бұрын
Js is a single threaded so, how thread pool use 4 thread ?
@pushkargoyal4278
@pushkargoyal4278 10 ай бұрын
Just need to confirm Non blocking is asynchronous And blocking is synchronous
@8creators
@8creators 9 ай бұрын
Non blocking is asynchronous! And blocking is synchronous !
@lalitverma8634
@lalitverma8634 Жыл бұрын
Very good explanation ❤
@kunalkumar2717
@kunalkumar2717 4 ай бұрын
conclusion - it's always a good practice to write non blocking (asynchronous) code, meaning in which the there is no blocking of threads. we can only have workers equal the number of cores in our CPU in the thread pool.
@santoshmehla8504
@santoshmehla8504 2 ай бұрын
You are the one who explain the things in a way to make one comprehend easily.
@muhammadnomanamin6650
@muhammadnomanamin6650 5 ай бұрын
akheer kar diya.... bhout great Ma Sha Allah
@rajgaurav1127
@rajgaurav1127 2 ай бұрын
kya blocking ka mtlb async task or non-blocking ka mtlb sync task hota hai starting se aap yahi bol rhe the but last me aapne opposite kar diya
@8creators
@8creators 9 ай бұрын
Awesome lots of doubt clear !
@not_amanullah
@not_amanullah 2 ай бұрын
this series is helpful ❤
@Ganesh-fk4wc
@Ganesh-fk4wc 10 ай бұрын
Impressive!! The way of teaching is faboulous. Thanks for your effort . @piyush Garg
@RamrachaiMarma
@RamrachaiMarma 9 ай бұрын
Good explanation. Liked it.
@bm9code
@bm9code 8 ай бұрын
blocking will make use of threads to complete it task, synchronous are blocking code will stop the code there and do not allow execution to next line, then what is the point in having multiple threads when each blocking code do not allow other code to execute ("correct me if any wrong in my understanding")
@SonuKumar-uq2rb
@SonuKumar-uq2rb Жыл бұрын
very easy explaination ever great
@pubgshorts5660
@pubgshorts5660 2 ай бұрын
great Lecture sir😍
@user-wj1wd4uu9y
@user-wj1wd4uu9y 5 ай бұрын
Hey Piyush, I have a question if nodeJS is single-threaded then how thread pool have 4 threads by default and we can increase it by increasing the number of CPU cores. Can you please help me here, I am quite confused.
@omkarporlikar6225
@omkarporlikar6225 2 ай бұрын
Yeah That's true, It all depends on the capabilities of system OS / Core . If it is good the no of worker threads may increase or vice-versa. Also no of worker threads depends upon version of node js so there no thing as default. Also u can increase the no of workers manually although value depends of Capacity of core we are using
@harshitbhargav6288
@harshitbhargav6288 2 ай бұрын
Great... Nice explanation
@SanketGanorkar-lb3xn
@SanketGanorkar-lb3xn Ай бұрын
Nicely explained sir
@deependu__
@deependu__ 11 ай бұрын
is 'await' a blocking or non-blocking operation? What about 'then'?
@iampiyush100
@iampiyush100 11 ай бұрын
Now you question is: But if I am using await I need to wait until the response not coming So the answer is: Yes, that is correct. When using await, the code will wait for the asynchronous operation to complete before moving on to the next line of code. This means that if the response is not yet available, the code will wait until it is before continuing. However, this does not block the event loop, so other operations can still be processed while waiting for the response.
@varunupadhyay2488
@varunupadhyay2488 2 ай бұрын
Very good explanation
@mpkumar7786
@mpkumar7786 4 ай бұрын
Good explaination.
@kaushikkundu
@kaushikkundu 9 ай бұрын
Excellent video, this video will reach lakhs of views in future
@ShivendraPratap524
@ShivendraPratap524 Жыл бұрын
it means non-blocking operations are recommended to use ??
@piyushgargdev
@piyushgargdev Жыл бұрын
Yes!
@fardinkhan3620
@fardinkhan3620 3 ай бұрын
As I know non blocking operation that is asynchronous operation gandle by thread pool
@shubhamgupta-bl1tr
@shubhamgupta-bl1tr Жыл бұрын
One question.. blocking request run by thread, then who is running non blocking request .. please answer sir
@tarushchandra8993
@tarushchandra8993 Жыл бұрын
I'm having the same doubt but lets discuss our points here. So, as per my research, I think in both the cases requests are exceuted by the thread pool only, in the blocking requests (Sync) - only 1 thread is used to execute the operation and when it is done, then only 2nd request comes in. so it's like we're not using node.js to its fullest (working as a single threaded system), in the non blocking requests (Async) - all the requests gets parallelly exceuted, but still it will be limited to its max thread pool size (for example - 4 or 8 in Piyush's laptop) but here we have the advantage of nodeJS can work on the next task rather than gets stuck like in the case of blocking requests. (working as a multi-threaded system).
@piyushgargdev
@piyushgargdev Жыл бұрын
Node.js uses an event-driven, non-blocking I/O model which makes it well suited for handling concurrent connections and handling a high number of requests. When a request is received, the server creates an event and adds it to an event queue. The event loop then runs and processes the events in the queue one by one. This allows Node.js to handle many requests simultaneously without blocking the execution of other requests. Node.js also uses a callback function, which is executed once the request has been processed, to return the response to the client. The event loop is responsible for executing non-blocking requests in Node.js. The event loop is a mechanism that allows Node.js to perform non-blocking I/O operations. It works by continuously running and checking the event queue for new events to process. When a new request is received, it is added to the event queue in the form of an event. The event loop then picks up the event and starts executing it. Once the event has been processed, the callback function associated with the event is called, which sends the response back to the client. This entire process happens in a non-blocking manner, allowing Node.js to handle multiple requests simultaneously without blocking the execution of other requests.
@tarushchandra8993
@tarushchandra8993 Жыл бұрын
@@piyushgargdev Thank you Piyush for clarifying our doubt :)
@vaibhavsingh3617
@vaibhavsingh3617 10 ай бұрын
​​@@piyushgargdevbookish definition, good answer from @tarush
@prathameshkambli6991
@prathameshkambli6991 8 ай бұрын
Its done by thread pool
@SulavGhimireeee
@SulavGhimireeee 5 ай бұрын
Thanks Bro!
@mohdyasir5421
@mohdyasir5421 3 ай бұрын
Thank you
@coding8061
@coding8061 3 ай бұрын
Awesome ❤
@SonuKumar-uq2rb
@SonuKumar-uq2rb Жыл бұрын
wow great job bro .......
@not_amanullah
@not_amanullah 2 ай бұрын
thanks ❤
@amityadav-vu5he
@amityadav-vu5he 7 ай бұрын
Great🎉❤
@QuodeHub
@QuodeHub 8 ай бұрын
finally understood
@akshayagulhane3304
@akshayagulhane3304 2 ай бұрын
Node js is a single threaded..Then how it use multiple thread?
@bhushanambhore8378
@bhushanambhore8378 2 ай бұрын
Event loop is responsible to make it multithreaded
@shashankjangir1873
@shashankjangir1873 4 ай бұрын
great video
@VikasSharma-kc2oc
@VikasSharma-kc2oc Жыл бұрын
Nice
@user-ol1cp3pu8r
@user-ol1cp3pu8r 6 ай бұрын
we always says nodejs is single threaded, then how can have 4 threads?
@jaimintopiwala5824
@jaimintopiwala5824 6 ай бұрын
yes i have same question
@WithBhavnish
@WithBhavnish 10 ай бұрын
bro why are you so confused between non blocking and Blocking operations
@user-og2lt8ou8i
@user-og2lt8ou8i 5 ай бұрын
Who's?
@jibanjyotinayak9359
@jibanjyotinayak9359 2 ай бұрын
nyc specs...
@Whoisankit
@Whoisankit 5 ай бұрын
nice
@animeshtyagi
@animeshtyagi 4 ай бұрын
very important
@vishalrajput7926
@vishalrajput7926 Ай бұрын
blocking=== async Non-blocking=== sync
@Rajeev-Verma
@Rajeev-Verma 5 ай бұрын
Sorry, but i learnt that in Node.js, the blocking (synchronous) operations are handled by the main thread, while the non-blocking (asynchronous) operations are offloaded to the thread pool.
@shubhamyadav-pf6bv
@shubhamyadav-pf6bv Ай бұрын
You learnt right boy😅😅
@skillfulmind960
@skillfulmind960 8 ай бұрын
aweeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeesome
@anuragbezboruahb-4778
@anuragbezboruahb-4778 9 ай бұрын
Hello I'm the director of an ed-tech startup.... contact kaise karu aapko
@amankumar3639
@amankumar3639 2 ай бұрын
👍👍👍👍
@as_if
@as_if 4 ай бұрын
max threads = no. of cores of CPU
@vishalparmar2355
@vishalparmar2355 8 ай бұрын
Share ppt plz😢
@sumannaskar5736
@sumannaskar5736 3 ай бұрын
Best best best
@alindsharma8109
@alindsharma8109 4 ай бұрын
This explanation can only further confuse someone who understands even a little bit how Node.js works. A little bit misleading...
@bunnytheweebster
@bunnytheweebster 5 ай бұрын
vid-6 ✅
@AdityaAditya-il6ng
@AdityaAditya-il6ng Ай бұрын
i have 12 cpus
@a-onestudies1848
@a-onestudies1848 7 ай бұрын
Sorry to say bt wrong information
@santoshraut150
@santoshraut150 2 ай бұрын
Bro wrong video delete karke naya dalo yar varna fresher ka to lag jayega don't break the trust yaar
@bhaskarmehta6313
@bhaskarmehta6313 Ай бұрын
Its wrong explanation
@mayankjain7910
@mayankjain7910 Ай бұрын
Wrong content
@NeerajSharma1
@NeerajSharma1 7 ай бұрын
os.cpus().length returns undefined on my machine. Why is so ?
Building HTTP Server in NodeJS
17:56
Piyush Garg
Рет қаралды 69 М.
Yaml Tutorial | Learn YAML in 18 mins
18:05
TechWorld with Nana
Рет қаралды 606 М.
Did you find it?! 🤔✨✍️ #funnyart
00:11
Artistomg
Рет қаралды 116 МЛН
Маленькая и средняя фанта
00:56
Multi DO Smile Russian
Рет қаралды 4,3 МЛН
How to make MONEY with OPEN SOURCE?
7:30
Victoria Endless
Рет қаралды 15 М.
How NodeJS Works? - You don't Know NodeJS
42:52
Piyush Garg
Рет қаралды 39 М.
Git MERGE vs REBASE
16:12
Academind
Рет қаралды 1 МЛН
What is JWT? JSON Web Tokens Explained (Java Brains)
14:53
Java Brains
Рет қаралды 1 МЛН
How SSL Certificate Works?  - HTTPS Explained
20:42
Piyush Garg
Рет қаралды 139 М.
File Handling in NodeJS
18:17
Piyush Garg
Рет қаралды 59 М.
Did you find it?! 🤔✨✍️ #funnyart
00:11
Artistomg
Рет қаралды 116 МЛН