Any way to figure out what language a certain file is in? - node.js

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?

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

Related

Converting stream to string in node.js

I am reading a file which comes in as an attachment like follows
let content = fs.readFileSync(attachmentNames[index], {encoding: 'utf8'});
When I inspect content, it looks ok, I see file contents but when I try to assign it to some other variable
attachmentXML = builder.create('ATTACHMENT','','',{headless:true})
.ele('FILECONTENT',content).up()
I get the following error
Error: Invalid character in string: PK
There are a couple of rectangular boxes (special characters) after PK in the above message which are not getting displayed.
builder here refers to an instance of the xmlbuilder https://www.npmjs.com/package/xmlbuilder node module.
I fixed this by enclosing the string inside a JS escape() method

In Node.js imported txt file into a variable, but variable doesnt behave like a string

So in node.js I a have read a simple txt file into a variable, but when I want to call whichever string function like split or indexOf on the variable, it doesnt work.
if I do string.indexOf('whatever character'), I become always -1
And if i do string.splice('whichever separator') I become always this on the console: '\u0000s\u0000\r\u0000\n\u0000....'
the code:
const fs = require('fs');
let emails = fs.readFileSync('../model/hotel-emails-with-links-exerc.txt', 'utf-8');
console.log(emails.split('/'));
console.log(emails.indexOf('http'));
this is the content of the file I read : 'youreamil#gmail.com|https://www.hotel-monte.at/de/zimmer-preise/pauschalen.html?offer=27'
If I do console.log(typeof emails) I get 'string' as normal.
However string variables whiches value was not imported from a txt file are working fine.
thanks for the suggestions

How to change all sorts of accents and special characters from a path in Swift?

Hey what's up everyone?
I have a simple app to display the file size of files selected by users. The problem is that when the file is located within a folder that has spaces in the folder name or special characters like accents (á é ç) the file path uses different symbols and then I can't get the file size.
The folder is: /Users/home/Checking/First Box
This is my code and the output:
var path = url.absoluteString?.stringByReplacingOccurrencesOfString("file://", withString: "", options: nil, range: nil)
var filePath = path
var attr:NSDictionary? = NSFileManager.defaultManager().attributesOfItemAtPath(filePath!, error: nil)
if let _attr = attr {
fileSize = _attr.fileSize();
}
println(fileSize)
println(filePath!)
And the output is nil for the file size and /Users/home/Checking/First%20Box for the file path.
Also if I select a folder with accent on its name like /Users/home/Checking/Café the output for the path will be /Users/home/Checking/Cafe%CC%81
One solution, which is the one I am using using stringByReplacingOccurrencesOfString but this adds a lot of line to the code since there are many characters with accent throughout the languages around the world and I was wondering if there's another more simple way to do this.
Any help will be much appreciated.
The problem is that you are using a wrong (and too complicated) method
to convert a file URL to a path.
Example:
let url = NSURL(fileURLWithPath: "/ä/ö/ü")!
println(url.absoluteString!) // file:///a%CC%88/o%CC%88/u%CC%88
println(url.path!) // /ä/ö/ü
As you see, .absoluteString returns a HTML string with percent escapes,
whereas .path returns the file path. So your code should look like this:
if let filePath = url.path {
println(filePath)
if let attr : NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: nil) {
let fileSize = attr.fileSize();
println(fileSize)
// ...
}
}

node.js fs.existsSync returns incorrect value for paths containing environment variables

I am trying to use fs.existsSync to check whether a file exists. When the full filesystem path is entered, it returns successfully. When the path contains an environment variable like ~/foo.bar or $HOME/foo.bar, it fails to find the file.
I have tried all of the methods from the path module to massage the path first, but nothing seems to work. I should note that the filepath is entered by the user either via command line or a JSON file.
I am aware that the environment variables live in process.env, but I was wondering if there is some way to handle this aside from a find/replace for every possible variable.
Environment variables are expanded by the shell. Node's fs methods make filesystem calls directly.
Read the variable you need out of process.env and use path.join to concatenate.
path.join(process.env.HOME, 'foo.bar');
(Keep in mind there is no HOME variable on Windows if you need to be cross-platform; I believe it's USERPROFILE.)
Since you're dealing with user input, you're going to have to parse the path components yourself.
First, normalize the input string and split it into an array.
var p = path.normalize(inputStr).split(path.sep);
If the first element is ~, replace it with the home directory.
if (p[0] == '~') p[0] = process.env.HOME || process.env.USERPROFILE; // Windows
Then loop over each element, and if it starts with $, replace it.
for (var i = 0; i < p.length; i++) {
if (p[i][0] == '$') {
var evar = p[i].substr(1);
if (process.env[evar]) p[i] = process.env[evar];
}
}
And finally, join the path array back together, re-normalizing:
path.join.apply(path, p);
Use process.env.HOME instead? Then use path.join to get the correct path.
fs.existsSync(path.join(process.env.HOME,"foo.bar"));

How to get the file name from the full path of the file, in vc++?

I need to get the name of a file from its full path, in vc++. How can I get this? I need only the file name. Can I use Split method to get this? If not how can I get the file name from the full path of the file?
String^ fileName = "C:\\mydir\\myfile.ext";
String^ path = "C:\\mydir\\";
String^ result;
result = Path::GetFileName( fileName );
Console::WriteLine( "GetFileName('{0}') returns '{1}'", fileName, result );
See Path::GetFileName Method
Find the last \ or /1 using one of the standard library string/char * search methods. Then extract the following text. Remember to special case where the / or \ is the last character.
1 The Windows API, for most purposes2 supports both.
1 The exception is when using long paths starting \\?\ to break 260 character limit on paths.
Directory::GetFiles Method (String, String)
Returns the names of files (including their paths) that match the specified search pattern in the specified directory.

Resources