Node.js实现一个Web服务器太简单了,只需几行代码:
比如一个"Hello World"的Web程序,代码如下:// 载入http模块
var http = require('http');
// create http server
http.createServer(function (req, res) {
// content header
res.writeHead(200, {'content-type': 'text/plain'});
// write message and signal communication is complete
res.end("Hello, World!\n");
}).listen(8124);
console.log('Server running on 8124');复制代码其次,用Node.js读取服务器文件也非常简单,比如代码如下:var http = require('http');
var fs = require('fs');
http.createServer(function(req, res){
fs.readFile('greeter.js', 'utf-8', function(err, data){
res.writeHead(200, {'Content-Type': 'text/plain'});
if(err)
res.write('Could not find or open file for reading\n');
else
res.write(data);
res.end();
});
}).listen(8124, function(){
console.log('bound to port 8124');
});
console.log('Server running on 8124/');复制代码
|