Is there a way I can make nodejs reload everytime it serves a page?
I want to do this during the dev cycle so I can avoid having to shutdown & startup on each code change?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Edit: Try nodules and their
require.reloadable()function.My former answer was about why not to reload the process of Node.js and does not really apply here. But I think it is still important, so I leave it here.
Node.js is evented IO and crafted specifically to avoid multiple threads or processes. The famous C10k problem asks how to serve 10 thousand clients simultaneously. This is where threads don’t work very well. Node.js can serve 10 thousand clients with only one thread. If you were to restart Node.js each time you would severely cripple Node.js.
What does evented IO mean?
To take your example: serving a page. Each time Node.js is about to serve a page, a callback is called by the event loop. The event loop is inherent to each Node.js application and starts running after initializations have completed. Node.js on the server-side works exactly like client-side Javascript in the browser. Whenever an event (mouse-click, timeout, etc.) happens, a callback – an event handler – is called.
And on the server side? Let’s have a look at a simple HTTP server (source code example taken from Node.js documentation)
This first loads the http module, then creates an HTTP server and tells it to invoke the inner function starting with
function (request, response)every time an HTTP request comes in, then makes the server listen to port 8124. This completes almost immediately so thatconsole.logwill be executed thereafter.Now Node.js event loop takes over. The application does not end but waits for requests. And voilà each request is answered with
Hello World\n.In a summary, don’t restart Node.js, but let its event loop decide when your code has to be run.