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,360
  • 13
  • 30
  • 42
Eyal Dreifuss
  • 29
  • 1
  • 5

3 Answers3

0

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

Igor Benikov
  • 884
  • 6
  • 21
  • 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
0

you can try to use file(1) utility that runs a number of tests against the file contents to classify it. Node.js has a module file-type that provides the functionality equivalent to file(1).

import {fileTypeFromFile} from 'file-type';

console.log(await fileTypeFromFile('test.js'));
Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76
windead
  • 51
  • 3
-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