简体   繁体   中英

How to get file extension from file content using Node.js

I need one help. I need to fetch what the file type should be from the file content only using Node.js. I am exaplining the scenario below.

Lets say I have some content like below.

let fileContent = "The textContent property sets or returns the text content of the specified node, and all its descendants."

If we can see here the variable fileContent has some text data and I want to write this data into one file. So for that I need to create the file with proper extension like abc.txt . Similarly If fileContent has some json data then I will create the file like abc.json and write the value inside it.

So here I need to fetch what should be the type of file from this content only using Node.js . If anybody has solution for this will be great help.

You can use popular file-type package for this. You can send buffer/file/stream/blob as an input and get file type as an output.

const FileType = require('file-type');
...
const { ext, mime } = await FileType.fromBuffer(your_data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM