计划每天看一点
process
可以读取一些环境变量吧,最常见的就是起服务的时候,process.env.PORT
下面是个例子,就是dog写错了,要在uncaughtException的时候退出(process.exit(1)),不然程序就卡这里无法继续了,可以对比执行下
process.on('exit', (code) => {
// do one final synchronous operation
// before the node process terminates
console.log(`About to exit with code: ${code}`);
});
process.on('uncaughtException', (err) => {
// something went unhandled.
// Do any cleanup and exit anyway!
console.error(err); // don't do just that.
// FORCE exit the process too.
process.exit(1);
});
// keep the event loop busy
process.stdin.resume();
// trigger a TypeError exception
console.dog();
Buffer的创建方式
存储 Buffer的创建
1 Buffer.alloc(8)
2 Buffer.allocUnsafe(9) 这种就是没初始化
3 Buffer.allocUnsafe(8).fill(0) 这种初始化
注意slice会改变原数组
//********注意***********
//slice()方法会返回一个新的buffer,但是新的bf2和源对象bf引用的是同一个!!!!也就是bf2的改变会改变bf
var bf=new Buffer('panwen');
console.log(bf); //<Buffer 70 61 6e 77 65 6e>
var bf2=bf.slice(1,4);//<Buffer 61 6e 77>---从下标1开始截取,截取到4,不包括4
console.log(bf2);
bf2[0]=0;
console.log(bf2); //<Buffer 00 6e 77>
console.log(bf);//<Buffer 70 00 6e 77 65 6e>
//********注意***********
实现深拷贝
要想实现深拷贝,用Buffer.copy(tembf);
var bf=new Buffer('panwen');
console.log(bf); //<Buffer 70 61 6e 77 65 6e>
var bf3=new Buffer(10);
bf.copy(bf3);//这是拷贝到bf3中!,拷贝也可选位置,bf.copy(bf3,1,2,4)从第二位开始拷贝到3,1实质拷贝到buffer的第一位!
console.log(bf3);//<Buffer 70 61 6e 77 65 6e 6f 72 00 00>后四位随机,不初始化
bf3[0]=0;
console.log(bf3);//<Buffer 00 61 6e 77 65 6e 6f 72 00 00>
console.log(bf); //<Buffer 70 61 6e 77 65 6e>,不会改动原对象
StringDecoder
const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');
process.stdin.on('readable', () => {
const chunk = process.stdin.read();
if (chunk != null) {
const buffer = Buffer.from([chunk]);
console.log('With .toString():', buffer.toString());
console.log('With StringDecoder:', decoder.write(buffer));
}
});
用StringDecoder来解析Buffer里面的数据吧,就是三个输入uft-8 最后解释成欧元字符