How can I get the file name from an absolute path in Nodejs?
e.g. "foo.txt"
from "/var/www/foo.txt"
I know it works with a string operation, like fullpath.replace(/.+\//, '')
,
but I want to know is there an explicit way, like file.getName()
in Java?
Fs. basename(path) : returns the file name with extension. Fs. basename(path) : returns the file name without extension.
Definition and Usage. The path. basename() method returns the filename part of a file path.
__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.
Use the basename
method of the path
module:
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'
Here is the documentation the above example is taken from.
To get the file name portion of the file name, the basename method is used:
var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var file = path.basename(fileName);
console.log(file); // 'python.exe'
If you want the file name without the extension, you can pass the extension variable (containing the extension name) to the basename method telling Node to return only the name without the extension:
var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var extension = path.extname(fileName);
var file = path.basename(fileName,extension);
console.log(file); // 'python'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With