automatic mimetypes in javascript node.js
Asked Answered
I

3

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.

Ideomotor answered 15/3, 2011 at 18:31 Comment(2)
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.Alicaalicante
oh wait - you're doing this from node ... whole different thing of course :-)Alicaalicante
S
11

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

Semicolon answered 15/3, 2011 at 19:6 Comment(3)
ahh there we go, thanks, i was mid way through writing my own really should improve my google fuIdeomotor
As of June 2012, the repo is no more available.Peccavi
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…Humus
T
5

npm install mime

require('mime')

var mimetype = mime.lookup('file.txt')
Tallowy answered 15/3, 2011 at 19:7 Comment(4)
Damn, is it only synchronous they? "content = fs.readFileSync(file, 'ascii')," yep, that needs changing.Toandfro
@tomwrong The load function with readFileSync only loads the configuration files on require(), it's not used by mime.lookup.Tallowy
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.Toandfro
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. github.com/broofa/node-mime/blob/master/mime.js#L62Tallowy
C
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.

Carminacarminative answered 16/2, 2014 at 23:32 Comment(1)
Agreed. but do you know how to install this package on windows platform ? its giving npm-gyp rebuild issue. github.com/mscdex/mmmagic/issues/70Heng

© 2022 - 2024 — McMap. All rights reserved.