准备写一个小小的Web服务器。幸运的是,Node让这一切变得易如反掌。
首先在项目目录下新建一个名为web.js的文件,在编译器中打开该文件,代码如下:
// 引入http模块
var http = require('http')
function process_request(req, res){
var body = 'Thanks for calling!\n';
var content_length = body.length;
res.writeHead(200,{
'Conten-Length' : content_length,
'Conten-Type' : 'text/plain'
});
res.end(body);
}
console.log("程序正在运行……")
var port = http.createServer(process_request);
port.listen(8080);
编写代码完毕后,在doc窗口下进入到项目目录(有Git可以在项目目录直接右键),输入代码如下:
node web.js
控制台会显示: 程序运行中……
在浏览器输入:
http://localhost:8080
则会响应:Thanks for calling!