Node.js特性
-
Node.js库的异步和事件驱动的API全部都是异步就是非阻塞。它主要是指基于Node.js的服务器不会等待API返回的数据。服务器移动到下一个API调用,Node.js发生的事件通知机制后有助于服务器获得从之前的API调用的响应。
-
非常快的内置谷歌Chrome的V8 JavaScript引擎,Node.js库代码执行是非常快的。
-
单线程但高度可扩展 - Node.js使用具有循环事件单线程模型。事件机制有助于服务器在一个非阻塞的方式响应并使得服务器高度可扩展,而不是创建线程限制来处理请求的传统服务器。Node.js使用单线程的程序,但可以提供比传统的服务器(比如Apache HTTP服务器)的请求服务数量要大得多。
-
没有缓冲 - Node.js的应用从来不使用缓冲任何数据。这些应用只是输出数据在块中。
-
许可证协议 - Node.js 在MIT协议 下发布
在哪里可以使用Node.js?
以下是Node.js证明自己完美的技术的合作伙伴的领域。
-
I/O 绑定应用程序
-
数据流应用
-
数据密集型实时应用(DIRT)
-
JSON API的应用程序
-
单页面应用
1.3创建HelloWorld程序
Node.js应用程序由以下三个重要部分组成:
-
导入所需模块: 使用require指令来加载javascript模块
-
创建一个服务器: 服务器这将听监听在Apache HTTP服务器客户端的请求。
-
读取请求并返回响应: 在前面的步骤中创建的服务器将响应读取由客户机发出的HTTP请求(可以是一个浏览器或控制台)并返回响应。
步骤 1:导入所需的包
使用require指令来加载 HTTP 模块。
var http = require("http")
步骤 2:使用http.createServer方法创建HTTP服务器。通过参数函数请求并响应。编写示例实现返回“Hello World”。服务器在8081端口监听。
http.createServer(function (request, response) { // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // send the response body as "Hello World" response.end('Hello World\n'); }).listen(8081); // console will print the message console.log('Server running at http://127.0.0.1:8081/');
步骤 3: 创建一个 js 文件在 helloworld.js 在 D:\>yiibai_worksp.
File: helloworld.js
var http = require("http") http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World\n'); }).listen(8081); console.log('Server running at http://127.0.0.1:8081/');
现在运行 helloworld.js 看到结果:
D:\yiibai_worksp\nodejs>node helloworld.js
验证输出,服务器应用已经启动!
Server running at http://127.0.0.1:8081/