这里使用Node.js实现一个最简单的Web服务器。
index.js
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('Hello Node.js\n');
}).listen(8080,"127.0.0.1");
console.log("Server start at http://127.0.0.1:8080");
上面的实例执行完了就退出了,这里为什么执行完了没有退出?原因在于活动的事件监听器。Node会始终启动一个事件循环,在这里.listen函数创建了一个实现HTTP协议的事件监听器。这个事件监听器会使index.js意志处于执行状态,直到终端执行退出操作,例如:Ctrl+C.