Node contains a full fledged API to perform timing and interval related operations. Out of those, 2 functions are very familiar to the client-side JS that we use in browsers:
1) setTimeout(function, time) - calls function after the time has elapsed
2) setInterval(function, time) - calls function after every time milliseconds
process.nextTick
There is one additional function that is exclusive to Node on the server side - process.nextTick. As we know that Node keeps pushing callbacks of the function in the event queue and the executes them in a queue one after the other, until the queue is empty. This is the concept of the event loop, and one round of execution is called a tick.
What process.nextTick does is, it defers the execution of the function passed as parameter, to the end of the current tick. Which enables us, to do some tasks that are intensive, after the critical processing is completed, like logging a file, but before that, ending the response stream so that the client can receive the response.
As an example, if you need to remove a temporary file you created, but perhaps you don’t need to do
it before replying to the client, you can defer it like this:
stream.on("data", function(data) {
stream.end("my response");
process.nextTick(function() {
fs.unlink("/path/to/file");
});
});
1) setTimeout(function, time) - calls function after the time has elapsed
2) setInterval(function, time) - calls function after every time milliseconds
process.nextTick
There is one additional function that is exclusive to Node on the server side - process.nextTick. As we know that Node keeps pushing callbacks of the function in the event queue and the executes them in a queue one after the other, until the queue is empty. This is the concept of the event loop, and one round of execution is called a tick.
What process.nextTick does is, it defers the execution of the function passed as parameter, to the end of the current tick. Which enables us, to do some tasks that are intensive, after the critical processing is completed, like logging a file, but before that, ending the response stream so that the client can receive the response.
As an example, if you need to remove a temporary file you created, but perhaps you don’t need to do
it before replying to the client, you can defer it like this:
stream.on("data", function(data) {
stream.end("my response");
process.nextTick(function() {
fs.unlink("/path/to/file");
});
});
No comments:
Post a Comment