I am currently attempting to utilize the file-type npm package directly in my browser.
Despite my efforts, I have encountered an error when trying to run the example code: Uncaught ReferenceError: fileType is not defined
(Example code can be found here: https://github.com/sindresorhus/file-type)const xhr = new XMLHttpRequest();
xhr.open('GET', 'unicorn.png');
xhr.responseType = 'arraybuffer';
xhr.onload = () => {
fileType(new Uint8Array(this.response));
//=> {ext: 'png', mime: 'image/png'}
};
xhr.send();
To resolve this issue, I attempted to include the file-type package in my index.html within a script tag without success. After some research, I discovered that using browserify was recommended for utilizing npm packages in the browser. Following this advice:
I created a file named deps.js and imported the file-type package as follows
const fileType = require("file-type");
Next, I bundled deps.js by running the command:
browserify deps.js -o bundle.js
Subsequently, I added bundle.js to index.html like this:
<script src="bundle.js"></script>
<script src="main.js"></script>
Below are snippets from: index.html, main.js, and deps.js for reference:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="bundle.js"></script>
<script src="main.js"></script>
</body>
</html>
//main.js
const xhr = new XMLHttpRequest();
xhr.open('GET', 'iris.webp');
xhr.responseType = 'arraybuffer';
xhr.onload = () => {
fileType(new Uint8Array(this.response));
//=> {ext: 'png', mime: 'image/png'}
};
xhr.send();
//deps.js
const fileType = require("file-type");
If everything works correctly, the expected output from fileType should resemble:
{
ext: 'webp',
mime: 'image/webp'
}
If anyone could offer insight into where I may be misstepping, it would be greatly appreciated. Thank you very much.