Node.js学习笔记
关于包
npm install
加上-g
参数可以全局安装,否则安装到当前目录下的node_module
里。
$ npm install -g <pkg_name>
全局和局部安装的区别:全局会注册PATH
变量但不能直接require
;局部能require
但不会注册PATH
。
用npm link <pkg_name>
可以将全局安装的包链接到本地的node_module
。
安装supervisor
包,以便随时加载被更改的源代码,方便开发调试。
$ sudo npm install -g supervisor
$ supervisor app.js
CommonJS对于包格式的规定:
package.json
放在包的顶层目录下- 二进制文件放在
bin
下 - JavaScript代码放在
lib
下 - 文档放在
doc
下 - 单元测试放在
test
下
Node.js寻找包的顺序:
- 检查
package.json
中的main
字段 - 如果不存在
main
,则寻找index.js
或index.node
CommonJS中对于package.json
的规范:
name
:包名称,不含空格的小写字母、数字和下划线组成description
:说明version
:符合语义化版本识别的版本字符串keywords
:关键字数组,用于搜索maintainers
:维护者数组,每个元素包含name
、email
(可选)、web
(可选)字段contributors
:贡献者数组,格式与maintainers
相同。包的作者应该是贡献者的第一位。bugs
:提交bug的地址,可以是网址或电子邮件licenses
:许可证数组,每个元素要包含type
(许可证名)和url
(连接到许可证文本的地址)。repositories
:仓库托管地址数组,每个元素要包含type
(仓库类型,如git
)、url
(仓库地址)和path
(相对于仓库的路径,可选)dependencies
:包的依赖,关联数组,由包名称和版本号组成
关于调试
调试:
$ node --debug[=port] script.js # 不暂停
$ node --debug-brk[=port] script.js # 执行第一条之前暂停
$ node debug 127.0.0.1:5858 # 连接远程调试器
$ node debug script.js # 直接调试本地文件
用node-inspector
调试:首先npm install -g node-inspector
,然后启动
`$ node-inspector`
最后连接http://127.0.0.1:8080/debug?port=5858
进行调试。
关于常用包
process
process.argv
:命令行数组,元素顺序为node
、脚本文件名、参数。
process.stdout
为标准输出流,process.stdout.write()
比console.log()
更底层。
proess.stdin
为标准输入流,默认暂停,需要先恢复:
process.stdin.resume();
process.stdin.on('data', function(data) {
process.stdout.write('read from console: ' + data.toString());
});
process.nextTick(callback)
用于拆分计算密集任务,例如
function doSomething(args, callback) {
somethingComplicated(args);
process.nextTick(callback);
}
doSomething(function onEnd() {
anotherThingComplicated();
});
console
console.log()
标准输出,console.error()
标准错误输出,console.trace()
输出调用栈。
util
util.inherits
原型继承,如
function Base() {} // define Base
Base.prototype.foo = function() {} // add method
function Sub() {} // define Sub
util.inherits(Sub, Base); // inherit from Base
util.inspect
检查对象内容,用于调试。格式:util.inspect(object, [showHidden], [depth], [colors])
。注意它不会调用对象的toString()
。
其他还有util.isArray()
、 util.isRegExp()
、 util.isDate()
、 util.isError()
、 util.format()
、 util.debug()
等工具。
events
events.EventEmitter
事件驱动。例如
var events = require('events');
var emitter = events.EventEmitter();
emitter.on('someEvent', function(arg1, arg2) {});
emitter.emit('someEvent', arg1, arg2);
其他方法有EventEmitter.once(event, listener)
(只触发一次)、 EventEmitter.removeListener(event, listener)
、 EventEmitter.removeAllListeners([event])
。