Skip to content

Commit 21fcebf

Browse files
committed
Support PM2 multi-instance forks
1 parent 4bbd584 commit 21fcebf

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

server.js

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ if (process.env.NODE_ENV === 'test') {
8989
* @see https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html
9090
*/
9191
function initServer(handler, port) {
92-
return http.createServer(function(req, res) {
92+
const server = http.createServer(function(req, res) {
9393
let body = '';
9494

9595
req.on('data', function(data) {
@@ -167,9 +167,22 @@ function initServer(handler, port) {
167167
this.emit('error', Error('Malformed handler method. Exiting..'));
168168
}
169169
});
170-
}).listen(port, () => {
171-
console.log(`HTTP server started. Listening on port ${port}`);
172170
});
171+
172+
// Start HTTP server; increment port in use.
173+
return server
174+
.listen(port, () => {
175+
console.log(`HTTP server started. Listening on port ${port}`);
176+
})
177+
.on('error', function(err) {
178+
if (err.code === 'EADDRINUSE') {
179+
this.close();
180+
181+
console.warn(`Port ${port} in use. Trying another port.`);
182+
183+
initServer(handler, port + 1);
184+
}
185+
});
173186
}
174187

175188
/**

0 commit comments

Comments
 (0)