Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

javascript - Node JS return hostname

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

I tried something like:

 window.location.hostname

But that did not work. Sample code below:

exports.config = {
    app_name : [ window.location.hostname ]
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

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.

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".

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.

By the way, you can always use localhost as the hostname :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...