3

I have an Angular app and a component where I upload files. Now I want to check a real file's type using the file-type library. It has a huge number of downloads and almost no issues, but I can't make it work. So, probably, I'm missing something basic but crucial.

I took the basic example of checking a file from BLOB:

const FileType = require('file-type/browser');
 
(async () => {
    const blob = new Blob(['<?xml version="1.0" encoding="ISO-8859-1" ?>'], {
        type: 'plain/text',
        endings: 'native'
    });
 
    console.log(await FileType.fromBlob(blob));
    //=> {ext: 'txt', mime: 'plain/text'}
})();

but it gives me an error:

Error in C:/project/node_modules/readable-web-to-node-stream/lib/index.js

Module not found: Error: can't resolve 'stream' in C:/project/node_modules/readable-web-to-node-stream/lib/

I've added a stream package (what is not a good solution, probably), and the error was changed to:

Uncaught TypeError: Class extends value undefined is not a constructor or null

After that, I decided that might be my current project is too complicated and I can give it a shot in a new small project, so I created one. Installed file-type and took the same example from their page (I only changed const FileType = require('file-type/browser'); to import {fromBlob} from 'file-type/browser');

But here another error appears:

Uncaught ReferenceError: global is not defined

I added (window as any)['global'] = window; to the polyfill.js

Uncaught ReferenceError: Buffer is not defined

I added the buffer package and global.Buffer = global.Buffer || require('buffer').Buffer; to the polyfill.js

Uncaught ReferenceError: process is not defined

Here I gave up. I definitely don't understand something and need some help. What I missed?

Wanted to add a stackblitz example, but it gives me another error:

Import error, can't find file: ./common

1 Answer 1

1

By the end I gave up using .fromBlob or .fromStream methods and file-type/browser part at all. What works:

polyfills.ts

/*
 * APPLICATION IMPORTS
 */
(window as any).global = window;
// @ts-ignore
// tslint:disable no-var-requires
window.Buffer = window.Buffer || require('buffer').Buffer;

component.ts

import { fromBuffer, FileTypeResult } from 'file-type/core';

async getTrueFileType(file: File): Promise<FileTypeResult | undefined> {
  return file.arrayBuffer().then(buffer => fromBuffer(buffer));
}

async validateFile(file) {
  const ext = await this.getTrueFileType(file);
  console.log(ext); // {ext: 'png', mime: 'image/png'}
}

For more details you can read the issue

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.