独书先生 Menu

Node.js学习笔记(2)–Nodejs console (控制台)总结简单示例

方法 描述
log 打印日志,支持格式符号%d,%s,%j,%
info 打印提示信息
error 打印错误信息
warn 打印警告信息
dir 打印对象的方法和属性。
time 计时器,和timeEnd成对使用,计算时间区间。
timeEnd 计时器,和time成对使用,计算时间区间。
trace 跟踪函数的执行过程,一般放在函数内部使用。
assert 断言。语法:console.assert(表达式,错误信息)

JS:

 

//console用法示例
//直接打印
console.log('print log');

//格式化打印
console.log('%d %d',1,2);

//格式化打印,格式不同,类型变化,输出结果
console.log('%d %d',1,'string');

//格式化打印,参数过多,多余参数直接按照空格隔开,然后输出
console.log('print %d %d yo',1,2,3,'string');

//格式化打印,遇到%s ,则返回对应参数的toString()值
console.log('%s',{name:'name'});
console.log({name:'name'}.toString());

//将参数按照json格式输出
console.log('%j',{name:'name'});

//百分号格式符
console.log('%',1);

//不同级别的打印输出,warn和error需要验证,输出乱序,但会早于info
console.info('print info');
console.warn('print warn');
console.error('print error');

//dir,打印对象的属性,如果遇到方法,不会打印方法体
var obj = {
    n1:1,
    n2:'string',
    n3:{
        n4:1,
        f:function () {
            console.log('function');
        },
        o:{}
    }
};
console.dir(obj);

//trace,跟踪方法
function f1() {
    console.log('f1');
}
function f2() {
    console.trace();
    f1();
}
f2();

//time和timeEnd,成对出现,用于测试代码执行时长
console.time('t1'); //启动t1的计时器
//做一些事情
for(var i=0;i<100000;i++){}
console.timeEnd('t1'); //停止计时器,此时会打印时长

//断言,判断表达式的值,当表达式为false时(或者undefined/null),
// 输出指定的内容,遇到一个断言即停止运行后面的代码
console.assert(1 != 1,'Error');

 

Result

 

print warn
print log
print error
1 2
1 NaN
print 1 2 yo 3 string
[object Object]
[object Object]
{“name”:”name”}
% 1
print info
Trace
{ n1: 1, n2: ‘string’, n3: { n4: 1, f: [Function: f], o: {} } }
at f2 (D:**.js:48:13)
f1
at Object. (D:**.js:51:1)
t1: 0.248ms
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:383:7)
at startup (bootstrap_node.js:149:9)

assert.js:80
throw new assert.AssertionError({
^
AssertionError: Error
at Console.assert (console.js:95:23)
at Object. (D:**.js:61:9)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:383:7)
at startup (bootstrap_node.js:149:9)

Process finished with exit code 1

PS:D:**.js为js本地运行的js文件