node.js中的buffer.slice方法使用說明
方法說明:
返回一個新的buffer對象,這個新buffer和老buffer公用一個內(nèi)存。
但是被start和end索引偏移縮減了。(比如,一個buffer里有1到10個字節(jié),我們只想要4-8個字節(jié),就可以用這個函數(shù)buf.slice(4,8),因為他們共用一個內(nèi)存,所以不會消耗內(nèi)存,)
因為共用內(nèi)存,所以修改新的buffer后,老buffer的內(nèi)容同樣也會被修改。
語法:
buffer.slice([start], [end])
接收參數(shù):
start 開始位置,默認(rèn)
end 結(jié)束位置,默認(rèn)為buffer長度
例子:
用ASCII碼字母表創(chuàng)建一個buffer,用一下slice函數(shù),然后修改原buffer中的一個字節(jié)。
var buf1 = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
}
var buf2 = buf1.slice(0, 3);
console.log(buf2.toString('ascii', 0, buf2.length));
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));
// abc
// !bc
源碼:
// TODO(trevnorris): currently works like Array.prototype.slice(), which
// doesn't follow the new standard for throwing on out of range indexes.
Buffer.prototype.slice = function(start, end) {
var len = this.length;
start = ~~start;
end = util.isUndefined(end) ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0)
start = 0;
} else if (start > len) {
start = len;
}
if (end < 0) {
end += len;
if (end < 0)
end = 0;
} else if (end > len) {
end = len;
}
if (end < start)
end = start;
var buf = new NativeBuffer();
sliceOnto(this, buf, start, end);
buf.length = end - start;
if (buf.length > 0)
buf.parent = util.isUndefined(this.parent) ? this : this.parent;
return buf;
};
- 使用node.js中的Buffer類處理二進(jìn)制數(shù)據(jù)的方法
- Node.js中使用Buffer編碼、解碼二進(jìn)制數(shù)據(jù)詳解
- Node.js Windows Binary二進(jìn)制文件安裝方法
- node.js中Buffer緩沖器的原理與使用方法分析
- Node.js Buffer模塊功能及常用方法實例分析
- 詳解如何在Node.js的httpServer中接收前端發(fā)送的arraybuffer數(shù)據(jù)
- Node.js Buffer用法解讀
- 關(guān)于Node.js中Buffer的一些你可能不知道的用法
- 淺談Node.js:Buffer模塊
- Node.js實用代碼段之正確拼接Buffer
- Node.js實用代碼段之獲取Buffer對象字節(jié)長度
- node.js中的buffer.copy方法使用說明
- node.js中的buffer.fill方法使用說明
- node.js中的buffer.length方法使用說明
- node.js中的buffer.toJSON方法使用說明
- node.js中的buffer.toString方法使用說明
- node.js中的buffer.Buffer.isEncoding方法使用說明
- node.js中的buffer.Buffer.isBuffer方法使用說明
- node.js中的buffer.Buffer.byteLength方法使用說明
- node.JS二進(jìn)制操作模塊buffer對象使用方法詳解
相關(guān)文章
利用Node.js+Koa框架實現(xiàn)前后端交互的方法
這篇文章主要給大家介紹了利用Node.js+Koa框架實現(xiàn)前后端交互的方法,文中介紹的非常詳細(xì),對大家具有一定的參考價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。2017-02-02node跨域轉(zhuǎn)發(fā) express+http-proxy-middleware的使用
這篇文章主要介紹了node跨域轉(zhuǎn)發(fā) express+http-proxy-middleware的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05nodejs?express路由匹配控制及Router模塊化使用詳解
這篇文章主要為大家介紹了nodejs?express路由匹配控制及Router模塊化使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10express如何解決ajax跨域訪問session失效問題詳解
這篇文章主要給大家介紹了關(guān)于express如何解決ajax跨域訪問session失效問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06