首先在PC上配置好Node.js的开发环境,然后新建文件,写入代码如下:
var http = require('http');
http.createServer(function (req, res){
res.writeHead(200,{'Content-Type' : 'text/html'});
res.write('<h1>Node.js</h1>');
res.end('<p>Hello World</p>');
}).listen(3000);
console.log("Http Server is listening at port: 3000");
这样一个简易的Web服务器就诞生了。
var http = require('http');
是用来获取一个模块,类似于在C++中的头文件。
http.createServer(function (req, res){
res.writeHead(200,{'Content-Type' : 'text/html'});
res.write('<h1>Node.js</h1>');
res.end('<p>Hello World</p>');
}).listen(3000);
这里则是注册了一个回调函数,跟Java中的注册回调函数使用匿名内部类那里很相像,Node采用的是事件驱动模型,里面的代码并不会被马上执行,而是等到http请求来触发这个事件,然后去调用这个回调函数。
回顾下整个程序,实际上当这段代码被执行完毕后,程序并不会退出,而是进入消息循环,等待消息的到来:
因为上述代码中,我们使用了listen这个函数,来监听3000端口。