Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js server.listen callback?

Tags:

node.js

I have a node.js application and I need to run a command once the server starts listening. The docs on server.listen say:
server.listen(port, [hostname], [backlog], [callback])
but when I try to use this format, the code is not run, but no error messages are appearing. Here is the listening part of my application:

var spawn = require('child_process').spawn
function listen(port) {
    try {
        server.listen(port, "localhost",511, function() {
          spawn("open",["http://localhost:"+port+"/"])
        })
    } catch (e) {
        listen(port+1)
    }
}



Some of you requested to see the entirety of my code, so here it is:
var http = require("http"),
    path = require("path"),
    fs = require("fs"),
    mime = require("mime"),
    port = 1
var server = http.createServer(function(req, resp) {
    if (req.url == "/action" && req.headers["command"]) {
        resp.writeHead(200, {
            "Content-Type": "text/plain"
        });
        console.log("Command sent: " + req.headers["command"])
        try {
            var out = eval(req.headers["command"])
            if (typeof out == "object") {
                var cache = [];
                out = JSON.stringify(out, function(key, value) {
                    if (typeof value === 'object' && value !== null) {
                        if (cache.indexOf(value) !== -1) {
                            return "[Circular]";
                        }
                        // Store value in our collection
                        cache.push(value);
                    }
                    return value;
                });
            }
            resp.end(out);
        } catch (e) {
            resp.end(e.stack)
        }
    }
    var local = __dirname + "/public" + req.url
    if (fs.existsSync(local)) {
        if (fs.lstatSync(local).isDirectory(local)) {
            if (fs.existsSync(local + "/index.html")) {
                local += "/index.html"
                resp.writeHead(200, {
                    "Content-Type": mime.lookup(local)
                });
                fs.readFile(local, function(err, data) {
                    if (err) {
                        resp.writeHead(500, {
                            "Content-Type": "text/plain"
                        });
                        resp.end("Internal server error");
                        throw err;
                    }
                    resp.end(data)
                });
            } else {
                server.status_code = 403
                resp.writeHead(403, {
                    "Content-Type": "text/plain"
                });
                resp.end("GET 403 " + http.STATUS_CODES[403] + " " + req.url + "\nThat Directory has no Index")
                console.log("GET 403 " + http.STATUS_CODES[403] + " " + req.url)
            }
        } else {
            resp.writeHead(200, {
                "Content-Type": mime.lookup(local)
            });
            fs.readFile(local, function(err, data) {
                if (err) {
                    resp.writeHead(500, {
                        "Content-Type": "text/plain"
                    });
                    resp.end("Internal server error");
                    throw err;
                }
                resp.end(data)
            });
        }
    } else {
        if (req.url != "/action") {
            server.status_code = 404
            resp.writeHead(404, {
                "Content-Type": "text/plain"
            });
            resp.end("GET 404 " + http.STATUS_CODES[404] + " " + req.url + "\nThat File Cannot be found")
            console.log("GET 404 " + http.STATUS_CODES[404] + " " + req.url)
        }
    }
});
var spawn = require('child_process').spawn
function listen(port) {
    try {
        server.listen(port, "localhost")
    } catch (e) {
        listen(port+1)
    }
}

Solved!

After combining the answers of both @mscdex and Peter Lyons I have solved the problem.

var spawn = require('child_process').spawn
server.listen(0,"localhost", function(err) {
    if(err) throw err;
    spawn("open",["http://localhost:"+server.address().port+"/"])

})

Thank you to both of you

like image 617
bren Avatar asked Jul 08 '14 01:07

bren


People also ask

What is server listen () in node JS?

The server. listen() method creates a listener on the specified port or path.

How do I call a callback function in node JS?

For example: In Node. js, when a function start reading file, it returns the control to execution environment immediately so that the next instruction can be executed. Once file I/O gets completed, callback function will get called to avoid blocking or wait for File I/O.

How do you send a response from server to client in node JS?

Methods to send response from server to client are:Using send() function. Using json() function.


1 Answers

var spawn = require('child_process').spawn

function listen(port) {
  //Don't need try/catch here as this is an asynchronous call
  server.listen(port, "localhost", function(error) {
    if (error) {
      console.error("Unable to listen on port", port, error);
      listen(port + 1);
      return;
    }
    spawn("open",["http://localhost:"+port+"/"])
}
  • Not sure what docs you are reading, but the official node.js docs for server.listen say server.listen(port, [host], [callback]).
  • You don't need try/catch because this is an asynchronous call that will indicate errors via the callback's first argument.
like image 111
Peter Lyons Avatar answered Sep 23 '22 12:09

Peter Lyons