通过分隔符分割缓冲区

如何通过分隔符将缓冲区拆分为数组


const array = split(buffer, '=')

在 Go 中我可以这样做


import "bytes"


parts := bytes.Split(buffer, []byte("="))

如何在 Nodejs 中实现相同的功能?


泛舟湖上清波郎朗
浏览 123回答 3
3回答

幕布斯6054654

不幸的是,至少我知道没有内置的方法。尝试这个function splitBufToArr(buf, splitStr) {    let start = 0;    let bufArr = [];    let isfound = true;    while (isfound) {        const idx = buf.indexOf(splitStr, start);        if (idx === -1) {            isfound = false;            if (bufArr.length > 0)                bufArr.push(buf.slice(idx));            break;        }        const chunk = buf.slice(start, idx);        start = idx + 1;        bufArr.push(chunk);    }    return bufArr;}const buf = Buffer.from('1,5,8,9');console.log(splitBufToArr(buf, ','));

慕标琳琳

根据您的需要,您可能最好使用字符串,因为它具有分割功能。但是如果你确实想将东西保留为缓冲区而不是字符串,使用 slice 和 indexOf,你可以创建一个简单的 split 函数,..例如。function splitBuffer(b, splitWith) {&nbsp; &nbsp; const ret = [];&nbsp; &nbsp; let s = 0;&nbsp; &nbsp; let i = b.indexOf(splitWith, s);&nbsp; &nbsp; while (i >= 0) {&nbsp; &nbsp; &nbsp; &nbsp; if (i >= 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ret.push(b.slice(s, i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; s = i + 1;&nbsp; &nbsp; &nbsp; &nbsp; i = b.indexOf(splitWith, s);&nbsp; &nbsp; }&nbsp; &nbsp; ret.push(b.slice(s));&nbsp; &nbsp; return ret;}//testconst b = Buffer.from('one=two=three');console.log(splitBuffer(b, '='))//result = [ <Buffer 6f 6e 65>, <Buffer 74 77 6f>,//<Buffer 74 68 72 65 65> ]

www说

在下面的示例中,我们使用库iter-ops来处理Buffer可迭代对象:import {pipe, split} from 'iter-ops';const i = pipe(    buffer,    split(value => value === 0x3D) // 0x3D = code for '=');console.log([...i]); //=> split chunks of buffer
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript