Node JS返回主机名 [英] Node JS return hostname
问题描述
我还在学习Node JS和javascript,并有一个应用程序。我有一个配置文件,我需要在Ubuntu 12.04上获取服务器的主机名
I'm still learning Node JS and javascript and have an app. I have a configuration file where I need to grab the hostname of the server on Ubuntu 12.04
我试过类似的东西:
window.location.hostname
但是没有工作。示例代码如下:
But that did not work. Sample code below:
exports.config = {
app_name : [ window.location.hostname ]
}
如果我使用字符串,它将加载正常,但这将通过Github进行管理并且需要在应用加载时进行区分。
If I use a string, it will load fine, but this is going to be managed through Github and needs to be differentiated when the app loads.
推荐答案
根据到os模块的node.js文档,您需要加载os模块,该模块具有主机名( )
功能:
According to the node.js documentation for the "os" module you need to load the "os" module, which has a hostname()
function:
var os = require("os");
var hostname = os.hostname();
但是,这只是主机名 - 没有域名(FQDN)。没有简单的方法来获取FQDN。您可以使用 node.js DNS功能来尝试转换服务器的IP地址(你得到 os.networkInterfaces()
,参见上面的doc链接)到一个名字。唯一的问题是服务器可能有不同的接口和名称,因此您必须决定您想要哪一个。
However, that only is the hostname - without the domain name (the FQDN). There is no easy way to get the FQDN. You could use the node.js DNS functions to try to turn the IP address of the server (which you get with os.networkInterfaces()
, see doc link above) into a name. The only problem is servers may have different interfaces and names, so you have to make a decision about which one you want.
您尝试使用 window
object,但这只存在于浏览器的JavaScript运行时环境中。显然,服务器端JavaScript没有窗口,因此没有窗口
对象。 请参阅此问题:node.js是否具有相同的权限浏览器中的窗口对象。
You tried using the window
object, but that only exists in the JavaScript runtime environment of browsers. Server side JavaScript doesn't have windows, obviously, so there is no window
object. See this question: "Does node.js have equivalent to window object in browser".
使用此信息,您的问题有点奇怪 - 在浏览器中 window.location.hostname
是当前页面加载的URL的主机部分。你如何将其转换为服务器上下文?根据定义,您在node.js上运行的代码来自该服务器,因此您实际上并不需要此信息。您(可能)在浏览器中需要它,因为该信息是可变的,尤其是当您运行mashup(来自各种源的JS代码)时,您的代码可能不知道它运行的页面从何处加载。在服务器上,你总是知道它是你的本地文件系统。
With this information your question is a little strange - in the browser window.location.hostname
is the host part of the URL the current page was loaded from. How do you translate that to a server context? The code you run on node.js is from that very server, by definition, so you don't actually need this information. You (may) need it in the browser because that information is variable, especially when you run mashups (JS code from various sources) your code may not know where the page it runs on was loaded from. On the server you always know it's your local filesystem.
顺便说一句,你总是可以使用 localhost
作为主机名:)
By the way, you can always use localhost
as the hostname :)
这篇关于Node JS返回主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!