(1)下载nodejs
我这边下载的是“node-v0.12.7-linux-x64.tar.gz”这个版本
[root@localhost bin]# ./node -v
v0.12.7
/database/nodejs/workspace/helloworld
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '202.102.83.169'); console.log('Server running at http://202.102.83.169:1337/');
[root@localhost helloworld]# cat first.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '202.102.83.169');
console.log('Server running at http://202.102.83.169:1337/');
server.listen(port, [hostname], [backlog], [callback])#
Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).
里面说到如果忽略了hostname,那么服务器将会接受所有IPV4地址的链接,IPv4地址包括127.0.0.1 localhost和本地IP。没有认真看API,以后要注意。那么这样做就可以实现监听本地IP、localhost、127.0.0.1了:
1
2
3
4
5
|
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337);
|
[root@localhost bin]# ./node /database/nodejs/workspace/helloworld/first.js
Server running at http://127.0.0.1:1337/