首页 > 其他分享 >Fetch API res.buffer vs res.arrayBuffer All In One

Fetch API res.buffer vs res.arrayBuffer All In One

时间:2023-09-12 22:24:25浏览次数:48  
标签:Response buffer res arrayBuffer response fetch

Fetch API res.buffer vs res.arrayBuffer All In One

error

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of ArrayBuffer

import fs from 'node:fs';
import path from 'path';
import fetch from "node-fetch";

// read JSON ✅ filename
const url = `https://cdn.xgqfrms.xyz/video/web-testing.mp4`
const filename = "web-testing.mp4";
const dirPath = "./abc";
if (!fs.existsSync(dirPath)) {
  fs.mkdirSync(dirPath);
}

// fetch data as a buffer
fetch(url)
  // ❌
  // .then((res) => res.arrayBuffer())
  .then((res) => {
    // console.log(`res =`, res)
    console.log(`loading ... ⏳`);
    return res.arrayBuffer();
  })
  // (node:40449) [node-fetch#buffer] DeprecationWarning: Please use 'response.arrayBuffer()' instead of 'response.buffer()'
  .then((buffer) => {
    console.log(`finished ✅`)
    // Write the buffer to a file
    // ❌`fs.writeFile` TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of ArrayBuffer
    fs.writeFile(path.join(dirPath, filename), buffer, (err) => {
      if (err) {
        console.error(err);
      } else {
        console.log("video downloaded successfully");
      }
    });
  })
  .catch((err) => console.error(err));

warning ⚠️

The signature '(): Promise<Buffer>' of 'res.buffer' is deprecated.ts(6387)
index.d.ts(134, 6): The declaration was marked as deprecated here.
(method) BodyMixin.buffer(): Promise<Buffer>
@deprecated — Use body.arrayBuffer() instead.

Deprecation Warning: Please use 'response.arrayBuffer()' instead of 'response.buffer()'

import fs from 'node:fs';
import path from 'path';
import fetch from "node-fetch";

// read JSON ✅ filename
const url = `https://cdn.xgqfrms.xyz/video/web-testing.mp4`
const filename = "web-testing.mp4";
const dirPath = "./abc";
if (!fs.existsSync(dirPath)) {
  fs.mkdirSync(dirPath);
}

// fetch data as a buffer
fetch(url)
  // ✅
  // .then((res) => res.buffer())
  .then((res) => {
    // console.log(`res =`, res)
    console.log(`loading ... ⏳`);
    return res.buffer();
  })
  // (node:40449) [node-fetch#buffer] DeprecationWarning: Please use 'response.arrayBuffer()' instead of 'response.buffer()'
  .then((buffer) => {
    console.log(`finished ✅`)
    // Write the buffer to a file
    fs.writeFile(path.join(dirPath, filename), buffer, (err) => {
      if (err) {
        console.error(err);
      } else {
        console.log("video downloaded successfully");
      }
    });
  })
  .catch((err) => console.error(err));

image

Response.arrayBuffer()

function getData() {
  const audioCtx = new AudioContext();

  return fetch("viper.ogg")
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error, status = ${response.status}`);
      }
      // arrayBuffer❓需要转换处理
      return response.arrayBuffer();
    })
    .then((buffer) => audioCtx.decodeAudioData(buffer))
    .then((decodedData) => {
      const source = new AudioBufferSourceNode();
      source.buffer = decodedData;
      source.connect(audioCtx.destination);
      return source;
    });
}

// wire up buttons to stop and play audio

play.onclick = () => {
  getData().then((source) => {
    source.start(0);
    play.setAttribute("disabled", "disabled");
  });
};

https://developer.mozilla.org/en-US/docs/Web/API/Response/arrayBuffer

demos

(

标签:Response,buffer,res,arrayBuffer,response,fetch
From: https://www.cnblogs.com/xgqfrms/p/17697977.html

相关文章

  • js 浏览器的5种observer 第三种 ResizeObserver 详解及使用方法
     ResizeObserver它允许开发者监听元素的尺寸变化。在前端开发中,元素尺寸的变化可能会受到许多因素的影响,例如窗口大小调整、设备方向变化、内部内容变化等。提供了一种高效的方法来响应这些变化,而不需要频繁使用事件监听器或轮询技术。1.使用方法constro=newResizeOb......
  • Docker配置PostgreSQL数据本地持久化
    原文:https://www.cnblogs.com/yangyangming/p/13502405.html主机中的本地目录作为Docker容器内的持久存储卷装载,以便在主机和Docker容器之间共享数据。如果主机希望访问或定期备份在Docker容器内运行的DB服务器写入文件夹的数据或数据库,则此方法非常有用。创建本地数据卷#创建......
  • opencv resize
    opencvresize importcv2fromccvimportccv2#读取图像image=cv2.imread("example.jpg")#调整图像大小resized_image=ccv2.resize(image,300,300,ccv2.INTER_LINEAR)#显示调整大小后的图像cv2.imshow("ResizedImage",resized_image)cv2.waitKey(0......
  • 关于intent之android.intent.action.USER_PRESENT的接收与使用
    在做解锁监听程序时,一开始采用监听屏幕SCREEN_ON和SCREEN_OFF这两个action。但奇怪的是,这两个action只能通过代码动态的形式注册,才能被监听到,使用AndroidManifest.xml完全监听不到。百度后发现这是PowerManager那边在发这个广播的时候做了限制,限制只能有register到代......
  • 如何使用Oracle Enterprise Manager Database Express连接到PDB数据库
    1.问题重复弹出登录框,无法登陆关闭登录框,显示invalidcontainername2.解决方法参考链接为PDB启动EMExpress要为PDB启动EMExpress,请确保PDB以读/写模式打开,然后尝试本主题中描述的以下方法之一(按所示顺序):连接到包含PDB的CDB的CDB$ROOT容器,并发出以下SQL......
  • ORACLE Enterprise Manager Database Express(OEM-express)配置端口和启动方法
    1.问题之前一直进不去ORACLEEnterpriseManagerDatabaseExpress,显示的是localhost拒绝了访问,经过查阅知道是没有配置相应端口。2.解决方法转载自:https://blog.csdn.net/wshjx0001/article/details/1224660151.首先查看监听状态,如果监听没有启动需要先启动监听2.在SQLpl......
  • static nat(network address translate)
    核心1、出接口配置natstatic转换,命令如下interfaceGigabitEthernet0/0/1ipaddress20.1.1.1255.255.255.0 natstaticglobal20.1.1.3inside10.1.1.2netmask255.255.255.255natstaticglobal20.1.1.4inside10.1.1.3netmask255.255.255.255注意:此种转换方式......
  • OGG-Postgres实时同步到Kafka
    (一)数据同步信息名称源端名称目标端数据库类型Postgresql12.4组件类型KafkaIP地址20.2.127.23Broker地址20.2.125.52:9092,20.2.127.23:9092,20.2.127.24:9092端口5432端口9092数据库testpdbZookeeperHa......
  • onBackPressed 设置返回值,onActivityResult resultcode一直是0
    activity1:Intentintent2=newIntent(this,checkactivity.class);startActivityForResult(intent2,1000);activity2:@OverridepublicvoidonBackPressed(){super.onBackPressed();Intentintent=newIntent();setResult(result,in......
  • mybatis中设置自增的值,使用resultmap设置多对一的关系以及使用级联的方式设置多对一的
    2023-09-11UserMappervoidinsertUser(Useruser);UserMapper.xml<insertid="insertUser"useGeneratedKeys="true"keyProperty="id">insertintot_uservalues(null,#{name},#{password},#{age},#{gender},#{email})......