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

Exlord picture Exlord · Aug 16, 2016 · Viewed 9.3k times · Source

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.

Answer

pspi picture pspi · Aug 16, 2016

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)