Introduction to file-type-cli
The file-type-cli is a powerful command-line tool for identifying file types by their header
signatures (often called magic numbers). It’s based on the
file-type
library and provides quick and accurate results. This tool is perfect for developers, system administrators, and anyone
who frequently works with various file formats.
Installation
npm install -g file-type-cli
Basic Usage
To identify a file type, simply run the following command:
file-type-cli
Examples of API Usage
Here are some useful APIs provided by file-type-cli:
1. Detecting the File Type from a Path
file-type-cli ./example.png
2. Detecting the File Type from a URL
curl -sL | file-type-cli
3. Detecting the File Type from STDIN
cat example.jpg | file-type-cli
4. Outputting in JSON Format
file-type-cli ./example.pdf --json
5. Specifying Multiple Files
file-type-cli file1.jpg file2.png file3.mp4
Example Application Using file-type-cli
Let’s build a small application that uses file-type-cli to detect file types and upload them:
Setup
First, create a Node.js project:
mkdir file-type-app
cd file-type-app
npm init -y
npm install file-type
Code Implementation
const fs = require('fs');
const fileType = require('file-type');
const { exec } = require('child_process');
const filePaths = ['./example1.jpg', './example2.png'];
async function detectFileType(filePath) {
const buffer = fs.readFileSync(filePath);
const type = await fileType.fromBuffer(buffer);
console.log(`${filePath} is of type ${type.ext}`);
}
filePaths.forEach(detectFileType);
// Alternatively, use file-type-cli
exec(`file-type-cli ${filePaths.join(' ')}`, (error, stdout, stderr) => {
if (error) throw error;
if (stderr) console.error(`stderr: ${stderr}`);
console.log(`stdout: ${stdout}`);
});
In this script, we use both file-type library and file-type-cli to detect the file types of the given files.
Conclusion
The file-type-cli is an invaluable tool for anyone needing to identify file formats quickly and efficiently. The simplicity and speed of this CLI tool make it an excellent choice for developers and system administrators alike.
Hash: 8cd41195773128c05363fedf9dac82fba9f9fd8cc0ed173b4fc557e2957e96a2