Introduction to file-type
The file-type
library is a powerful tool for identifying the MIME type and extension of various file formats quickly and efficiently. It is widely used in modern web and mobile applications to handle file uploads, verify file formats, and much more. In this guide, we will explore dozens of useful APIs provided by the file-type
library with practical code snippets and examples.
Installation
npm install file-type
Basic Usage
Identify the file type of a buffer:
const FileType = require('file-type'); (async () => { const buffer = ...; const fileType = await FileType.fromBuffer(buffer); if (fileType) { console.log(fileType); // { ext: 'png', mime: 'image/png' } } })();
Identifying File Type from a Stream
const FileType = require('file-type'); const fs = require('fs'); (async () => { const stream = fs.createReadStream('file.png'); const fileType = await FileType.fromStream(stream); if (fileType) { console.log(fileType); // { ext: 'png', mime: 'image/png' } } })();
Detecting File Type from File Path
const FileType = require('file-type'); const fs = require('fs'); (async () => { const fileType = await FileType.fromFile('path/to/file.png'); if (fileType) { console.log(fileType); // { ext: 'png', mime: 'image/png' } } })();
Supported Mime Types
const types = FileType.extensions; console.log(types); // ['jpg', 'png', 'gif', 'webp', ...]
App Example with File-Type APIs
Below is a basic Express.js application demonstrating the use of file-type
to validate file uploads:
const express = require('express'); const multer = require('multer'); const FileType = require('file-type'); const app = express(); const upload = multer({ storage: multer.memoryStorage() }); app.post('/upload', upload.single('file'), async (req, res) => { const buffer = req.file.buffer; const fileType = await FileType.fromBuffer(buffer); if (fileType && (fileType.mime === 'image/png' || fileType.mime === 'image/jpeg')) { res.send('File is valid!'); } else { res.status(400).send('Invalid file type!'); } }); app.listen(3000, () => { console.log('Server started on port 3000'); });
The example above sets up an Express server with a file upload endpoint. It uses Multer to handle the file upload and file-type
to validate the file type. Only PNG and JPEG files are considered valid in this example.
Conclusion
The file-type
library is highly versatile and efficient for identifying file formats. It supports a wide range of file types and provides asynchronous methods for handling files. By integrating file-type
into your application, you can ensure proper file validation and streamline file handling processes.
Hash: a6b4edb371e864e4d17754188166f981f9a9a78e11273c7d8c87b4363c20af9d