Shamoon
Shamoon

Reputation: 43501

Any way to figure out what language a certain file is in?

If I have an arbitrary file sent to me, using Node.js, how can I figure out what language it's in? It could be a PHP file, HTML, HTML with JavaScript inline, JavaScript, C++ and so on. Given that each of these languages is unique, but shares some syntax with other languages.

Are there any packages or concepts available to figure out what programming language a particular file is written in?

Upvotes: 0

Views: 725

Answers (1)

user3587554
user3587554

Reputation: 353

You'd need to get the extension of the file. Are you getting this file with the name including the extension or just the raw file? There is no way to tell if you do not either get the file name with the extension or to scan the dir it's uploaded to and grabbing the names of the files, and performing a directory listing task to loop through them all. Node has file system abilities so both options work. You need the file's name with extension saved in a variable or array to perform this. Depending on how you handle this you can build an array of file types by extensions optionally you can try using this node.js mime

Example:

var fileExtenstions = {h : "C/C++ header", php : "PHP file", jar : "Java executeable"};

You can either split the string that contains the files name using split() or indexOf() with substring.

Split Example:

var fileName = "hey.h"; // C/C++/OBJ-C header

var fileParts = fileName.split(".");

// result would be...
// fileParts[0] = "hey";
// fileParts[1] = "h";

Now you can loop the array of extensions to see what it is and return the description of the file you set in the object literal you can use a 2d array and a for loop on the numeric index and check the first index to see it's the extension and return the second index(second index is 1)

indexOf Example:

var fileName = "hey.h";

var delimiter = ".";

var extension = fileName.substring( indexOf( delimiter ), fileName.length );

now loop through the object and compare the value

Upvotes: 1

Related Questions