Node.js教程
NodeJs入门 (2)
模块系统
在NodeJs中,系统之间通过模块引用,模块是一种组件模块,使用模块能够最大化松耦合,引用模块的方法如下:
var hello = require('./hello');
hello.world();
这是引用当前目录下的hello.js文件。其内容如下:
exports.world = function() {
console.log('Hello World');
}
其中exports是模块的一种通用标识写法,当模块被require 调用时,它就被作为类似引用指针一样返回,上面是传递给hello,因此可以直接通过hello调用其方法world(); 也可以如下写:
module.exports = function() {
// ...
}
这个将直接返回exports的函数。
如何使用require调用时,不使用相对路径呢?
var http = require('http');
这是引用一个核心模块http,但是如果引用的是非核心模块,如'mysql'如何呢?
var mysql = require('mysql');
NodeJS将沿着目录树,向每个上级目录查找node_modules,如果有这个目录,在里面寻找mysql.js的文件,如果搜索到root根目录没有,抛出错误。
事件机制
NodeJS使用一个叫EventEmitter的类实现观察者模式,你可以使用on()函数来监听事件,提供事件名称和回调函数:
var data = '';
req
.on('data', function(chunk) {
data += chunk;
})
.on('end', function() {
console.log('POST data: %s', data);
})
这里的'data'是表示监听request的数据,request的可监听事件可以在其http API找到。
下面我们使用事件编写一个客户端和服务器端来回对话的案例。客户端代码如下:
var http = require("http");
var req = http.get("http://localhost:8888/?x=fromclient", function(res) {
console.log("Got response: " + res.statusCode);
var data = '';
res.on('data', function (chunk) {
data += chunk;
}).on('end', function() {
console.log('Got data: %s', data);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
这是访问本地http://localhost:8888,有一个参数名为x,值为fromclient。服务器端代码如下:
var http = require("http");
var url = require('url');
function onRequest(request, response) {
console.log("Request received.");
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
response.writeHead(200, {"Content-Type": "text/plain"});
response.write( "hello world " + query.x);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
在这段代码中,我们使用url库提取客户端提交的参数,通过query.x直接得到参数值fromclient。
运行结果是,客户端输出如下结果,服务器端将参数发回客户端了:
Got response: 200
Got data: hello world fromclient
服务器端输出:
Server has started.
Request received.
调试NodeJS
使用console.log()和node debugger
node.js debug my_file.js
常用框架
express 能够分析提交Post的请求数据,如路由,配置,模板引擎,POST解析和许多其他功能。前面我们使用url,现在使用express如下:
var app = require('express').createServer();
app.get('/', function(req, res){
res.send('id: ' + req.query.id);
});
app.listen(3000);
这是使用express创建的服务器,获得参数的方式非常简单。req.params是检查路由参数如 /user/:id,(req.query)是检查?id=12这样的参数。大部分我们可以使用req.param('foo')来获得foo参数的值。
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
使用express之前需要安装 npm install express即可。