You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发VS Code扩展时出现“ArrayBuffer is not a constructor”错误的原因?

解决Binary File Viewer子扩展的ArrayBuffer构造函数错误

问题场景

为VS Code的Binary File Viewer扩展编写子扩展时,运行出现Type error: ArrayBuffer is not a constructor错误,代码如下:

/**
 * Select the 'aid' extension.
 */
registerFileType((fileExt, filePath, fileData) => {
    return fileExt == 'wav';
});

registerParser(() => {
    const buffer = new ArrayBuffer(4);

    let temp = new DataView(buffer);
    temp.setInt32(0, 123)
    let I = String(temp.getFloat32());
    addRow('I', I, '');
});

错误原因

  1. 运行环境限制:Binary File Viewer的子扩展运行在VS Code扩展的受限沙箱环境中,全局未暴露ArrayBuffer构造函数,不能直接使用浏览器/Node.js环境的全局二进制对象。
  2. 数据读写类型不匹配:代码中用setInt32写入整数数据,却用getFloat32读取,这会导致解析出错误的数值,虽不是当前构造函数错误的直接原因,但属于逻辑bug。

解决方法

  1. 查阅扩展API文档:优先参考Binary File Viewer子扩展的开发文档,确认其提供的内置二进制数据处理API,多数此类扩展会封装专属的二进制操作工具,避免依赖全局对象。
  2. 适配运行环境:若必须使用原生二进制对象,需确认环境是否支持通过其他方式获取(如VS Code内置模块),但更可靠的方式是使用扩展提供的替代方案。
  3. 纠正数据读写逻辑:保证写入和读取的类型一致,示例修改如下:
/**
 * Select the 'wav' extension.
 */
registerFileType((fileExt, filePath, fileData) => {
    return fileExt === 'wav'; // 使用严格相等判断更严谨
});

registerParser(() => {
    // 若环境支持ArrayBuffer,或已通过扩展API获取到构造权限
    const buffer = new ArrayBuffer(4);
    const temp = new DataView(buffer);
    // 建议指定字节序(true为小端,false为大端),根据WAV文件格式调整
    temp.setInt32(0, 123, true);
    // 用对应类型读取数据
    const I = String(temp.getInt32(0, true));
    addRow('I', I, '');
});

内容的提问来源于stack exchange,提问作者Dmitry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 18:31:25