global:
// 在Node.js中没有window对象,但是有一个类似的对象global,访问全局成员的时候可以省略global
global.console.log(123456);
__filename、__dirname:
// 包含文件名称的全路径
console.log(__filename);
// 文件的路径(不包含文件名称)
console.log(__dirname);
clearTimeout(timeoutObject)、setTimeout(callback, delay[, ...args]):
// 定时函数,用法与浏览器中的定时函数类似
var timer = setTimeout(function(){
console.log(123);
},1000);
setTimeout(function(){
clearTimeout(timer);
},2000);
process:
process.argv:
// argv是一个数组,默认情况下,前两项数据分别是:Node.js环境的路径;当前执行的js文件的全路径
// 从第三个参数开始表示命令行参数
console.log(process.argv);
当命令行加了参数的时候,会累加到数组后面:
process.arch:
// 打印当前系统的架构(64位或者32位)
console.log(process.arch);
Buffer类:
Buffer对象是Node处理二进制数据的一个接口。它是Node原生提供的全局对象,可以直接使用,不需要require(‘buffer’)。Buffer本质上就是字节数组
构造方法(类):实例化buf对象
Buffer.from(array):
let buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
console.log(buf.toString());
Buffer.from(string):
let buf = Buffer.from('hello','utf8');
console.log(buf);
Buffer.alloc(size):
let buf = Buffer.alloc(5);
console.log(buf);
静态方法:
Buffer.isEncoding() 判断是否支持该编码
console.log(Buffer.isEncoding('utf8'));
console.log(Buffer.isEncoding('gbk'));
Buffer.isBuffer() 判断是否为Buffer
let buf = Buffer.from('hello');
console.log(Buffer.isBuffer(buf));
console.log(Buffer.isBuffer({}));
Buffer.byteLength() 返回指定编码的字节长度,默认utf8
let buf = Buffer.from('中国','utf8');
console.log(Buffer.byteLength(buf));
console.log(buf.toString());
let buf1 = Buffer.from('中国','ascii');
console.log(Buffer.byteLength(buf1));
console.log(buf1.toString());
Buffer.concat() 将一组Buffer对象合并为一个Buffer对象
3);
let buf2 = Buffer.alloc(5);
let buf3 = Buffer.concat([buf1,buf2]);
console.log(Buffer.byteLength(buf3));
let buf1 = Buffer.from('tom');
let buf2 = Buffer.from('jerry');
let buf3 = Buffer.concat([buf1,buf2]);
console.log(Buffer.byteLength(buf3));
console.log(buf3.toString());
实例方法:
write() 向buffer对象中写入内容
let buf = Buffer.alloc(5);
console.log(buf);
let buf = Buffer.alloc(5);
buf.write('hello');
console.log(buf);
let buf = Buffer.alloc(5);
buf.write('hello',2);
console.log(buf);
let buf = Buffer.alloc(5);
buf.write('hello',2,2);
console.log(buf);
slice() 截取新的buffer对象
toString() 把buf对象转成字符串
let buf = Buffer.from('hello');
let buf1 = buf.slice(1,4);
console.log(buf === buf1);//false
console.log(buf1.toString());
toJson() 把buf对象转成json形式的字符串
// toJSON方法不需要显式(强制转换)调用,当JSON.stringify方法调用的时候会自动调用toJSON方法
// const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const buf = Buffer.from('hello');
const json = JSON.stringify(buf);
console.log(json);