node.js - 从 Node.js 的缓冲区中删除 "empty"字节

标签 node.js buffer

我有这个代码:

  const start = pos * 100;
  const b = Buffer.alloc(99);
  fs.readSync(logFD, b, 0, b.length, start);
  console.log(String(b)); 
  const j = JSON.parse(String(b).trim());

我收到此错误:

SyntaxError: Unexpected token in JSON at position 15

问题可能是我的缓冲区中有空字节:

7b22 7022 3a37 3236 3736 2c22 6222 3a31
3837 7d00 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000

我不知道要读取多少字节,所以我必须读取超过阈值的数据,然后将其缩小。有什么方法可以在转换为字符串之前从缓冲区中删除空字节吗?

最佳答案

所以我认为这有效:

  const i = b.indexOf(0x00);
  const nb = b.slice(0, i);

我只是在十六进制 0x00 的第一个索引出现后删除

关于node.js - 从 Node.js 的缓冲区中删除 "empty"字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283950/

相关文章:

node.js - 如何在客户端进行 react 将图像上传到 mongodb 缓冲区

emacs - 如何在 Emacs 中调用缓冲区列表

language-agnostic - 如何重现这种半随机像素背景?

mysql - 查询返回 BIT 数据类型的嵌套对象。如何获取位值?

javascript - JavaScript 中的对象方法与函数和封装

node.js - Node Express 模块抛出 'has no method urlencoded' 错误

windows - 在 Windows 上安装 npm 模块时出现 "cannot find module"

node.js - 无法将 mongodb atlas 连接到 intellij MongoExplorer

node.js - 从 Gridfs 读取 block 并转换为缓冲区

将具有不同类型成员的结构复制到缓冲区