Unit: createServer in nodejs seems to return undefined

Created on 23 Mar 2020  Â·  4Comments  Â·  Source: nginx/unit

I'm trying to use unit with an express app and seem to be running into two problems that may be related.

app.listen() should return the server instance
createServer(app).listen() should also return a server instance

Both seem to return undefined when using unit-http.

bug

All 4 comments

Hello,
Unit implementation of listen() does nothing and the purpose of this method only compatibility. It is relatively easy to make it to return server instance. Please try this patch:

diff --git a/src/nodejs/unit-http/http_server.js b/src/nodejs/unit-http/http_server.js
--- a/src/nodejs/unit-http/http_server.js
+++ b/src/nodejs/unit-http/http_server.js
@@ -453,6 +453,8 @@ Server.prototype.setTimeout = function s

 Server.prototype.listen = function () {
     this.unit.listen();
+
+    return this;
 };

 Server.prototype.emit_request = function (req, res) {

Thanks! That would be perfect for compatibility.

Since the method does nothing do the events still fire? For example server.on('listening', ... etc?

.. do the events still fire?

No. Socket is opened by Unit and application only process request events.

Following patch enables listening event fire:

diff --git a/src/nodejs/unit-http/http_server.js b/src/nodejs/unit-http/http_server.js
--- a/src/nodejs/unit-http/http_server.js
+++ b/src/nodejs/unit-http/http_server.js
@@ -451,8 +451,21 @@ Server.prototype.setTimeout = function s
     return this;
 };

-Server.prototype.listen = function () {
+Server.prototype.listen = function (...args) {
     this.unit.listen();
+
+    var cb = null;
+    if (args.length > 0) {
+        cb = args[args.length - 1];
+    }
+
+    if (cb !== null && typeof cb === 'function') {
+        this.once('listening', cb);
+    }
+
+    this.emit('listening');
+
+    return this;
 };

 Server.prototype.emit_request = function (req, res) {

That's excellent. Thanks so much.

I feel these need to go into Unit ASAP for compatibility with existing Express applications. There are a few apps I've tried to use that minimally listen to connection and listening with some boilerplate mostly going into listening

Was this page helpful?
0 / 5 - 0 ratings