一个简单的node.js的例子

        当应用程序需要处理大量并发的I/O,而在向客户端发出响应之前,应用程序内部并不需要进行非常复杂的处理的时候,Node.js非常适合。Node.js也非常适合与web socket配合,开发长连接的实时交互应用程序。

helloworld例子

编写一个js文件:

//require表示引包,引包就是引用自己的一个特殊功能
var http = require("http");
//创建服务器,参数是一个回调函数,表示如果有请求进来,要做什么
var server = http.createServer(function(req,res){
    //req表示请求,request;  res表示响应,response
    //设置HTTP头部,状态码是200,文件类型是html,字符集是utf8
    res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});
    res.end("hello,world!");
});

//运行服务器,监听3000端口(端口号可以任改)
server.listen(3000,"localhost");

启动Node.js服务器:

cd到helloworld.js所在的文件夹,运行:

$ node helloworld.js

浏览器访问:http://localhost:3000/

猜你喜欢

转载自blog.csdn.net/aganliang/article/details/88205084