11

I'm uploading files to aws s3 in javascript, and AFAIK they all need a mimetype to function correctly. Is there a script that automatically maps filenames to mimetypes that I could use?

Edit: If there's a way for amazon to automatically handle the mimetypes that would be better.

ben75
  • 29,217
  • 10
  • 88
  • 134
Mark
  • 32,293
  • 33
  • 107
  • 137
  • I'm pretty sure that the browser makes an internal determination of file MIME type, probably by browser- and/or platform-dependent rules. I don't know of any way to have code in the page play a role in that determination. – Pointy Mar 15 '11 at 18:40
  • 1
    oh wait - you're doing this from node ... whole different thing of course :-) – Pointy Mar 15 '11 at 18:45

3 Answers3

11

https://github.com/broofa/node-mime is a decent looking library for automatic mime lookups.

Andrei Neculau
  • 986
  • 1
  • 10
  • 15
Zikes
  • 5,888
  • 1
  • 30
  • 44
  • 1
    ahh there we go, thanks, i was mid way through writing my own really should improve my google fu – Mark Mar 15 '11 at 19:11
  • As of June 2012, the repo is no more available. – esengineer Jun 27 '12 at 04:43
  • This lib just looks at the extension to infer de MIME type, if extension is wrong, MIME will be wrong too. Not secure depending on what you do with it… – Buzut Dec 06 '15 at 18:25
5

npm install mime

require('mime')

var mimetype = mime.lookup('file.txt')
Andrei Neculau
  • 986
  • 1
  • 10
  • 15
Ricardo Tomasi
  • 34,573
  • 2
  • 55
  • 66
  • Damn, is it only synchronous they? "content = fs.readFileSync(file, 'ascii')," yep, that needs changing. – thomas-peter Aug 08 '12 at 07:58
  • @tomwrong The `load` function with `readFileSync` only loads the configuration files on `require()`, it's not used by `mime.lookup`. – Ricardo Tomasi Aug 09 '12 at 18:25
  • it which case, why has lookup not got a callback function. Please don't read this the wrong way, I'm still learning node.js and honestly can't understand how any code after "var mimetype = mime.lookup('file.txt')" would get executed until lookup returns. – thomas-peter Aug 14 '12 at 10:50
  • `lookup` is synchronous, so nothing will execute until it returns. But don't worry, it's just a simple operation, your app code using it is probably 10x slower. https://github.com/broofa/node-mime/blob/master/mime.js#L62 – Ricardo Tomasi Aug 14 '12 at 14:44
2

Found this question via Google and just wanted to add that mime type detection by looking at the file extension is not secure at all. I'd recomment using mmmagic which actually looks at the data to determine the mime type of a file.

Philippe Gerber
  • 17,457
  • 6
  • 45
  • 40
  • Agreed. but do you know how to install this package on windows platform ? its giving npm-gyp rebuild issue. https://github.com/mscdex/mmmagic/issues/70 – Aman Gupta Dec 15 '15 at 07:48