Node.js官網上常常掛著Node.js的Simplest Web Server Demo
這邊把它修改一下,頁面加上顯示IP資訊
方便做為雲端多主機部署程式時檢查之用
var http = require('http');
var os = require('os');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('My Address: '+JSON.stringify(os.networkInterfaces().net0[0].address));
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');
連線時,只要瀏覽器列打上 http://your_ip_address:1337
就可以看到如下圖的資訊
其中network interface的顯示依平台與設定而不同,在Mac上顯示資訊如下:
{ lo0:
[ { address: 'fe80::1', family: 'IPv6', internal: true },
{ address: '127.0.0.1', family: 'IPv4', internal: true },
{ address: '::1', family: 'IPv6', internal: true } ],
en0:
[ { address: 'fe80::1240:f3ff:fe8b:a9bc',
family: 'IPv6',
internal: false },
{ address: '192.168.1.106', family: 'IPv4', internal: false } ] }
而筆者的另一個平台顯示如下:
[root@simon001 ~/TestPrj]# node
> var os = require('os');
> os.networkInterfaces()
{ lo0:
[ { address: '127.0.0.1',
family: 'IPv4',
internal: true },
{ address: '::1',
family: 'IPv6',
internal: true } ],
net0:
[ { address: '211.78.255.31',
family: 'IPv4',
internal: false } ] }
因此,如果要實作不同平台的程式,可要注意這些差異喲∼