nodejs学习笔记

常用命令: cd //进入文件 node hello.js //调用hello.js node -e "consloe.log('hello,node");" //输出hello,node node //进入REPL模式 > ctrl + c //两次退出REPL模式 创建http服务器 [php] var http = require('http'); http.createServer(function(req,res){ res.writeHead(200,{'Content_Type':'text/xml'}); res.write('<h1>Node.js</h1>'); res.end('<p>Hello World</p>'); }).listen(3000); console.log('HTTP server is listenging at port 3000'); [/php] 小技巧:使用supervisor方便开发调试 node.js异步读取文件 [php] var fs = require('fs'); fs.redaFile('file.txt','utf-8',function(err,data){ if(err){ console.error(err); }else{ console.log(data); } }); console.log('end.'); [/php] //输出为: end. Contents of the file. node.js同步读取文件API [php] var fs = require('fs'); var data = fs.readFileSync('file.txt','UTF-8'); console.log(date); console.log('end.'); [/php] //输出为: Contents of the file. end. EventEMitter node.js 中没有显示的循环,node.js 中的循环对开发者不可见,由libev实现 模块和包 #创建模块 node.js为模块提供了两个对象。exports和require,其中exports是模块的公开借口,require用于从外部获取一个模块的接口,即获取模块的exports对象 [php] //module.js var name; exports.setName = function(thyName){ name=thyName; }; exports.sayHello = function(){ console.log('hello '+name); } //getModule.js var myModule = require('./module'); myModule.setName('HUSTecho'); myModule.sayHello(); [/php] require不会重复加载模块,无论多少次调用模块,获得都是同一个 面向对象覆盖exports [php] //singleobject.js function Hello(){ var name; this.setName = function(thyName){ name = thyName; }; this.sayHello = function(){ console.log('Hello '+name); } module.exports = Hello; } //gethello.js var Hello = require('./hello'); hello = new Hello(); hello.setName('HUSTecho'); hello.sayHello(); [/php] exports 本身仅仅是一个普通的空对象{},它专门用声明接口,本质上是通过它为模块闭包的内部建立了一个有限的访问接口 #创建包 严格符合CommonJS规范的包具备以下特征: 1.package.json必须在包的顶层目录下 2.二进制文件应该在bin目录下 3.javascript代码应该在lib目录下 4.文档应该在doc目录下 5.单元测试应该在test目录下 node.js在调用某个包时,会首先检查包的package.json文件的main字段,将其作为包的接口模块,如果package.json或main字段不存在,会尝试寻找index.js或index.node作为包的接口。 使用全局模式安装的包不能再javascript中用require获得,但可以自动注册path变量。而本地模式安装的包可以通过require获得,但没有注册path变量 所以,当我们要把某个包作为工程运行的一部分时,通过本地模式获取,在命令行下使用,则使用全局模式安装。 nodejs bug 调试 node debug debug.js node --debug=port debug.js node --debug 127.0.0.1:5858 #nodejs 全局变量 ##在nodejs中你不可能最外层定义变量,因为所有变量都是属于当前模块的,而模块本身不是最外层上下文 ##process ###process.argv是命令行参数数组 ###process.stdout是标准输出流 ###process.stdin是标准输入流,初始时它是被暂停的,回复流代码如下: process.stdin.resume(); process.stdin.on('data',function(data){ process.stdout.write('read from console:'+data.toString()); }) ###process.nextTick(callback)是为时间设置一项任务,nodejs会在下次时间循环响应时调用callback ##常用工具util ###util.inherits实现对象间原型继承的函数,用法如下: [php] var util = require('util'); function Base(){ this.name='name'; this.base='1992'; this.sayHello = function(){ console.log('Hello '+this.name); }; } Base.prototype.showName = function(){ console.log(this.name); }; function Sub(){ this.name='sub'; }; util.inhreits(Sub,Base); var objBase = new Base(); objBase.showName(); objBase.sayHello(); console.log(objBase); var objSub = new Sub(); objSub.showName(); console.log(objSub); [/php] ###util.inspector util.inspect(object,[showHidden],[depth],[colors])是一个将人以对象转换为字符串的方法,通常用于调试和错误输出。 ##事件驱动events ###事件发生器events.eventEmitter();常用API如下: eventsEmitter.on/emit/once/removeListener/removeAllListener ###error事件 当error被发射时,EventEmitter()规定如果相应的监听器,node.js会把它当做异常,退出程序并打印调用栈 ##文件系统fs ###fs.readFIle(filename,[encoding],[callback(err,data)]) [php] var fs = require('fs'); fs.readFile('content.txt','utf-8',function(err,data){ if(err){ console.error(err); }else{ console.log(data); } }) [/php] ###fs.redaFileSync同上 ###fs.open(path,flags,[mode],callback(err,fd))--fd为文件描述符,是一个非负整数,表示操作系统内核为当前进程所维护的打开文件的记录表索引 ###fs.read(fd,buffer,offset,length,position,[callback(err,bytesRead,buffer)]) 一般来说,除非必要,否则不要使用这种方式读取文件,因为它要求你手动管理缓冲区和文件指针,尤其是在你不知道文件大小的时候,这将会是一件很麻烦的事 ##http服务器与客户端 ###http.Server 继承自EventEmitter,提供一下几个事件: request/connection/close ###http.ServerRequest http请求一般可以分为两部分:请求头和请求体,请求头一般较短,请求体可能相对较长,需要一定的传输时间,因此http.ServerRequest提供了三个事件用于控制请求体传输: data/end/close ###获取GET请求 Node.js的url模块中的parse包含了这个功能,如下所示: [php] var http = require('http'); var url = require('url'); var util = require('util'); http.createServer(function(req,res){ res.whiteHead(200,{'Content-Type':'text/plain'}); res.end(util.inspect(url.parse(req.url,true))) }).listen(3000); [/php] ###获取POST请求内容 因为等待请求体传输可能是一件耗时的工作,所以node.js默认是不会解析请求体的,需要的时候必须手动来做,代码如下: [php] var http = require('http'); var querystring = require('querystring'); var util = require('util'); http.createServer(function(req,res){ var post=''; req.on('data',function(chunk){ post += chunk; }); req.on('end',function(){ post = querystring.prase(post); res.end(util,inspect(post)) }); }).listen(3000); [/php] ###http.ServerResponse 它是由http.Server的request事件发送的,通常作为第二个参数传递,一般简写做response或res。有三个重要的成员函数,用于返回响应头、响应内容以及结束请求。 response.writeHead(statusCode,[headers]) response.write(data,[encoding]) response.end([data],[encoding]) ##http客户端 ###http.request(option,callback) option常用的参数如下: host/port/method/path/headers ###http.get(option,callback) http.ClientRequest/http.ClientResponse 看nodejs开发指南的笔记,记得比较乱,都是书上的东西,就不继续整理了。
posted @ 2013-04-30 00:00  echoHUST  阅读(230)  评论(0编辑  收藏  举报