0

I am writing a program in node.js.

I want to create a function isJsFile(file) that get a file (name or content) and return true if the file is javascript file or false if its not.

How can i create this function?

Hamza Zafeer
  • 2,164
  • 13
  • 30
  • 38
Eyal Dreifuss
  • 29
  • 1
  • 5

2 Answers2

0

You can to use node-mime to indentity by mime type: https://github.com/broofa/node-mime

Igor Benikov
  • 814
  • 5
  • 19
  • I can't trust the file extension or mim type, i am working on files that i get from servers using http\s protocol , some of the files i get don't have ext, that is, the file doesn't ends with .js and the mime type isn't javascript. I need to find a way using only the file content to know if the file is javascript or not. – Eyal Dreifuss Jun 27 '16 at 08:14
  • you can use regular expression to determinate content ) – Igor Benikov Jun 27 '16 at 08:45
  • i don't think that regular expression will help here, javascript is too complicate for this, unless you have an idea how? – Eyal Dreifuss Jun 27 '16 at 10:02
  • If you can't trust to mime and file extension - you have two options: or regular expression or try to eval code – Igor Benikov Jun 27 '16 at 12:29
  • Perhaps using esprima will help here? – Eyal Dreifuss Jun 30 '16 at 13:05
-1

Simply use path to get the file extension:

var path = require('path')
path.extname(YOUR_FILENAME) // returns '.js' if file is a js file
  • I can't trust the file extension or mim type, i am working on files that i get from servers using http\s protocol , some of the files i get don't have ext, that is, the file doesn't ends with .js and the mime type isn't javascript. I need to find a way using only the file content to know if the file is javascript or not. – Eyal Dreifuss Jun 27 '16 at 08:15