console
格式化
console.log("%s:%s", "a", "b") //字符串
console.log("%d.%d", 10.2, 0.12) //整型
console.log("%j", {a: "aa", b: "bb"}) //json
冲定向错误输出柳
- 对于
throw Erro, console.error, console.warn
node exec.js 2 > error.log
查看对象属性和方法
console.dir(obj)
//等价
var util = require('util')
console.log(util.inspect(obj));
计时器
console.time(label) //开始
console.timeEnd(label) //结束
查看当前调用栈
//打印当前位置的栈,并跟踪到标准错误输出流
console.trace(label)
断言
console.assert(expression, error message)
//相当于
var assert = require('assert')
assert.okt(expression, error message)
readline
命令行输入数据
var readline = require('readline')
var read = readline.createInterface({
input: process.stdin,
output: process.stdout
})
read.question("you name?", function(answer) {
console.log(answer);
read.close()
})
向控制台输出组合控制键
//3s后模拟ctrl+u
var readline = require('readline')
var read = readline.createInterface({
input: process.stdin,
output: process.stdout
})
read.write("Delete me! Wait for 3 seconds...")
var timer = setTimeout(function () {
read.write(null, {ctrl: true, name: 'u'})
}, 3000)
//read,write(data, key) key是一个代表键序列的对象
模拟控制台界面
//read.prompt(boolean) 为true或空时可以阻止命令提示符的光标被重置为0
var readline = require('readline')
var read = readline.createInterface({
input: process.stdin,
output: process.stdout
})
read.setPrompt('NodeJs>')
read.prompt()
read.on("line", function (line) {
switch(line.trim()) {
case 'book1':
console.log(100);
break;
case 'book2':
console.log(200);
break;
default:
console.log('no');
break;
}
read.prompt()
})
.on('close', function () {
console.log('bye');
process.exit(0);
})
module
node_modules文件加载
module.paths
: 数组返回加载的依次路径
module.exports 对象和exports对象
module.parent 指向该module被require时的module,可以用于测试判读
module.exports
是module
模块的真正接口, exports
是指向它的变量;
- 所以设置
module.exports
后exports
设置就失效了
Buffer
js语言本身仅仅支持Unicode字符串数据处理
初始化
var buffer1 = new Buffer([0x6e, 0x6f, 0x64, 0x65, 0x6a, 0x73])
var buffer2 = new Buffer('nodejs')
//显示都为<Buffer 6e 6f 64 65 6a 73>, 16进制, hex
buffer.toString(encoding, start, end) // 默认utf8, 还有hex, binary, base64, utf16le, ascii
//特别定义
var buffer = new Buffer(length) /分配大小为length的8位字节
buffer.write(string, offset, length, encoding)
//判断是否为指定编码
buffer.isEncoding(encoding)
Buffer字节长度
str.length //字符长度
Buffer.byteLength(str, encoding) //字节长度
- 在改写
http
响应头Content-Length
时一定要使用该方法而不是修改length
基本操作
var buf = new Buffer('nodejs')
//裁减, buf.slice(start, end)
var buf1 = buf.slice() // 副本, buf1和buf2指向同一地址
buf1[0] = 97 //ASCII 'a'
console.log(buf.toString()); //anodejs
console.log(buf1.toString()); //anodejs
//拷贝 buf.copy(target, targetStart, sourceStart, sourceEnd)
var buf2 = new Buffer(buf.length)
buf.copy(buf2,0,0,buf.length)
buf2[0] = 110 //ASCII 'n'
console.log(buf.toString()); //anodejs
console.log(buf2.toString()); //nnodejs
//拼接 Buffer.concat(list, totalLength)
//如果totalLength没有提供会增加额外的计算
var list = [], len = 0;
for (var i = 0; i < 4; i++) {
list.push(buf)
len += buf.length
}
var buf3 = Buffer.concat(list, len)
console.log(buf3.toString());