Node.js server.listen 回调?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24622267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js server.listen callback?
提问by MayorMonty
I have a node.js application and I need to run a command once the server starts listening. The docs on server.listensay: 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:
我有一个 node.js 应用程序,一旦服务器开始侦听,我需要运行一个命令。文档server.listen说:server.listen(port, [hostname], [backlog], [callback])
但是当我尝试使用这种格式时,代码没有运行,但没有出现错误消息。这是我的应用程序的听力部分:
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)
}
}
你们中的一些人要求查看我的完整代码,所以这里是:
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.
在结合@mscdex 和 Peter Lyons 的答案后,我解决了这个问题。
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
谢谢你们俩
采纳答案by Peter Lyons
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.listensayserver.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.
- 不确定您正在阅读哪些文档,但是官方的 node.js 文档是
server.listensayserver.listen(port, [host], [callback])。 - 您不需要 try/catch 因为这是一个异步调用,它将通过回调的第一个参数指示错误。

