最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

file - In node.js given a filename how do you get its format and media type? - Stack Overflow

programmeradmin3浏览0评论

I want the output to be like image/png. type then followed by the extension. The filename doesn't include any information.

I tried basics such as mediainfo and ffprobe but one showed missing libraries error and the other doesn't work with images. I also

I want the output to be like image/png. type then followed by the extension. The filename doesn't include any information.

I tried basics such as mediainfo and ffprobe but one showed missing libraries error and the other doesn't work with images. I also

Share Improve this question asked Mar 17 at 8:38 Ur NiiicbUr Niiicb 31 bronze badge 1
  • Please provide enough code so others can better understand or reproduce the problem. – Community Bot Commented Mar 17 at 9:53
Add a comment  | 

1 Answer 1

Reset to default 0

You can use the fs module (built-in) and file-type package (install with npm):

npm install file-type

with code like:

const fs = require('fs');
const fileType = require('file-type');
    
const getFileType = async(filePath) {
    const fileBuffer = fs.readFileSync(filePath);
    const type = await fileType.fromBuffer(fileBuffer);
    
    if (type) {
       console.log(`${type.mime} (${type.ext})`);
       return `${type.mime}`
    } else {
       console.log('Unable to determine the file type.');
       return 'unknown';
    }

}

const filename = 'path/to/your/file';
getFileType(filename)
.then((result) => console.log('MIME type:', result))
.catch((err) => console.error('Error:', err));
发布评论

评论列表(0)

  1. 暂无评论