STDIO模块:Nodejs核心带有STDIO模块,所以不需要依赖任何的模块,在STDIO模块中,信息被记录到终端。
1)console.log():
只需要一行代码就可以实现:
console.log("test");
D:\nodejs\test>node app.js
test
Express server listening on port 3000
2)console.error():记录产生的错误,可以很清楚的记录错误所在。
function notDefined(){
try {
someFunction();
} catch (e) {
console.error(e);
}
}
notDefined();
D:\nodejs\test>node app.js
[ReferenceError: someFunction is not defined]
Express server listening on port 3000
3)console.time()与console.timeEnd()方法:探索代码的瓶颈所在或者想快速检测代码的某部分的性能:
var sum=0;
var arr=new Array(100000);
for(var i=0;i<arr.length;i++){
arr[i]=Math.random();
}
console.time("for-loop-1");
for(var i in arr){
sum+=arr[i];
}
console.timeEnd("for-loop-1");
console.time("for-loop-2");
for(var i=0;i<arr.length;i++){
sum+=arr[i];
}
console.timeEnd("for-loop-2");
输入结果如下:
D:\nodejs\test>node app.js
for-loop-1: 47ms
for-loop-2: 0ms
Express server listening on port 3000
4)console.trace():查看堆栈的位置内容。
5)断点调试:debugger
例子:
var foo = function(){
var a = 3, b = 5;
debugger;
var bar = function() {
var b = 7, c = 11;
a += b + c;
debugger;
}
bar ();
debugger;
};
foo();
前进到第一个节点:cont
进入repl模式:repl命令
然后查询内容:a,b,c等。
退出第一个节点:crl+c,进入下一个节点:cont
进入repl模式:repl
然后查看内容:a,b,c:
D:\nodejs\test>node debug app.js
< debugger listening on port 5858
connecting... ok
break in D:\nodejs\test\app.js:6
4 */
5
6 var express = require('express');
7 var routes = require('./routes');
8 var user = require('./routes/user');
debug> cont
break in D:\nodejs\test\app.js:40
38 var foo = function(){
39 var a = 3, b = 5;
40 debugger;
41 var bar = function() {
42 var b = 7, c = 11;
debug> a
ReferenceError: a is not defined
at repl:1:2
at Interface.controlEval (_debugger.js:969:21)
at Interface.<anonymous> (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.EventEmitter.emit (events.js:98:17)
at emitKey (readline.js:1095:12)
debug> repl
Press Ctrl + C to leave debug repl
> a
3
> b
5
> c
ReferenceError: c is not defined
> repl
ReferenceError: repl is not defined
> cont
ReferenceError: cont is not defined
debug> cont
break in D:\nodejs\test\app.js:44
42 var b = 7, c = 11;
43 a += b + c;
44 debugger;
45 }
46 bar ();
debug> repl
Press Ctrl + C to leave debug repl
> a
21
> b
7
> c
11
> d
ReferenceError: d is not defined
debug> cont
break in D:\nodejs\test\app.js:47
45 }
46 bar ();
47 debugger;
48 };
49 foo();
debug> repl
Press Ctrl + C to leave debug repl
> a
21
> b
5
> c
ReferenceError: c is not defined
>