This is useful when you want to make a conditional branch by file name, or when you want to apply a filter.
I'm trying to figure out a way to extract only the trailing filenames from a given FullPath for both Windows and Unix systems. We will consider code for both Windows and Unix systems.
First, let's run the code in nodejs on Windows.
C:\02_data\01_dev\03_nodachisoftweb\contents\sample.js Let's get the file "sample.js" from the path of
var GetFilenameWindows = (path) => path.split('\\').pop(); var fulllpath_windows = "C:\\02_data\\01_dev\\03_nodachisoftweb\\contents\\sample.js"; console.log(GetFilename(fullpath_windows));
The result of the execution is as follows. The filename was retrieved properly.
> node sample.js sample.js
This is not enough to support Unix-like systems (Linux, MacOS, etc.), so let's define a version of the function that supports both, GetFilenameWindows.
var GetFilename = (path) => path.split('/').pop().split('\\').pop(); var fullpath_windows = "C:\\02_data\\01_dev\\03_nodachisoftweb\\contents\\sample.js"; var fullpath_unix = "/home/amaji/sample.js"; console.log("from Windows path : " + GetFilename(fullpath_windows)); console.log("from Linux path : " + GetFilename(fullpath_unix));
The result of the execution is as follows.
> node sample.js from Windows path : sample.js from Linux path : sample.js
There are many other ways to do this, but it's so simple that I'll just post this one for now.
Use the following function.
var GetFilename = (path) => path.split('/').pop().split('\\').pop();
Thank you for your message.
Sorry. The Error has occurred.We apologize for the inconvenience.Please try again in a few minutes or contact us via DM below.Twitter:@NodachiSoft_engName:
Send the following information to us. If you are happy with your submission, please click "Send". If you want to modify it, please click "Back".Name: