初识node

来源:互联网 发布:linux 增加用户组 编辑:程序博客网 时间:2024/05/17 09:31

Node.js是以Google V8 JavaScript引擎为基础的服务器端技术,简单的说就是运行在服务端的JavaScript。它使用了一个事件驱动、非阻塞式 I/O 的模型,轻量又高效。

当然,学习node就要先安装node.js,网上的教程有很多。我们要确保本机上node和npm能正常运行。

第一个node程序

// load http modulevar http = require('http');// create http serverhttp.createServer(function(request, response) { // content headerresponse.writeHead(200, {    'content-type': 'text/plain'});// write message and signal communication is completeresponse.end("Hello World\n");}).listen(8124);console.log('Server running on 8124');

将代码保存为 helloworld.js ,运行如下命令来启动程序 :
node helloworld.js
运行命令

在浏览器中会看到一个显示有”Hello World”内容的页面
helloworld


分析

. var http = require('http);

node中的许多功能都是通过外部程序或库来提供,被我们称作模块(modules)。第一行中,我们通过require来载入http模块。HTTP模块能提供基本的HTTP功能,可以让应用程序支持对网络的访问。

. http.createServer(function(request,response){});

使用 createServer 方法创建一个新的服务器,并且传递一个匿名函数来作为该方法的参数。这个匿名函数就是 requestListener 函数,它通过两个参数来接收和响应数据,一个是代表服务器接收到的请求 ( http.ServerRequest ),另一个代表服务器的响应 ( http.ServerResponse )。

. response.writeHead(200, {    'content-type': 'text/plain'});

该方法用来发送相应信息的HTTP头, 指定HTTP状态码 ( status code ) 为200,内容类型为:text/plain。

. response.end("Hello World\n");

调用 http.ServerResponse.end 方法表示本次通信已经完成,并且 “Hello World”内容被放入到了响应信息中。该方法不可缺少。

. }).listen(8124);

匿名函数和 createServer 函数结束,listen方法指定端口监听。

. console.log('Server running on 8124');

终端打印信息,将文本信息输出到命令行。

总结

使用 node.js 时,我们不仅仅实现了一个应用,还实现了整个 HTTP 服务器。
让 js 运行在服务端,这真的很酷,希望自己的 node 之旅玩的很嗨 ^-^

原创粉丝点击