Reputation: 8563
I am having a route
app.get('/posts', function (req, res) {
res.json([
// data
]);
// what would happen to the code below
// Suppose it is processing a million records
processMillionRecords();
});
function processMillionRecords () {
// process million records
}
Once the response is sent, another function is called which is quite an expensive operation. What would happen if this continues? Are there any implications?
I know the ideal way of doing it is using background processes. So I replaced it with the below.
res.json([
// data
]);
var child = require('child_process');
child.fork('worker.js');
// worker.js
function processMillionRecords () {
// process million records
}
Which one is more preferred and in which cases?
Upvotes: 2
Views: 204
Reputation: 33864
What will happen in the situation described above (as mentioned by Timothy), is this:
If you're building an app that is expecting a lot of traffic, or a lot of CPU intensive workload, it's best to move this stuff into a separate server specifically meant for processing long-running tasks. This reduces the chance that:
Hope that helps.
Upvotes: 0
Reputation: 23070
Node is built to handle long asynchronous operations. Unless it's very CPU heavy, you probably don't need to fork a new worker process. Just write your processMillionRecords to be async and make sure it doesn't block the event loop.
Upvotes: 2