I'm using nextJS with NodeJS and want to enable child processes or workers. The code provided by nextjs themselves works completely fine.
*The code provided by NextJS that I'm talking about: NextJS with NodeJS
*The other site I followed: NextJS with Express
server.listen(8080, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${8080}`);
});
I tried replacing the above code with this:
//if the cluster is master
if (cluster.isMaster) {
for (let i = 0; i < numCpu; i++) {
cluster.fork();
}
//if worker dies or is killed
cluster.on("exit", (worker, code, signal) => {
cluster.fork();
});
} else {
server.listen(8080, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${8080}`);
});
}
But it gives an error
info - Loaded env from C:\Users\Gp\Desktop\restro\.env
wait - compiling...
event - compiled client and server successfully in 535 ms (143 modules)
wait - compiling...
event - compiled client and server successfully in 502 ms (143 modules)
node:events:368
throw er; // Unhandled 'error' event
^
Error: EPERM: operation not permitted, open 'C:\Users\Gp\Desktop\restro\.next\trace'
Emitted 'error' event on WriteStream instance at:
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'C:\\Users\\Gp\\Desktop\\restro\\.next\\trace'
}
Simply the code looks like this
const express = require("express");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
server.all("*", (req, res) => {
return handle(req, res);
});
// server.listen(port, (err) => {
// if (err) throw err;
// console.log(`> Ready on http://localhost:${port}`);
// });
//if the cluster is master
if (cluster.isMaster) {
for (let i = 0; i < numCpu; i++) {
cluster.fork();
}
//if worker dies or is killed
cluster.on("exit", (worker, code, signal) => {
cluster.fork();
});
} else {
server.listen(8080, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${8080}`);
});
}
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});