Last active
December 21, 2021 03:31
-
-
Save myesn/599b0f04f94fc40f70f50ed2a11073a6 to your computer and use it in GitHub Desktop.
node.js 利用所有的 CPU 内核
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const os = require('os'); | |
const cluster = require('cluster'); | |
const app = express(); | |
const PORT = process.env.PORT || 5000; | |
const clusterWorkerSize = os.cpus().length; | |
if (clusterWorkerSize > 1) { | |
if (cluster.isMaster) { | |
for (let i = 0; i < clusterWorkerSize; i++) { | |
cluster.fork(); | |
} | |
cluster.on('exit', (worker, code, signal) => { | |
console.log('Worker', worker.id, ' has exitted.'); | |
}); | |
} else { | |
app.listen(PORT, () => { | |
console.log( | |
`Express server listening on port ${PORT} and worker ${process.pid}` | |
); | |
}); | |
} | |
} else { | |
app.listen(PORT, () => { | |
console.log( | |
`Express server listening on port ${PORT} with the single worker ${process.pid}` | |
); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment