【问题标题】:Nodejs, to get file type of a fileNodejs,获取文件的文件类型
【发布时间】:2018-12-28 13:55:07
【问题描述】:

六年前的问题“Node.js - File System get file type, solution around year 2012”有更好的答案,但过时的答案是正确的。

因此提出了一个问题,以获得最新的解决方案。

【问题讨论】:

    标签: javascript node.js filesystems file-type


    【解决方案1】:

    选项 1:如果您想要 mimetype

    安装

    npm i -S file-type read-chunk
    

    使用

    const readChunk = require('read-chunk');
    const fileType = require('file-type');
    
    const buffer = readChunk.sync(filePath, 0, fileType.minimumBytes);
    console.log(fileType(buffer));
    

    选项 2:如果您只需要可能的文件扩展名

    安装

    npm i -S image-size
    

    使用

    const sizeOf = require('image-size');
    console.log(sizeOf(filePath).type);
    

    【讨论】:

    • 文件类型 不起作用。刚刚尝试过,它正确地为 windows dll 返回mime":"application/x-msdownload",但它为二进制文件返回undefinedfile 命令正确返回ELF 64-bit LSB shared object, x86-64...
    • 我为 txt 类型的文件尝试了这个解决方案(选项 1 和 2),它只是返回了 undefined
    • 文本文件不需要有文件头,因此使用文件头的方法无法确定类型。
    猜你喜欢
    • 1970-01-01
    • 2018-12-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2022-12-05
    相关资源
    最近更新 更多