nodejs學習筆記-問題記錄

1.nodejs的buffer

// https://semlinker.com/node-buffer/
const typedArray3 = new Int8Array(8);typedArray3[0] = -32;
const typedArray4 = new Int16Array(8);typedArray4[0] = -32;
const typedArray5 = new Uint8Array(8);typedArray5[0] = -32;// 2^8 - 32
const typedArray6 = new Uint16Array(8);typedArray6[0] = -32;// 2^16 - 32

console.log(typedArray3);
console.log(typedArray4);
console.log(typedArray5);
console.log(typedArray6);

// 輸出:
> Int8Array [-32, 0, 0, 0, 0, 0, 0, 0]
> Int16Array [-32, 0, 0, 0, 0, 0, 0, 0]
> Uint8Array [224, 0, 0, 0, 0, 0, 0, 0]
> Uint16Array [65504, 0, 0, 0, 0, 0, 0, 0]

node和瀏覽器的buffer都是基於js的Uint8Array類生成。

allocUnsafe和allocSafe的區別是什麼?

allocUnsafe不會對分配的內存進行初始化: https://nodejs.org/dist/latest-v14.x/docs/api/buffer.html#buffer_class_method_buffer_allocunsafe_size

 2.npm包私有作用域

 

 

 3.模塊函數化和模塊對象化

// 模塊函數化
module.exports = function a(){}

// 模塊對象化
//user.js
function User(pName){
    this.name=pName;
    this.say=function(){
        console.log('你好,我是隔壁 '+this.name);          
    }
}
//將模塊導出對象替換爲User
module.exports=User;
//index.js
// 引用user.js導出模塊
var User=require('./user.js');
//創建一個user對象
var user1=new User('老王');
//調用這個對象的say方法
user1.say();

一個模塊中的JS代碼僅在模塊第一次被使用時執行一次,並在執行過程中初始化模塊的導出對象。之後,緩存起來的導出對象被重複利用。這就是commonJs的緩存機制。

4.sockjs

SockJS的一大好處在於提供了瀏覽器兼容性。優先使用原生WebSocket,如果在不支持websocket的瀏覽器中,會自動降爲輪詢的方式。

以下幾種輪詢方式的解釋:https://www.cnblogs.com/hoojo/p/longPolling_comet_jquery_iframe_ajax.html

https://github.com/sockjs/sockjs-client

xhr-polling
jsonp-polling
iframe-xhr-polling
xdr-polling †
WebRTC

 

 5.換行符(亂入)

Linux、Windows 和 Mac 中的換行符對比
對於換行這個動作,Unix下一般只有一個 0x0A 表示換行("\n"),Windows 下一般都是 0x0D 和 0x0A 兩個字符,即 0D0A("\r\n"),蘋果機(MAC OS系統)則採用回車符 CR 表示下一行("\r")。
Unix 系統中:每行結尾只有 "<換行>",即 "\n";
Windows 系統中:每行結尾是 "<回車><換行>",即 "\r\n";
Mac 系統中:每行結尾是 "<回車>",即 "\r"。

 

這也是爲什麼form-data裏面的key-value之間要用/r/n換行

 6.在Node.js裏面,process.nextTick和Promise優先級

在Node.js裏面,process.nextTick和Promise,誰的優先級更高,why?他們和其他的event loop關係是什麼(比如時序上,和setTimeout,setImmediate之類的進行比較)https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章