How to check if a variable is a blob in JavaScript

北城以北 提交于 2019-12-03 01:13:11

You can test if it is an instanceof Blob like this:

var MyBlob = new Blob(['test text'], {type : 'text/plain'});
console.log(MyBlob instanceof Blob) // true

jsFiddle: http://jsfiddle.net/jfriend00/5xkgd/

This will work for things that inherit from Blob also.

Note that instanceof needs to be passed the exact constructor function used to create the object!

This isn't always the case in NodeJS, since it doesn't have a global Blob implementation (so we're dealing with polyfills).

For example, node-fetch uses an internal Blob implementation, but if you're using jest in a test suite (which polyfills Blob), you'll notice that expect(myBlob).toBeInstanceOf(Blob); will throw an exception similar to:

expect(value).toBeInstanceOf(constructor)

Expected constructor: Blob
Received constructor: Blob

In such cases, the best we can do is:

const fetch = require('node-fetch');
fetch(/* some request */).then(res => {
  const myBlob = await res.blob(); // a Blob created by node-fetch
  console.log(myBlob.constructor.name === 'Blob'); // true
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!