Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs check if the given string is a valid file system path without actually checking the file system

How in nodejs can I check if the given string is a valid filesystem path without actually checking the filesystem.

I am using telegram bot nodejs api and when sending files it checks if the file exist or not. But on the second time I am using the telegram file id that i got from the previews upload and not the actual file path to send the file, so in this case i want to check if the string is a actual file path and not a file id(exp: AgADBAADuqcxG-ysuwhqkRaOdVnJI0CZXhkABL1NBSyVlK3gduoAAgI) before checking if file exist so to increase performance and avoid unnecessary file system access.

like image 705
Exlord Avatar asked Aug 16 '16 09:08

Exlord


1 Answers

1.

You could check if the string equals path.basename(string). Then it doesn't contain any path separators and is definitely not a file in another directory. That funtion doesn't go touch the filesystem and only inspects the string for platforms specific directory separator, and hence suits your performance needs.

string === path.basename(string)

2.

Another idea: if the identifiers follow a specific format, then create a regexp for the format and test each string for a match and proceed accordingly.

/identifierregex/.test(string)
like image 143
pspi Avatar answered Oct 02 '22 13:10

pspi