node.js学习笔记(一):基础

1.HelloWorld 
方法1,直接运行 
安装好node js后,在cmd命令窗口输入node. 
然后你可以直接输入:console.log('Hello World'); 

方法2,执行js 
或者把他写在一个helloworld.js里,cmd模式输入(注意看到$,不是nodejs命令,仅仅普通cmd命令): 
$ node helloworld.js 

你都能看到输出结果 

支持变量写法 
console.log('%s: %d', 'Hello', 25); 

另外直接作为字符串执行:$ node -e "console.log('Hello World');"

2.建立Http服务器

//app.js
1. var  http = require( 'http' );
2. http.createServer( function  (req, res)
3. {
4. res.writeHead(200, { 'Content-Type' 'text/html' });
5. res.write( '<h1>Node.js</h1>' );
6. res.end( '<p>Hello World</p>' );
7. }).listen(3000);
8. console.log( "HTTP server is listening at port 3000." );
接下来运行node app.js命令,打开浏览器访问 http://127.0.0.1:3000 

 

 

Node.js 只有在第一次引用到某部份时才会去解析脚本文件,以后都会直接访问内存,避免重复载入Node.js的这种设计虽然有利于提高性能,却不利于开发调试,因为我们在开发过程中总是希望修改后立即看到效果,而不是每次都要终止进程并重启。 
supervisor 可以帮助你实现这个功能,它会监视你对代码的改动,并自动重启Node.js。 
使用方法很简单,首先使用npm 安装supervisor: 
$ npm install -g supervisor 
接下来,使用supervisor 命令启动app.js: 
$ supervisor app.js
 

3.非阻塞单线程异步编程

让我们看看在Node.js 中如何用异步的方式读取一个文件,下面是一个例子: 
//readfile.js
01. var fs = require('fs');
02. fs.readFile('file.txt''utf-8'function (err, data)
03. {
04. if (err)
05. {
06. console.error(err);
07. else
08. {
09. console.log(data);
10. }
11. });
12. console.log('end.');
输出: 
end. 
Contents of the file. 

其中的function就是回调函数,不会阻塞等待的
1. var fs = require('fs'); 异步写法。当然这个读取文件也有同步写法,如下:
2. vardata = fs.readFileSync('file.txt''utf-8');
3. console.log(data);
4. console.log('end.');
输出: 
Contents of the file. 
end.
 

4.模块

模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个Node.js 文件就是一个模块,这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。 

1. 创建模块 
module.js
01. var name;
02. exports.setName = function (thyName)
03. {
04. name = thyName;
05. };
06. exports.sayHello = function ()
07. {
08. console.log('Hello ' + name);
09. };
在同一目录下创建getmodule.js,内容是: 
getmodule.js
1. var myModule = require('./module');
2. myModule.setName('BYVoid');
3. myModule.sayHello();
运行node getmodule.js,结果是: 
Hello BYVoid 

在以上示例中,module.js 通过 exports 对象把setName 和 sayHello 作为模块的访 
问接口,在getmodule.js 中通过 require('./module') 加载这个模块,然后就可以直接访 
问module.js 中 exports 对象的成员函数了。 

2.单例加载
1. varhello1 = require('./module');
2. hello1.setName('BYVoid');
3.  
4. var hello2 = require('./module');
5. hello2.setName('BYVoid 2');
6.  
7. hello1.sayHello();
运行后发现输出结果是 Hello BYVoid 2,这是因为变量 hello1 和 hello2 指向的是 
同一个实例,因此 hello1.setName 的结果被hello2.setName 覆盖,最终输出结果是 
由后者决定的。 

3.覆盖exports 
hello.js
01. function Hello()
02. {
03. var name;
04. this.setName = function (thyName)
05. {
06. name = thyName;
07. };
08. this.sayHello = function ()
09. {
10. console.log('Hello ' + name);
11. };
12. }
13. ;
14. module.exports = Hello;
这样就直接拿对象操作,不间接通过Module:
1. var Hello = require('./hello');
2. hello = new Hello();
3. hello.setName('BYVoid');
4. hello.sayHello();

5.包

包是一个目录,其中包含一个JSON 格式的包说明文件package.json。严格符合CommonJS 规范的包应该具备以下特征: 
 package.json 必须在包的顶层目录下; 
 二进制文件应该在bin 目录下; 
 JavaScript 代码应该在lib 目录下; 
 文档应该在doc 目录下; 
 单元测试应该在test 目录下。 

1.最简单的例子: 
somepackage/index.js
1. exports.hello = function() {
2. console.log('Hello.');
3. };
getpackage.js
1. varsomePackage = require('./somepackage');
2. somePackage.hello();
使用这种方法可以把文件夹封装为一个模块,即所谓的包。包通常是一些模块的集合,在模块的基础上提供了更高层的抽象,相当于提供了一些固定接口的函数库。通过定制package.json,我们可以创建更复杂、更完善、更符合规范的包用于发布。 

2.package.json 
在前面例子中的somepackage 文件夹下,我们创建一个叫做package.json 的文件,内容如下所示:
1. {
2. "main" "./lib/interface.js"
3. }
然后将index.js 重命名为interface.js 并放入lib 子文件夹下。以同样的方式再次调用这个 
包,依然可以正常使用。 
package.json 是CommonJS 规定的用来描述包的文件,完全符合规范的package.json 文件应该含有以下字段。 
 name:包的名称,必须是唯一的,由小写英文字母、数字和下划线组成,不能包含空格。 
 description:包的简要说明。 
 version:符合语义化版本识别①规范的版本字符串。 
 keywords:关键字数组,通常用于搜索。 
 maintainers:维护者数组,每个元素要包含 name、email (可选)、web (可选)字段。 
 contributors:贡献者数组,格式与maintainers相同。包的作者应该是贡献者数组的第一个元素。 
 bugs:提交bug的地址,可以是网址或者电子邮件地址。 
 licenses:许可证数组,每个元素要包含 type (许可证的名称)和 url (链接到许可证文本的地址)字段。 
 repositories:仓库托管地址数组,每个元素要包含 type  (仓库的类型,如 git )、url (仓库的地址)和 path (相对于仓库的路径,可选)字段。 
 dependencies:包的依赖,一个关联数组,由包名称和版本号组成。 

实例:
01. {
02. "name" "mypackage" ,
03. "description" "Sample package for CommonJS. This package demonstrates the required elements of a CommonJS package." ,
04. "version" "0.7.0" ,
05. "keywords" : [
06. "package" ,
07. "example"
08. ],
09. "maintainers" : [
10. {
11. "name" "Bill Smith" ,
12. "email" "[email protected]" ,
13. }
14. ],
15. "contributors" : [
16. {
17. "name" "BYVoid" ,
18. "web" "http://www.byvoid.com/"
19. }
20. ],
21. "bugs" : {
22. "mail" "[email protected]" ,
23. "web" "http://www.example.com/bugs"
24. },
25. "licenses" : [
26. {
27. "type" "GPLv2" ,
29. }
30. ],
31. "repositories" : [
32. {
33. "type" "git" ,
35. }
36. ],
37. "dependencies" : {
38. "webkit" "1.2" ,
39. "ssl" : {
40. "gnutls" : [ "1.0" "2.0" ],
41. "openssl" "0.9.8"
42. }
43. }
44. }

 

 

6.调试

Node.js 支持命令行下的单步调试。在命令行下执行node debug xxx.js,将会启动调试工具. 

Node.js 调试命令 
run  执行脚本,在第一行暂停 
restart  重新执行脚本 
cont, c  继续执行,直到遇到下一个断点 
next, n  单步执行 
step, s  单步执行并进入函数 
out, o  从函数中步出 
setBreakpoint(), sb()  在当前行设置断点 
setBreakpoint(‘f()’), sb(...)  在函数f的第一行设置断点 
setBreakpoint(‘script.js’, 20), sb(...)  在script.js 的第20行设置断点 
clearBreakpoint, cb(...)  清除所有断点 
backtrace, bt  显示当前的调用栈 
list(5)  显示当前执行到的前后5行代码 
watch(expr)  把表达式 expr 加入监视列表 
unwatch(expr)  把表达式 expr 从监视列表移除 
watchers  显示监视列表中所有的表达式和值 
repl  在当前上下文打开即时求值环境 
kill  终止当前执行的脚本 
scripts  显示当前已加载的所有脚本 
version  显示V8 的版本 


远程调试: 
node --debug[=port] xxx.js 

开发工具调试: 
如果开发工具支持,可以在开发工具调试,比如eclipse(我会尝试idea是否可行) 

使用node-inspector 调试Node.js: 
使用 npm install -g node-inspector 命令安装node-inspector,然后在终端中通过node --debug-brk=5858 xxx.js 命令连接你要除错的脚本的调试服务器 
启动node-inspector:$ node-inspector 

在浏览器中打开 http://127.0.0.1:8080/debug?port=5858,即可显示出优雅的Web 调试工具

猜你喜欢

转载自jorwen-fang.iteye.com/blog/2032193