node學習三:全域性成員概述
阿新 • • 發佈:2018-11-25
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);